repo_name
stringlengths 4
116
| path
stringlengths 3
942
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
Workday/OpenFrame | ppapi/proxy/ppapi_command_buffer_proxy.cc | 10421 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ppapi/proxy/ppapi_command_buffer_proxy.h"
#include "base/numerics/safe_conversions.h"
#include "ppapi/proxy/ppapi_messages.h"
#include "ppapi/shared_impl/api_id.h"
#include "ppapi/shared_impl/host_resource.h"
#include "ppapi/shared_impl/proxy_lock.h"
namespace ppapi {
namespace proxy {
PpapiCommandBufferProxy::PpapiCommandBufferProxy(
const ppapi::HostResource& resource,
PluginDispatcher* dispatcher,
const gpu::Capabilities& capabilities,
const SerializedHandle& shared_state,
uint64_t command_buffer_id)
: command_buffer_id_(command_buffer_id),
capabilities_(capabilities),
resource_(resource),
dispatcher_(dispatcher),
next_fence_sync_release_(1),
pending_fence_sync_release_(0),
flushed_fence_sync_release_(0) {
shared_state_shm_.reset(
new base::SharedMemory(shared_state.shmem(), false));
shared_state_shm_->Map(shared_state.size());
InstanceData* data = dispatcher->GetInstanceData(resource.instance());
flush_info_ = &data->flush_info_;
}
PpapiCommandBufferProxy::~PpapiCommandBufferProxy() {
// gpu::Buffers are no longer referenced, allowing shared memory objects to be
// deleted, closing the handle in this process.
}
bool PpapiCommandBufferProxy::Initialize() {
return true;
}
gpu::CommandBuffer::State PpapiCommandBufferProxy::GetLastState() {
ppapi::ProxyLock::AssertAcquiredDebugOnly();
return last_state_;
}
int32 PpapiCommandBufferProxy::GetLastToken() {
ppapi::ProxyLock::AssertAcquiredDebugOnly();
TryUpdateState();
return last_state_.token;
}
void PpapiCommandBufferProxy::Flush(int32 put_offset) {
if (last_state_.error != gpu::error::kNoError)
return;
OrderingBarrier(put_offset);
FlushInternal();
}
void PpapiCommandBufferProxy::OrderingBarrier(int32 put_offset) {
if (last_state_.error != gpu::error::kNoError)
return;
if (flush_info_->flush_pending && flush_info_->resource != resource_) {
FlushInternal();
}
flush_info_->flush_pending = true;
flush_info_->resource = resource_;
flush_info_->put_offset = put_offset;
pending_fence_sync_release_ = next_fence_sync_release_ - 1;
}
void PpapiCommandBufferProxy::WaitForTokenInRange(int32 start, int32 end) {
TryUpdateState();
if (!InRange(start, end, last_state_.token) &&
last_state_.error == gpu::error::kNoError) {
bool success = false;
gpu::CommandBuffer::State state;
if (Send(new PpapiHostMsg_PPBGraphics3D_WaitForTokenInRange(
ppapi::API_ID_PPB_GRAPHICS_3D,
resource_,
start,
end,
&state,
&success)))
UpdateState(state, success);
}
DCHECK(InRange(start, end, last_state_.token) ||
last_state_.error != gpu::error::kNoError);
}
void PpapiCommandBufferProxy::WaitForGetOffsetInRange(int32 start, int32 end) {
TryUpdateState();
if (!InRange(start, end, last_state_.get_offset) &&
last_state_.error == gpu::error::kNoError) {
bool success = false;
gpu::CommandBuffer::State state;
if (Send(new PpapiHostMsg_PPBGraphics3D_WaitForGetOffsetInRange(
ppapi::API_ID_PPB_GRAPHICS_3D,
resource_,
start,
end,
&state,
&success)))
UpdateState(state, success);
}
DCHECK(InRange(start, end, last_state_.get_offset) ||
last_state_.error != gpu::error::kNoError);
}
void PpapiCommandBufferProxy::SetGetBuffer(int32 transfer_buffer_id) {
if (last_state_.error == gpu::error::kNoError) {
Send(new PpapiHostMsg_PPBGraphics3D_SetGetBuffer(
ppapi::API_ID_PPB_GRAPHICS_3D, resource_, transfer_buffer_id));
}
}
scoped_refptr<gpu::Buffer> PpapiCommandBufferProxy::CreateTransferBuffer(
size_t size,
int32* id) {
*id = -1;
if (last_state_.error != gpu::error::kNoError)
return NULL;
// Assuming we are in the renderer process, the service is responsible for
// duplicating the handle. This might not be true for NaCl.
ppapi::proxy::SerializedHandle handle(
ppapi::proxy::SerializedHandle::SHARED_MEMORY);
if (!Send(new PpapiHostMsg_PPBGraphics3D_CreateTransferBuffer(
ppapi::API_ID_PPB_GRAPHICS_3D, resource_,
base::checked_cast<uint32_t>(size), id, &handle))) {
if (last_state_.error == gpu::error::kNoError)
last_state_.error = gpu::error::kLostContext;
return NULL;
}
if (*id <= 0 || !handle.is_shmem()) {
if (last_state_.error == gpu::error::kNoError)
last_state_.error = gpu::error::kOutOfBounds;
return NULL;
}
scoped_ptr<base::SharedMemory> shared_memory(
new base::SharedMemory(handle.shmem(), false));
// Map the shared memory on demand.
if (!shared_memory->memory()) {
if (!shared_memory->Map(handle.size())) {
if (last_state_.error == gpu::error::kNoError)
last_state_.error = gpu::error::kOutOfBounds;
*id = -1;
return NULL;
}
}
return gpu::MakeBufferFromSharedMemory(shared_memory.Pass(), handle.size());
}
void PpapiCommandBufferProxy::DestroyTransferBuffer(int32 id) {
if (last_state_.error != gpu::error::kNoError)
return;
Send(new PpapiHostMsg_PPBGraphics3D_DestroyTransferBuffer(
ppapi::API_ID_PPB_GRAPHICS_3D, resource_, id));
}
void PpapiCommandBufferProxy::SetLock(base::Lock*) {
NOTIMPLEMENTED();
}
bool PpapiCommandBufferProxy::IsGpuChannelLost() {
NOTIMPLEMENTED();
return false;
}
gpu::CommandBufferNamespace PpapiCommandBufferProxy::GetNamespaceID() const {
return gpu::CommandBufferNamespace::GPU_IO;
}
uint64_t PpapiCommandBufferProxy::GetCommandBufferID() const {
return command_buffer_id_;
}
uint64_t PpapiCommandBufferProxy::GenerateFenceSyncRelease() {
return next_fence_sync_release_++;
}
bool PpapiCommandBufferProxy::IsFenceSyncRelease(uint64_t release) {
return release != 0 && release < next_fence_sync_release_;
}
bool PpapiCommandBufferProxy::IsFenceSyncFlushed(uint64_t release) {
return release <= flushed_fence_sync_release_;
}
bool PpapiCommandBufferProxy::IsFenceSyncFlushReceived(uint64_t release) {
return IsFenceSyncFlushed(release);
}
void PpapiCommandBufferProxy::SignalSyncToken(const gpu::SyncToken& sync_token,
const base::Closure& callback) {
NOTIMPLEMENTED();
}
bool PpapiCommandBufferProxy::CanWaitUnverifiedSyncToken(
const gpu::SyncToken* sync_token) {
return false;
}
uint32 PpapiCommandBufferProxy::InsertSyncPoint() {
uint32 sync_point = 0;
if (last_state_.error == gpu::error::kNoError) {
Send(new PpapiHostMsg_PPBGraphics3D_InsertSyncPoint(
ppapi::API_ID_PPB_GRAPHICS_3D, resource_, &sync_point));
}
return sync_point;
}
uint32 PpapiCommandBufferProxy::InsertFutureSyncPoint() {
uint32 sync_point = 0;
if (last_state_.error == gpu::error::kNoError) {
Send(new PpapiHostMsg_PPBGraphics3D_InsertFutureSyncPoint(
ppapi::API_ID_PPB_GRAPHICS_3D, resource_, &sync_point));
}
return sync_point;
}
void PpapiCommandBufferProxy::RetireSyncPoint(uint32 sync_point) {
if (last_state_.error == gpu::error::kNoError) {
Send(new PpapiHostMsg_PPBGraphics3D_RetireSyncPoint(
ppapi::API_ID_PPB_GRAPHICS_3D, resource_, sync_point));
}
}
void PpapiCommandBufferProxy::SignalSyncPoint(uint32 sync_point,
const base::Closure& callback) {
NOTREACHED();
}
void PpapiCommandBufferProxy::SignalQuery(uint32 query,
const base::Closure& callback) {
NOTREACHED();
}
gpu::Capabilities PpapiCommandBufferProxy::GetCapabilities() {
return capabilities_;
}
int32 PpapiCommandBufferProxy::CreateImage(ClientBuffer buffer,
size_t width,
size_t height,
unsigned internalformat) {
NOTREACHED();
return -1;
}
void PpapiCommandBufferProxy::DestroyImage(int32 id) {
NOTREACHED();
}
int32 PpapiCommandBufferProxy::CreateGpuMemoryBufferImage(
size_t width,
size_t height,
unsigned internalformat,
unsigned usage) {
NOTREACHED();
return -1;
}
bool PpapiCommandBufferProxy::Send(IPC::Message* msg) {
DCHECK(last_state_.error == gpu::error::kNoError);
// We need to hold the Pepper proxy lock for sync IPC, because the GPU command
// buffer may use a sync IPC with another lock held which could lead to lock
// and deadlock if we dropped the proxy lock here.
// http://crbug.com/418651
if (dispatcher_->SendAndStayLocked(msg))
return true;
last_state_.error = gpu::error::kLostContext;
return false;
}
void PpapiCommandBufferProxy::UpdateState(
const gpu::CommandBuffer::State& state,
bool success) {
// Handle wraparound. It works as long as we don't have more than 2B state
// updates in flight across which reordering occurs.
if (success) {
if (state.generation - last_state_.generation < 0x80000000U) {
last_state_ = state;
}
} else {
last_state_.error = gpu::error::kLostContext;
++last_state_.generation;
}
}
void PpapiCommandBufferProxy::TryUpdateState() {
if (last_state_.error == gpu::error::kNoError)
shared_state()->Read(&last_state_);
}
gpu::CommandBufferSharedState* PpapiCommandBufferProxy::shared_state() const {
return reinterpret_cast<gpu::CommandBufferSharedState*>(
shared_state_shm_->memory());
}
void PpapiCommandBufferProxy::FlushInternal() {
DCHECK(last_state_.error == gpu::error::kNoError);
DCHECK(flush_info_->flush_pending);
DCHECK_GE(pending_fence_sync_release_, flushed_fence_sync_release_);
IPC::Message* message = new PpapiHostMsg_PPBGraphics3D_AsyncFlush(
ppapi::API_ID_PPB_GRAPHICS_3D, flush_info_->resource,
flush_info_->put_offset);
// Do not let a synchronous flush hold up this message. If this handler is
// deferred until after the synchronous flush completes, it will overwrite the
// cached last_state_ with out-of-date data.
message->set_unblock(true);
Send(message);
flush_info_->flush_pending = false;
flush_info_->resource.SetHostResource(0, 0);
flushed_fence_sync_release_ = pending_fence_sync_release_;
}
} // namespace proxy
} // namespace ppapi
| bsd-3-clause |
tciuro/NanoStore | Classes/Public/NanoStore.h | 24679 | /*
NanoStore.h
NanoStore
Copyright (c) 2013 Webbo, Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions
and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions
and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of Webbo 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.
*/
#import "NSFNanoObjectProtocol.h"
#import "NSFNanoObject.h"
#import "NSFNanoGlobals.h"
#import "NSFNanoStore.h"
#import "NSFNanoPredicate.h"
#import "NSFNanoExpression.h"
#import "NSFNanoSearch.h"
#import "NSFNanoSortDescriptor.h"
#import "NSFNanoResult.h"
#import "NSFNanoBag.h"
#import "NSFNanoEngine.h"
#import "NSFNanoGlobals.h"
/**
@mainpage Welcome To NanoStore
@section whatis_sec What is NanoStore?
NanoStore is an open source, lightweight schema-less local key-value document store written in Objective-C for Mac OS X and iOS.
Relational databases tend to have a rich understanding of the structure of your data, but requires some planing beforehand and some level of
maintenance as well. NanoStore provides the flexibility that comes with key-value document stores, but still understands something about your data.
Because the data is key-value based, it can be accessed quickly and can grow as much as needed... all without ever worrying about the schema.
@section mainadv_sec Main advantages
- No SQL knowledge required
- Schema-less
- Key-value based storage
- Store your own custom objects
- Bags, a free-form relational system
- Fast, direct object manipulation
- Dynamic queries
- Full index support, inner-objects, embedded arrays and dictionaries
- Convenience methods to access, manipulate and maintain SQLite databases
- Full SQLite access available
- Mac OS X Lion 10.7 and iOS 5 ready
- iOS library runs on the device and simulator
- ARC compliant
@section latest_changes Latest changes
v2.5 - January 1, 2013
Starting with v2.5, the plist mechanism has been replaced with NSKeyedArchiver. There are several reasons for it: it's more compact, faster and uses less memory. Perhaps the most important reason is that it opens the possibility to store other data types.
NSNull is now supported. Big thanks to Wanny (https://github.com/mrwanny) for taking the time to improve this section of NanoStore.
@section installation_sec Installation
Building NanoStore is very easy. Just follow these steps:
- 1) Download NanoStore
- 2) Open the NanoStore.xcodeproj file
- 3) Select Universal > My Mac 64-bit or 32-bit from the Scheme popup
- 4) Build (Command-B)
Now you should have a new <i>Distribution</i> directory within the NanoStore project directory which contains the Universal static library (armv6/armv7/i386)
as well as the header files. To add it in your project, do the following:
- 1) Drag the Distribution directory to the Project Navigator panel
- 2) Include #import "NanoStore.h" in your code
@details <b>Example:</b>
@code
#import "NanoStore.h"
@implementation MyDemoAppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
// Instantiate a NanoStore and open it
NSFNanoStore *nanoStore = [NSFNanoStore createAndOpenStoreWithType:NSFMemoryStoreType path:nil error:nil];
...
@endcode
@note
If you want to add a dependency between your project and NanoStore so that it gets automatically rebuilt when
you update NanoStore, do the following (we'll assume your app is called "MyDemoApp"):
- 1) Select the MyDemoApp project in the Project Navigator
- 2) Select the MyDemoApp target
- 3) Expand the Target Dependencies box
- 4) Click "+" and add NanoStore
@section howitworks_sec How does NanoStore work?
The basic unit of data in NanoStore is called NanoObject. A NanoObject is any object which conforms to the NSFNanoObjectProtocol protocol.
At its core, a NanoObject is nothing more than a wrapper around two properties:
- A dictionary which contains the metadata (provided by the developer)
- A key (UUID) that identifies the object (provided by NanoStore)
The dictionary <i>must</i> be serializable, which means that only the following data types are allowed:
- NSArray
- NSDictionary
- NSString
- NSData (*)
- NSDate
- NSNumber
(*) The data type NSData is allowed, but it will be excluded from the indexing process.
To save and retrieve objects from the document store, NanoStore moves the data around by encapsulating it in NanoObjects. In order to store the objects in
NanoStore the developer has three options:
- Use the NSFNanoObject class directly
- Expand your custom classes by inheriting from NSFNanoObject
- Expand your custom classes by implementing the NSFNanoObjectProtocol protocol
Regardless of the route you decide to take, NanoStore will be able to store and retrieve objects from the document store seamlessly. The beauty of this system is that
NanoStore returns the object as it was stored, that is, instantiating an object of the class that was originally stored.
@note
If the document store is opened by another application that doesn't implement the object that was stored, NanoStore will instantiate a
NSFNanoObject instead, thus allowing the app to retrieve the data seamlessly. If the object is then updated by this application, the original
class name will be honored.
<b>Example:</b>
- App A stores an object of class <i>Car</i>.
- App B retrieves the object, but since it doesn't know anything about the class <i>Car</i>, NanoStore returns a NSFNanoObject.
- App B updates the object, perhaps adding a timestamp or additional information. NanoStore saves it as a <i>Car</i>, not as a NSFNanoObject.
- App A retrieves the updated object as a <i>Car</i> object, in exactly the same format as it was originally stored.
@section typesofdocumentstores Types of Document Stores
There are three types of document stores available in NanoStore: in-memory, temporary and file-based. These document stores are defined by the \link NSFGlobals::NSFNanoStoreType NSFNanoStoreType \endlink type:
- NSFMemoryStoreType: create the transient backing store in RAM. Its contents are lost when the process exits. Fastest, uses more RAM (*).
- NSFTemporaryStoreType: create a transient temporary backing store on disk. Its contents are lost when the process exits. Slower, uses less RAM than NSFMemoryStoreType.
- NSFPersistentStoreType:create a persistant backing store on disk. Slower, uses less RAM than NSFMemoryStoreType (*).
@note
Until the limit set by NSFNanoEngine's \link NSFNanoEngine::cacheSize - (NSUInteger)cacheSize \endlink has been reached, memory usage would be the same for in-memory store and on-disk store. When the size
of the store grows beyond \link NSFNanoEngine::cacheSize - (NSUInteger)cacheSize \endlink in-memory stores start to consume more memory than on-disk ones, because it has nowhere to push pages out of the cache.
Typically, most developers may want to create and open the document store. To do that, use NSFNanoStore's \link createAndOpenStoreWithType:path:error: + (NSFNanoStore *)createAndOpenStoreWithType:(NSFNanoStoreType)theType path:(NSString *)thePath error:(NSError * __autoreleasing *)outError \endlink method.
@details <b>Example:</b>
@code
// Instantiate an in-memory document store and open it. The path parameter is unused.
NSFNanoStore *nanoStore = [NSFNanoStore createAndOpenStoreWithType:NSFMemoryStoreType path:nil error:nil];
// Instantiate a temporary document store and open it. The path parameter is unused.
NSFNanoStore *nanoStore = [NSFNanoStore createAndOpenStoreWithType:NSFTemporaryStoreType path:nil error:nil];
// Instantiate a file-based document store and open it. The path parameter must be specified.
NSFNanoStore *nanoStore = [NSFNanoStore createAndOpenStoreWithType:NSFPersistentStoreType path:@"~/Desktop/myDatabase.database" error:nil];
@endcode
@note
In the case of file-based document stores, the file gets created automatically if it doesn't exist and then opened. If it already exists, it gets opened and made available for use right away.
There are instances where you may want to fine-tune the engine. Tunning the engine has to be performed before the document store is opened. Another method is available In NSFNanoStore for this
purpose: \link createStoreWithType:path: + (NSFNanoStore *)createStoreWithType:(NSFNanoStoreType)theType path:(NSString *)thePath \endlink.
@details <b>Example:</b>
@code
// Instantiate a file-based document store but don't open it right away. The path parameter must be specified.
NSFNanoStore *nanoStore = [NSFNanoStore createStoreWithType:NSFPersistentStoreType path:@"~/Desktop/myDatabase.database" error:nil];
// Obtain the engine
NSFNanoEngine *nanoStoreEngine = [nanoStore nanoStoreEngine];
// Set the synchronous mode setting
[nanoStoreEngine setSynchronousMode:SynchronousModeOff];
[nanoStoreEngine setEncodingType:NSFEncodingUTF16];
// Open the document store
[nanoStore openWithError:nil];
@endcode
@note
Check the section Performance Tips below for important information about how to get the most out of NanoStore.
@section workingwithnanoobject_sec Working with a NanoObject
There are three basic operations that NanoStore can perform with a NanoObject:
- Add it to the document store
- Update an existing object in the document store
- Remove it from the document store
To add an object, instantiate a \link NSFNanoObject::nanoObject NanoObject, \endlink populate it and add it to the document store.
@details <b>Example:</b>
@code
// Instantiate a NanoStore and open it
NSFNanoStore *nanoStore = [NSFNanoStore createAndOpenStoreWithType:NSFMemoryStoreType path:nil error:nil];
// Generate an empty NanoObject
NSFNanoObject *object = [NSFNanoObject nanoObject];
// Add some data
[object setObject:@"Doe" forKey:@"kLastName"];
[object setObject:@"John" forKey:@"kFirstName"];
[object setObject:[NSArray arrayWithObjects:@"[email protected]", @"[email protected]", nil] forKey:@"kEmails"];
// Add it to the document store
[nanoStore addObject:object error:nil];
// Close the document store
[nanoStore closeWithError:nil];
@endcode
Alternatively, you can instantiate a \link NSFNanoObject::nanoObject NanoObject \endlink providing a dictionary via \link NSFNanoObject::nanoObjectWithDictionary: + (NSFNanoObject*)nanoObjectWithDictionary:(NSDictionary *)theDictionary. \endlink
NanoStore will assign a UUID automatically when the \link NSFNanoObject::nanoObjectWithDictionary: NanoObject \endlink
is instantiated. This means that requesting the key from the \link NSFNanoObject::nanoObjectWithDictionary: NanoObject \endlink will return a valid UUID.
The same holds true for objects that inherit from NSFNanoObject. However, classes that implement the NSFNanoObjectProtocol protocol should
make sure they return a valid key via \link NSFNanoObjectProtocol::nanoObjectKey - (NSString *)nanoObjectKey \endlink
@warning
If an attempt is made to add or remove an object without a valid key, an exception of type \ref NSFGlobals::NSFNanoObjectBehaviorException
"NSFNanoObjectBehaviorException" will be raised.
To update an object, simply modify the object and add it to the document store. NanoStore will replace the existing object with the one being added.
@details <b>Example:</b>
@code
// Instantiate and open a NanoStore
NSFNanoStore *nanoStore = [NSFNanoStore createAndOpenStoreWithType:NSFMemoryStoreType path:nil error:nil];
// Assuming the dictionary exists, instantiate a NanoObject
NSDictionary *info = ...;
NSFNanoObject *object = [NSFNanoObject nanoObjectWithDictionary:info];
// Add the NanoObject to the document store
[nanoStore addObject:object error:nil];
// Update the NanoObject with new data
[object setObject:@"foo" forKey:@"SomeKey"];
// Update the NanoObject in the document store
[nanoStore addObject:object error:nil];
@endcode
To remove an object, there are several options available. The most common methods are found in NSFNanoStore:
- \link NSFNanoStore::removeObject:error: - (BOOL)removeObject:(id <NSFNanoObjectProtocol>)theObject error:(NSError * __autoreleasing *)outError \endlink
- \link NSFNanoStore::removeObjectsWithKeysInArray:error: - (BOOL)removeObjectsWithKeysInArray:(NSArray *)theKeys error:(NSError * __autoreleasing *)outError \endlink
- \link NSFNanoStore::removeObjectsInArray:error: - (BOOL)removeObjectsInArray:(NSArray *)theObjects error:(NSError * __autoreleasing *)outError \endlink
@details <b>Example:</b>
@code
// Instantiate and open a NanoStore
NSFNanoStore *nanoStore = [NSFNanoStore createAndOpenStoreWithType:NSFMemoryStoreType path:nil error:nil];
// Assuming the dictionary exists, instantiate a NanoObject
NSDictionary *info = ...;
NSFNanoObject *object = [NSFNanoObject nanoObjectWithDictionary:info];
// Add the NanoObject to the document store
[nanoStore addObject:object error:nil];
// Remove the object
[nanoStore removeObject:object error:nil];
// ... or you could pass the key instead
[nanoStore removeObjectsWithKeysInArray:[NSArray arrayWithObject:[object nanoObjectKey]] error:nil];
@endcode
@section notaflatworld_sec It's not a flat World
Most database solutions force the developer to think in a two-dimensional space (rows and columns), forcing the developer to plan the schema ahead of
time. This situation is not ideal because in most cases schema refinements could be required, oftentimes impacting the code as well.
NanoStore goes beyond that allowing the developer to store objects in their natural form. These objects must conform to the NSFNanoObjectProtocol
protocol, providing NanoStore with the NSDictionary that will be stored. By using a dictionary data can be inspected very quickly, and it also allows the
structure to be defined in a hierarchical fashion as well, due to the fact that it includes support for nested collections (of type NSDictionary and NSArray.)
Each inner-object is indexed automatically, thus allowing to quickly find objects which contain a specific key and/or value.
By default, NanoStore allows objects to be stored without any sense of relationship to other objects. This simple format, while powerful, is limited because
the developer has to keep track of the relationships among objects. Some applications may need to relate objects, some of them perhaps of different nature or class
type. This is exactly what NanoBag (represented by the NSFNanoBag class) does: it allows any object conforming to the NSFNanoObjectProtocol protocol to be
added to the bag. By saving the bag with one single call, the new and/or modified are taken care of seamlessly.
The NSFNanoBag API is rich, allowing the developer to add, remove, reload and undo its changes, deflate it (thus saving memory) and inflate it whenever it's
required. In addition, it provides methods to obtain all bags, specific bags matching some keys, and bags containing a specific object
(see NSFNanoStore for more information).
@section wherearetheobjects_sec Where are my objects?
While NSFNanoStore provides some convenience methods to obtain standard objects such as bags, the bulk of the search mechanism is handled by NSFNanoSearch.
The steps involved to perform a search are quite simple:
- 1) Instantiate a search object
- 2) Configure the search via its accessors
- 3) Obtain the results specifying whether objects or keys should be returned (*)
(*) If introspecting the data is needed, request objects. You should request keys if you need to feed the result to another method, such as NSFNanoStore
\link NSFNanoStore::removeObjectsWithKeysInArray:error: -(BOOL)removeObjectsWithKeysInArray:(NSArray *)theKeys error:(NSError * __autoreleasing *)outError \endlink method.
@details <b>Example: finding all objects with the attribute 'LastName' and value 'Doe'.</b>
@code
NSFNanoSearch *search = [NSFNanoSearch searchWithStore:nanoStore];
search.attribute = @"LastName";
search.match = NSFEqualTo;
search.value = @"Doe";
// Returns a dictionary with the UUID of the object (key) and the NanoObject (value).
NSDictionary *searchResults = [search searchObjectsWithReturnType:NSFReturnObjects error:nil];
@endcode
@details <b>Example: removing all objects with the attribute 'LastName' and value 'Doe'.</b>
@code
NSFNanoSearch *search = [NSFNanoSearch searchWithStore:nanoStore];
search.attribute = @"LastName";
search.match = NSFEqualTo;
search.value = @"Doe";
// Returns an array of matching UUIDs
NSArray *matchingKeys = [search searchObjectsWithReturnType:NSFReturnKeys error:nil];
// Remove the NanoObjects matching the selected UUIDs
NSError *outError = nil;
if ([nanoStore removeObjectsWithKeysInArray:matchingKeys error:&outError]) {
NSLog(@"The matching objects have been removed.");
} else {
NSLog(@"An error has occurred while removing the matching objects. Reason: %@", [outError localizedDescription]);
}
@endcode
Another cool feature is the possibility to invoke aggregated functions (count, avg, min, max and total) on the search results. Using the search snippet above,
calculating the average salary of all people with last name equal to 'Doe' is very easy.
@details <b>Example: calculating the average salary of all objects with the attribute 'LastName' and value 'Doe'.</b>
@code
NSFNanoSearch *search = [NSFNanoSearch searchWithStore:nanoStore];
search.attribute = @"LastName";
search.match = NSFEqualTo;
search.value = @"Doe";
float averageSalary = [[search aggregateOperation:NSFAverage onAttribute:@"Salary"]floatValue];
@endcode
@section sorting_sec Sorting
Combining search and sort is an extremely easy operation. There are two simple parts:
- 1) Preparing your classes for sorting
- 2) Setup a search operation and set its sort descriptors
@section preparesorting_sec Preparing your classes for sorting
Since NanoStore relies on KVC to perform the sorts, a hint of the location where the data lives within the object is required. Since KVC uses a key path to reach the element being sorted, we need a way to "point" to it. Most custom classes will return <i>self</i>, as is the case for NSFNanoBag:
@code
- (id)rootObject
{
return self;
}
@endcode
<i>Self</i> in this case represents the top level, the location where the variables <i>name</i>, <i>key</i> and <i>hasUnsavedChanges</i> are located:
@code
@interface NSFNanoBag : NSObject <NSFNanoObjectProtocol, NSCopying>
{
NSFNanoStore *store;
NSString *name;
NSString *key;
BOOL hasUnsavedChanges;
}
@endcode
Assume we have an object that represents a person and its root object is set to <i>self</i>, just as demonstrated above:
@code
@interface Person : NSFNanoObject
{
NSString *firstName;
NSString *lastName;
NSString *email;
}
@endcode
If we wanted to retrieve all the existing people with <i>firstName</i> equal to <i>John</i> sorted by <i>lastName</i> we would do the following:
@code
// Assume NanoStore has been opened elsewhere
NSFNanoStore *nanoStore = ...;
// Prepare the search
NSFNanoSearch *search = [NSFNanoSearch searchWithStore:nanoStore];
search.attribute = @"firstName";
search.match = NSFEqualTo;
search.value = @"John";
// Prepare and set the sort descriptor
NSFNanoSortDescriptor *sortByLastName = [[NSFNanoSortDescriptor alloc]initWithAttribute:@"lastName" ascending:YES];
search.sort = [NSArray arrayWithObject:sortByLastName];
// Perform the search
NSArray *searchResults = [search searchObjectsWithReturnType:NSFReturnObjects error:nil];
@endcode
@section paging_limit_sec Paging using Limit and Offset
SQLite provides a really cool feature called OFFSET that is usually used with a LIMIT clause.
The LIMIT clause is used to limit the number of results returned in a SQL statement. So if you have 1000 rows in table, but only want to return the first 10, you would do something like this:
@code
SELECT column FROM table LIMIT 10
@endcode
Now suppose you wanted to show results 11-20. With the OFFSET keyword it's just as easy. The following query will do:
@code
SELECT column FROM table LIMIT 10 OFFSET 10
@endcode
Using pagination is also quite easy with NanoStore. This example based on one of the unit tests provided with the NanoStore distro:
@code
NSFNanoStore *nanoStore = [NSFNanoStore createAndOpenStoreWithType:NSFMemoryStoreType path:nil error:nil];
// Assume we have added objects to the store
NSFNanoSearch *search = [NSFNanoSearch searchWithStore:nanoStore];
search.value = @"Barcelona";
search.match = NSFEqualTo;
search.limit = 5;
search.offset = 3;
NSDictionary *searchResults = [search searchObjectsWithReturnType:NSFReturnObjects error:nil];
// Assuming the query matches some results, NanoStore should have retrieved
// the first 5 records right after the 3rd one from the result set.
@endcode
@section performancetips_sec Performance Tips
NanoStore by defaults saves every object to disk one by one. To speed up inserts and edited objects, increase NSFNanoStore's \link NSFNanoStore::saveInterval saveInterval \endlink property.
@details <b>Example:</b>
@code
// Instantiate and open a NanoStore
NSFNanoStore *nanoStore = [NSFNanoStore createAndOpenStoreWithType:NSFMemoryStoreType path:nil error:nil];
// Increase the save interval
[nanoStore setSaveInterval:1000];
// Do a bunch of inserts and/or edits
// Don't forget that some objects could be lingering in memory. Force a save.
[nanoStore saveStoreAndReturnError:nil];
@endcode
@note If you set the saveInterval value to anything other one, keep in mind that some objects may still be left unsaved after being added or modified. To make sure they're saved properly, call \link NSFNanoStore::saveStoreAndReturnError: - (BOOL)saveStoreAndReturnError:(NSError * __autoreleasing *)outError \endlink.
Choosing a good saveInterval value is more art than science. While testing NanoStore using a medium-sized dictionary (iTunes' MP3 dictionary) setting saveInterval to 1000 resulted in the best performance. You may want to test with different numbers and fine-tune it for your data set.
@warning Setting saveInterval to a large number could result in decreased performance because SQLite's would have to spend more time reading the journal file and writing the changes to the database.
@section needhelp_sec Need more help?
There are two quick ways to find answers: reading the documentation and browsing the Unit tests.
While several attempts have been made to make the documentation easy to read and understand, it's far from perfect. If you find that the documentation is
incomplete, incorrect or needs some clarification, please file a bug. I'll appreciate it and correct it as soon as possible:
- NanoStore Documentation: http://dl.dropbox.com/u/2601212/NanoStore%202.0/html/index.html
- NanoStore Bug Tracker: https://github.com/tciuro/NanoStore/issues
- Twitter: http://twitter.com/nanostoredev
@section officialsourcerepo_sec Official Source Repository
The official repository for NanoStore is hosted on GitHub: https://github.com/tciuro/NanoStore
*/
| bsd-3-clause |
raquel-ucl/cartodb | lib/assets/javascripts/cartodb/common/dialogs/create/listing/datasets/remote_dataset_item_view.js | 3614 | var cdb = require('cartodb.js');
var $ = require('jquery');
var DatasetItem = require('./dataset_item_view');
var Utils = require('cdb.Utils');
var UploadConfig = require('../../../../background_importer/upload_config');
var pluralizeString = require('../../../../view_helpers/pluralize_string');
/**
* Remote dataset item view
*
*/
module.exports = DatasetItem.extend({
tagName: 'li',
className: 'DatasetsList-item',
events: {
'click .js-tag-link': '_onTagClick',
'click': '_toggleSelected'
},
initialize: function() {
this.elder('initialize');
this.template = cdb.templates.getTemplate('common/views/create/listing/remote_dataset_item');
this.table = new cdb.admin.CartoDBTableMetadata(this.model.get('external_source'));
},
render: function() {
var vis = this.model;
var table = this.table;
var tags = vis.get('tags') || [];
var description = vis.get('description') && Utils.stripHTML(markdown.toHTML(vis.get('description'))) || '';
var source = vis.get('source') && markdown.toHTML(vis.get('source')) || '';
var d = {
isRaster: vis.get('kind') === 'raster',
geometryType: table.geomColumnTypes().length > 0 ? table.geomColumnTypes()[0] : '',
title: vis.get('name'),
source: source,
description: description,
timeDiff: moment(vis.get('updated_at')).fromNow(),
tags: tags,
tagsCount: tags.length,
routerModel: this.routerModel,
maxTagsToShow: 3,
canImportDataset: this._canImportDataset(),
rowCount: undefined,
datasetSize: undefined
};
var rowCount = table.get('row_count');
if (rowCount >= 0) {
d.rowCount = ( rowCount < 10000 ? Utils.formatNumber(rowCount) : Utils.readizableNumber(rowCount) );
d.pluralizedRows = pluralizeString('Row', rowCount);
}
var datasetSize = table.get('size');
if (datasetSize >= 0) {
d.datasetSize = Utils.readablizeBytes(datasetSize, true);
}
this.$el.html(this.template(d));
this._setItemClasses();
this._renderTooltips();
return this;
},
_setItemClasses: function() {
// Item selected?
this.$el[ this.model.get('selected') ? 'addClass' : 'removeClass' ]('is--selected');
// Check if it is selectable
this.$el[ this._canImportDataset() ? 'addClass' : 'removeClass' ]('DatasetsList-item--selectable');
// Check if it is importable
this.$el[ this._canImportDataset() ? 'removeClass' : 'addClass' ]('DatasetsList-item--banned');
},
_renderTooltips: function() {
this.addView(
new cdb.common.TipsyTooltip({
el: this.$('.DatasetsList-itemStatus'),
title: function(e) {
return $(this).attr('data-title')
}
})
)
},
_onTagClick: function(ev) {
if (ev) {
this.killEvent(ev);
}
var tag = $(ev.target).val();
if (tag) {
this.routerModel.set({
tag: tag,
library: true
});
}
},
_canImportDataset: function() {
return ( this.user.get('remaining_byte_quota') * UploadConfig.fileTimesBigger ) >= ( this.table.get('size') || 0 )
},
_toggleSelected: function(ev) {
// Let links use default behaviour
if (ev.target.tagName !== 'A') {
this.killEvent(ev);
if (this._canImportDataset() && this.options.createModel.canSelect(this.model)) {
this.model.set('selected', !this.model.get('selected'));
}
}
}
});
| bsd-3-clause |
sfdazsdf/cpp-hiredis-cluster | include/container.h | 6201 | /*
* Copyright (c) 2015, Dmitrii Shinkevich <shinmail at gmail dot com>
*
* 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 Redis 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.
*/
#ifndef __libredisCluster__container__
#define __libredisCluster__container__
#include "cluster.h"
namespace RedisCluster {
template<typename redisConnection, typename ConnectionContainer>
class Cluster;
// Container for redis connections. Simple container defined here, it's not thread safe
// but can be replaced by user defined container as Cluster template class
template<typename redisConnection>
class DefaultContainer
{
typedef Cluster<redisConnection, DefaultContainer> RCluster;
typedef typename RCluster::SlotRange SlotRange;
typedef typename RCluster::Host Host;
typedef std::map <SlotRange, redisConnection*, typename RCluster::SlotComparator> ClusterNodes;
typedef std::map <Host, redisConnection*> RedirectConnections;
public:
DefaultContainer( typename RCluster::pt2RedisConnectFunc conn,
typename RCluster::pt2RedisFreeFunc disconn,
void* userData ) :
data_( userData ),
connect_(conn),
disconnect_(disconn)
{
}
~DefaultContainer()
{
disconnect();
}
inline
void insert( typename RCluster::SlotRange slots, const char* host, int port )
{
redisConnection* conn = connect_( host,
port,
data_ );
if( conn == NULL || conn->err )
{
throw ConnectionFailedException();
}
nodes_.insert( typename ClusterNodes::value_type(slots, conn) );
}
inline
typename RCluster::HostConnection insert( string host, string port )
{
string key( host + ":" + port );
try
{
return typename RCluster::HostConnection( key, connections_.at( key ) );
}
catch( const std::out_of_range &oor )
{
}
typename RCluster::HostConnection conn( key, connect_( host.c_str(), std::stoi(port), data_ ) );
if( conn.second != NULL && conn.second->err == 0 )
{
connections_.insert( conn );
}
return conn;
}
template<typename Storage>
inline static typename Storage::iterator searchBySlots( typename RCluster::SlotIndex index, Storage &storage )
{
typename RCluster::SlotRange range = { index + 1, 0 };
typename Storage::iterator node = storage.lower_bound( range );
// as with lower bound we find greater (next) slotrange, so now decrement
if( node != storage.begin() )
--node;
if ( node != storage.end() )
{
range = node->first;
if ( range.first > index || range.second < index )
{
throw NodeSearchException();
}
else
{
return node;
}
}
else
{
throw NodeSearchException();
}
}
inline
typename RCluster::SlotConnection getConnection( typename RCluster::SlotIndex index )
{
return *searchBySlots(index, nodes_);
}
// for a not multithreaded container this functions are dummy
inline void releaseConnection( typename RCluster::SlotConnection ) {}
inline void releaseConnection( typename RCluster::HostConnection ) {}
inline
void disconnect()
{
disconnect<ClusterNodes>( nodes_ );
disconnect<RedirectConnections>( connections_ );
}
template <typename T>
inline void disconnect(T &cons)
{
if( disconnect_ != NULL )
{
typename T::iterator it(cons.begin()), end(cons.end());
while ( it != end )
{
disconnect_( it->second );
++it;
}
}
cons.clear();
}
void* data_;
private:
typename RCluster::pt2RedisConnectFunc connect_;
typename RCluster::pt2RedisFreeFunc disconnect_;
RedirectConnections connections_;
ClusterNodes nodes_;
};
}
#endif /* defined(__libredisCluster__cluster__) */
| bsd-3-clause |
manguiatmarvin/osms | module/SanAuth/src/SanAuth/Model/MyAuthStorage.php | 1233 | <?php
namespace SanAuth\Model;
use Zend\Authentication\Storage;
class MyAuthStorage extends Storage\Session
{
public function setRememberMe($rememberMe = 0, $time = 1209600)
{
if ($rememberMe == 1) {
$this->session->getManager()->rememberMe($time);
}
}
public function forgetMe()
{
$this->session->getManager()->forgetMe();
}
/*Set tableGateway as save handler
muscreate a table session
CREATE TABLE IF NOT EXISTS `session` (
`id` char(32) NOT NULL DEFAULT '',
`name` char(32) NOT NULL DEFAULT '',
`modified` int(11) DEFAULT NULL,
`lifetime` int(11) DEFAULT NULL,
`data` text,
PRIMARY KEY (`id`,`name`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
*/
public function setDbHandler()
{
$tableGateway = new TableGateway('session', $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'));
$saveHandler = new DbTableGateway($tableGateway, new DbTableGatewayOptions());
//open session
$sessionConfig = new SessionConfig();
$saveHandler->open($sessionConfig->getOption('save_path'), $this->namespace);
$this->session->getManager()->setSaveHandler($saveHandler);
}
}
| bsd-3-clause |
manuelpichler/staticReflection | src/test/resources/files/regression/010498195/True.php | 50 | <?php
namespace bug_010498195;
class True {
} | bsd-3-clause |
STMicroelectronics/STMems_Standard_C_drivers | lsm6dsm_STdC/examples/lsm6dsm_sens_hub_lis2mdl.c | 14884 | /*
******************************************************************************
* @file sensor_hub_lis2mdl_no_fifo_simple.c
* @author Sensors Software Solution Team
* @brief This file show the simplest way enable a LIS2MDL mag connected
* to LSM6DSM I2C master interface (no FIFO support).
*
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2020 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under BSD 3-Clause license,
* the "License"; You may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
* opensource.org/licenses/BSD-3-Clause
*
******************************************************************************
*/
/*
* This example was developed using the following STMicroelectronics
* evaluation boards:
*
* - STEVAL_MKI109V3 + STEVAL-MKI189V1
* - NUCLEO_F411RE + STEVAL-MKI189V1
*
* and STM32CubeMX tool with STM32CubeF4 MCU Package
*
* Used interfaces:
*
* STEVAL_MKI109V3 - Host side: USB (Virtual COM)
* - Sensor side: SPI(Default) / I2C(supported)
*
* NUCLEO_STM32F411RE - Host side: UART(COM) to USB bridge
* - I2C(Default) / SPI(supported)
*
* If you need to run this example on a different hardware platform a
* modification of the functions: `platform_write`, `platform_read`,
* `tx_com` and 'platform_init' is required.
*
*/
/* STMicroelectronics evaluation boards definition
*
* Please uncomment ONLY the evaluation boards in use.
* If a different hardware is used please comment all
* following target board and redefine yours.
*/
//#define STEVAL_MKI109V3
#define NUCLEO_F411RE_X_NUCLEO_IKS01A2
#if defined(STEVAL_MKI109V3)
/* MKI109V3: Define communication interface */
#define SENSOR_BUS hspi2
/* MKI109V3: Vdd and Vddio power supply values */
#define PWM_3V3 915
#elif defined(NUCLEO_F411RE_X_NUCLEO_IKS01A2)
/* NUCLEO_F411RE_X_NUCLEO_IKS01A2: Define communication interface */
#define SENSOR_BUS hi2c1
#endif
/* Includes ------------------------------------------------------------------*/
#include <string.h>
#include <stdio.h>
#include "lsm6dsm_reg.h"
#include "lis2mdl_reg.h"
#if defined(NUCLEO_F411RE)
#include "stm32f4xx_hal.h"
#include "usart.h"
#include "gpio.h"
#include "i2c.h"
#elif defined(STEVAL_MKI109V3)
#include "stm32f4xx_hal.h"
#include "usbd_cdc_if.h"
#include "gpio.h"
#include "spi.h"
#include "tim.h"
#elif defined(SPC584B_DIS)
#include "components.h"
#endif
typedef union {
int16_t i16bit[3];
uint8_t u8bit[6];
} axis3bit16_t;
/* Define number of byte for each sensor sample */
#define OUT_XYZ_SIZE 6
/* Private variables ---------------------------------------------------------*/
static float acceleration_mg[3];
static float angular_rate_mdps[3];
static float magnetic_mG[3];
static axis3bit16_t data_raw_magnetic;
static axis3bit16_t data_raw_acceleration;
static axis3bit16_t data_raw_angular_rate;
static stmdev_ctx_t dev_ctx;
static stmdev_ctx_t mag_ctx;
static uint8_t whoamI, rst;
static uint8_t tx_buffer[1000];
/* Extern variables ----------------------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/*
* WARNING:
* Functions declare in this section are defined at the end of this file
* and are strictly related to the hardware platform used.
*
*/
static int32_t platform_write(void *handle, uint8_t reg, const uint8_t *bufp,
uint16_t len);
static int32_t platform_read(void *handle, uint8_t reg, uint8_t *bufp,
uint16_t len);
static void tx_com( uint8_t *tx_buffer, uint16_t len );
static void platform_delay(uint32_t ms);
static void platform_init(void);
/*
* Read data byte from internal register of a slave device connected
* to master I2C interface
*/
static int32_t lsm6dsm_read_lis2mdl_cx(void *ctx, uint8_t reg,
uint8_t *data,
uint16_t len)
{
axis3bit16_t data_raw_acceleration;
int32_t mm_error;
uint8_t drdy;
uint8_t i;
lsm6dsm_reg_t reg_endop;
uint8_t sh_reg[18];
lsm6dsm_sh_cfg_read_t val = {
.slv_add = LIS2MDL_I2C_ADD,
.slv_subadd = reg,
.slv_len = len,
};
(void)ctx;
/* Configure Sensor Hub to read LIS2MDL */
mm_error = lsm6dsm_sh_slv0_cfg_read(&dev_ctx, &val);
lsm6dsm_sh_num_of_dev_connected_set(&dev_ctx, LSM6DSM_SLV_0_1);
/* Enable I2C Master and I2C master Pull Up */
lsm6dsm_func_en_set(&dev_ctx, PROPERTY_ENABLE);
lsm6dsm_sh_master_set(&dev_ctx, PROPERTY_ENABLE);
/* Enable accelerometer to trigger Sensor Hub operation */
lsm6dsm_xl_data_rate_set(&dev_ctx, LSM6DSM_XL_ODR_104Hz);
/* Wait Sensor Hub operation flag set */
lsm6dsm_acceleration_raw_get(&dev_ctx, data_raw_acceleration.i16bit);
do {
lsm6dsm_xl_flag_data_ready_get(&dev_ctx, &drdy);
} while (!drdy);
do {
lsm6dsm_read_reg(&dev_ctx, LSM6DSM_FUNC_SRC1, ®_endop.byte, 1);
} while (!reg_endop.func_src1.sensorhub_end_op);
lsm6dsm_xl_data_rate_set(&dev_ctx, LSM6DSM_XL_ODR_OFF);
lsm6dsm_sh_read_data_raw_get(&dev_ctx,
(lsm6dsm_emb_sh_read_t *)&sh_reg);
lsm6dsm_func_en_set(&dev_ctx, PROPERTY_DISABLE);
lsm6dsm_sh_master_set(&dev_ctx, PROPERTY_DISABLE);
for (i = 0; i < len; i++) {
data[i] = sh_reg[i];
}
return mm_error;
}
/*
* Write data byte to internal register of a slave device connected
* to master I2C interface
*/
static int32_t lsm6dsm_write_lis2mdl_cx(void *ctx, uint8_t reg,
const uint8_t *data, uint16_t len)
{
axis3bit16_t data_raw_acceleration;
int32_t mm_error;
uint8_t drdy;
lsm6dsm_reg_t reg_endop;
lsm6dsm_sh_cfg_write_t val = {
.slv0_add = LIS2MDL_I2C_ADD,
.slv0_subadd = reg,
.slv0_data = *data,
};
(void)ctx;
(void)len;
/* Disable accelerometer */
lsm6dsm_xl_data_rate_set(&dev_ctx, LSM6DSM_XL_ODR_OFF);
/* Configure Sensor Hub to write */
mm_error = lsm6dsm_sh_cfg_write(&dev_ctx, &val);
/* Enable I2C Master and I2C master Pull Up */
lsm6dsm_func_en_set(&dev_ctx, PROPERTY_ENABLE);
lsm6dsm_sh_master_set(&dev_ctx, PROPERTY_ENABLE);
/* Enable accelerometer to trigger Sensor Hub operation */
lsm6dsm_xl_data_rate_set(&dev_ctx, LSM6DSM_XL_ODR_104Hz);
/* Wait Sensor Hub operation flag set */
lsm6dsm_acceleration_raw_get(&dev_ctx, data_raw_acceleration.i16bit);
do {
lsm6dsm_xl_flag_data_ready_get(&dev_ctx, &drdy);
} while (!drdy);
do {
lsm6dsm_read_reg(&dev_ctx, LSM6DSM_FUNC_SRC1, ®_endop.byte, 1);
} while (!reg_endop.func_src1.sensorhub_end_op);
lsm6dsm_xl_data_rate_set(&dev_ctx, LSM6DSM_XL_ODR_OFF);
lsm6dsm_func_en_set(&dev_ctx, PROPERTY_DISABLE);
lsm6dsm_sh_master_set(&dev_ctx, PROPERTY_DISABLE);
return mm_error;
}
/* Main Example --------------------------------------------------------------*/
void example_sensor_hub_lis2mdl_no_fifo_simple_lsm6dsm(void)
{
lsm6dsm_sh_cfg_read_t val = {
.slv_add = LIS2MDL_I2C_ADD,
.slv_subadd = LIS2MDL_OUTX_L_REG,
.slv_len = OUT_XYZ_SIZE,
};
dev_ctx.write_reg = platform_write;
dev_ctx.read_reg = platform_read;
dev_ctx.handle = &SENSOR_BUS;
/* Configure low level function to access to external device */
mag_ctx.read_reg = lsm6dsm_read_lis2mdl_cx;
mag_ctx.write_reg = lsm6dsm_write_lis2mdl_cx;
dev_ctx.handle = &SENSOR_BUS;
/* Init test platform */
platform_init();
/* Wait sensor boot time */
platform_delay(15);
/* Check device ID */
lsm6dsm_device_id_get(&dev_ctx, &whoamI);
if (whoamI != LSM6DSM_ID)
while (1) {
/* manage here device not found */
}
/* Restore default configuration */
lsm6dsm_reset_set(&dev_ctx, PROPERTY_ENABLE);
do {
lsm6dsm_reset_get(&dev_ctx, &rst);
} while (rst);
/* Some hardware require to enable pull up on master I2C interface */
//lsm6dsm_sh_pin_mode_set(&dev_ctx, LSM6DSM_INTERNAL_PULL_UP);
/* Check if LIS2MDL connected to Sensor Hub */
lis2mdl_device_id_get(&mag_ctx, &whoamI);
if (whoamI != LIS2MDL_ID) {
while (1) {
/* manage here device not found */
}
}
/* Set XL full scale and Gyro full scale */
lsm6dsm_xl_full_scale_set(&dev_ctx, LSM6DSM_2g);
lsm6dsm_gy_full_scale_set(&dev_ctx, LSM6DSM_2000dps);
/* Configure LIS2MDL on the I2C master line */
lis2mdl_operating_mode_set(&mag_ctx, LIS2MDL_CONTINUOUS_MODE);
lis2mdl_offset_temp_comp_set(&mag_ctx, PROPERTY_ENABLE);
lis2mdl_block_data_update_set(&mag_ctx, PROPERTY_ENABLE);
lis2mdl_data_rate_set(&mag_ctx, LIS2MDL_ODR_50Hz);
/* Prepare sensor hub to read data from external sensor */
lsm6dsm_sh_slv0_cfg_read(&dev_ctx, &val);
/* Configure Sensor Hub to read one slave */
lsm6dsm_sh_num_of_dev_connected_set(&dev_ctx, LSM6DSM_SLV_0);
/* Enable master and XL trigger */
lsm6dsm_func_en_set(&dev_ctx, PROPERTY_ENABLE);
lsm6dsm_sh_master_set(&dev_ctx, PROPERTY_ENABLE);
/* Set XL and Gyro Output Data Rate */
lsm6dsm_xl_data_rate_set(&dev_ctx, LSM6DSM_XL_ODR_52Hz);
lsm6dsm_gy_data_rate_set(&dev_ctx, LSM6DSM_GY_ODR_26Hz);
while (1) {
uint8_t drdy;
uint8_t emb_sh[18];
/* Read output only if new value is available */
lsm6dsm_xl_flag_data_ready_get(&dev_ctx, &drdy);
if (drdy) {
/* Read acceleration field data */
memset(data_raw_acceleration.u8bit, 0x0, 3 * sizeof(int16_t));
lsm6dsm_acceleration_raw_get(&dev_ctx, data_raw_acceleration.i16bit);
acceleration_mg[0] =
lsm6dsm_from_fs2g_to_mg(data_raw_acceleration.i16bit[0]);
acceleration_mg[1] =
lsm6dsm_from_fs2g_to_mg(data_raw_acceleration.i16bit[1]);
acceleration_mg[2] =
lsm6dsm_from_fs2g_to_mg(data_raw_acceleration.i16bit[2]);
sprintf((char *)tx_buffer,
"Acceleration [mg]:%4.2f\t%4.2f\t%4.2f\r\n",
acceleration_mg[0], acceleration_mg[1], acceleration_mg[2]);
tx_com(tx_buffer, strlen((char const *)tx_buffer));
/* Read magnetic data from sensor hub register: XL trigger a new read to
* mag sensor
*/
lsm6dsm_sh_read_data_raw_get(&dev_ctx,
(lsm6dsm_emb_sh_read_t *)&emb_sh);
memcpy((uint8_t *)&data_raw_magnetic,
(uint8_t *)&emb_sh[0],
OUT_XYZ_SIZE);
magnetic_mG[0] = lis2mdl_from_lsb_to_mgauss(
data_raw_magnetic.i16bit[0]);
magnetic_mG[1] = lis2mdl_from_lsb_to_mgauss(
data_raw_magnetic.i16bit[1]);
magnetic_mG[2] = lis2mdl_from_lsb_to_mgauss(
data_raw_magnetic.i16bit[2]);
sprintf((char *)tx_buffer, "Mag [mG]:%4.2f\t%4.2f\t%4.2f\r\n",
magnetic_mG[0], magnetic_mG[1], magnetic_mG[2]);
tx_com(tx_buffer, strlen((char const *)tx_buffer));
}
lsm6dsm_gy_flag_data_ready_get(&dev_ctx, &drdy);
if (drdy) {
/* Read angular rate field data */
memset(data_raw_angular_rate.u8bit, 0x0, 3 * sizeof(int16_t));
lsm6dsm_angular_rate_raw_get(&dev_ctx, data_raw_angular_rate.i16bit);
angular_rate_mdps[0] =
lsm6dsm_from_fs2000dps_to_mdps(data_raw_angular_rate.i16bit[0]);
angular_rate_mdps[1] =
lsm6dsm_from_fs2000dps_to_mdps(data_raw_angular_rate.i16bit[1]);
angular_rate_mdps[2] =
lsm6dsm_from_fs2000dps_to_mdps(data_raw_angular_rate.i16bit[2]);
sprintf((char *)tx_buffer,
"Angular rate [mdps]:%4.2f\t%4.2f\t%4.2f\r\n",
angular_rate_mdps[0],
angular_rate_mdps[1],
angular_rate_mdps[2]);
tx_com(tx_buffer, strlen((char const *)tx_buffer));
}
}
}
/*
* @brief Write generic device register (platform dependent)
*
* @param handle customizable argument. In this examples is used in
* order to select the correct sensor bus handler.
* @param reg register to write
* @param bufp pointer to data to write in register reg
* @param len number of consecutive register to write
*
*/
static int32_t platform_write(void *handle, uint8_t reg, const uint8_t *bufp,
uint16_t len)
{
#if defined(NUCLEO_F411RE)
HAL_I2C_Mem_Write(handle, LSM6DSM_I2C_ADD_H, reg,
I2C_MEMADD_SIZE_8BIT, (uint8_t*) bufp, len, 1000);
#elif defined(STEVAL_MKI109V3)
HAL_GPIO_WritePin(CS_up_GPIO_Port, CS_up_Pin, GPIO_PIN_RESET);
HAL_SPI_Transmit(handle, ®, 1, 1000);
HAL_SPI_Transmit(handle, (uint8_t*) bufp, len, 1000);
HAL_GPIO_WritePin(CS_up_GPIO_Port, CS_up_Pin, GPIO_PIN_SET);
#elif defined(SPC584B_DIS)
i2c_lld_write(handle, LSM6DSM_I2C_ADD_H & 0xFE, reg, (uint8_t*) bufp, len);
#endif
return 0;
}
/*
* @brief Read generic device register (platform dependent)
*
* @param handle customizable argument. In this examples is used in
* order to select the correct sensor bus handler.
* @param reg register to read
* @param bufp pointer to buffer that store the data read
* @param len number of consecutive register to read
*
*/
static int32_t platform_read(void *handle, uint8_t reg, uint8_t *bufp,
uint16_t len)
{
#if defined(NUCLEO_F411RE)
HAL_I2C_Mem_Read(handle, LSM6DSM_I2C_ADD_H, reg,
I2C_MEMADD_SIZE_8BIT, bufp, len, 1000);
#elif defined(STEVAL_MKI109V3)
reg |= 0x80;
HAL_GPIO_WritePin(CS_up_GPIO_Port, CS_up_Pin, GPIO_PIN_RESET);
HAL_SPI_Transmit(handle, ®, 1, 1000);
HAL_SPI_Receive(handle, bufp, len, 1000);
HAL_GPIO_WritePin(CS_up_GPIO_Port, CS_up_Pin, GPIO_PIN_SET);
#elif defined(SPC584B_DIS)
i2c_lld_read(handle, LSM6DSM_I2C_ADD_H & 0xFE, reg, bufp, len);
#endif
return 0;
}
/*
* @brief Send buffer to console (platform dependent)
*
* @param tx_buffer buffer to transmit
* @param len number of byte to send
*
*/
static void tx_com(uint8_t *tx_buffer, uint16_t len)
{
#if defined(NUCLEO_F411RE)
HAL_UART_Transmit(&huart2, tx_buffer, len, 1000);
#elif defined(STEVAL_MKI109V3)
CDC_Transmit_FS(tx_buffer, len);
#elif defined(SPC584B_DIS)
sd_lld_write(&SD2, tx_buffer, len);
#endif
}
/*
* @brief platform specific delay (platform dependent)
*
* @param ms delay in ms
*
*/
static void platform_delay(uint32_t ms)
{
#if defined(NUCLEO_F411RE) | defined(STEVAL_MKI109V3)
HAL_Delay(ms);
#elif defined(SPC584B_DIS)
osalThreadDelayMilliseconds(ms);
#endif
}
/*
* @brief platform specific initialization (platform dependent)
*/
static void platform_init(void)
{
#if defined(STEVAL_MKI109V3)
TIM3->CCR1 = PWM_3V3;
TIM3->CCR2 = PWM_3V3;
HAL_TIM_PWM_Start(&htim3, TIM_CHANNEL_1);
HAL_TIM_PWM_Start(&htim3, TIM_CHANNEL_2);
HAL_Delay(1000);
#endif
}
| bsd-3-clause |
ovh/cds | engine/api/workflow/dao_audit.go | 1322 | package workflow
import (
"github.com/go-gorp/gorp"
"github.com/ovh/cds/sdk"
)
// InsertAudit insert a workflow audit
func InsertAudit(db gorp.SqlExecutor, a *sdk.AuditWorkflow) error {
audit := auditWorkflow(*a)
if err := db.Insert(&audit); err != nil {
return sdk.WrapError(err, "Unable to insert audit")
}
a.ID = audit.ID
return nil
}
// LoadAudits Load audits for the given workflow
func LoadAudits(db gorp.SqlExecutor, workflowID int64) ([]sdk.AuditWorkflow, error) {
query := `
SELECT * FROM workflow_audit WHERE workflow_id = $1 ORDER BY created DESC
`
var audits []auditWorkflow
if _, err := db.Select(&audits, query, workflowID); err != nil {
return nil, sdk.WrapError(err, "Unable to load audits")
}
workflowAudits := make([]sdk.AuditWorkflow, len(audits))
for i := range audits {
workflowAudits[i] = sdk.AuditWorkflow(audits[i])
}
return workflowAudits, nil
}
// LoadAudit Load audit for the given workflow
func LoadAudit(db gorp.SqlExecutor, auditID int64, workflowID int64) (sdk.AuditWorkflow, error) {
var audit auditWorkflow
if err := db.SelectOne(&audit, "SELECT * FROM workflow_audit WHERE id = $1 AND workflow_id = $2", auditID, workflowID); err != nil {
return sdk.AuditWorkflow{}, sdk.WrapError(err, "Unable to load audit")
}
return sdk.AuditWorkflow(audit), nil
}
| bsd-3-clause |
hholi/phd2 | cameras/ASICamera2.h | 25949 | /**************************************************
this is the second version of release ASI Camera ASIs
any question feel free contact us:[email protected]
here is the suggested procedure to operate the camera.
--> ASIGetNumOfConnectedCameras
----> ASIGetCameraProperty for each camera
--> ASIOpenCamera
--> ASIGetNumOfControls
----> ASIGetControlCaps for each contronl and set or get value from them
--> ASISetROIFormat
--> ASIStartVideoCapture
//this is recommended to do in another thread
while(1)
{
ASIGetVideoData
...
}
***************************************************/
#ifndef ASICAMERA2_H
#define ASICAMERA2_H
#ifdef _WINDOWS
#define ASICAMERA_API __declspec(dllexport)
#else
#define ASICAMERA_API
#endif
typedef enum ASI_BAYER_PATTERN{
ASI_BAYER_RG=0,
ASI_BAYER_BG,
ASI_BAYER_GR,
ASI_BAYER_GB
}ASI_BAYER_PATTERN;
typedef enum ASI_IMG_TYPE{ //Supported Video Format
ASI_IMG_RAW8 = 0,
ASI_IMG_RGB24,
ASI_IMG_RAW16,
ASI_IMG_Y8,
ASI_IMG_END = -1
}ASI_IMG_TYPE;
typedef enum ASI_GUIDE_DIRECTION{ //Guider Direction
ASI_GUIDE_NORTH=0,
ASI_GUIDE_SOUTH,
ASI_GUIDE_EAST,
ASI_GUIDE_WEST
}ASI_GUIDE_DIRECTION;
typedef enum ASI_FLIP_STATUS {
ASI_FLIP_NONE = 0,//: original
ASI_FLIP_HORIZ,//: horizontal flip
ASI_FLIP_VERT,// vertical flip
ASI_FLIP_BOTH,//:both horizontal and vertical flip
}ASI_FLIP_STATUS;
typedef enum ASI_ERROR_CODE{ //ASI ERROR CODE
ASI_SUCCESS=0,
ASI_ERROR_INVALID_INDEX, //no camera connected or index value out of boundary
ASI_ERROR_INVALID_ID, //invalid ID
ASI_ERROR_INVALID_CONTROL_TYPE, //invalid control type
ASI_ERROR_CAMERA_CLOSED, //camera didn't open
ASI_ERROR_CAMERA_REMOVED, //failed to find the camera, maybe the camera has been removed
ASI_ERROR_INVALID_PATH, //cannot find the path of the file
ASI_ERROR_INVALID_FILEFORMAT,
ASI_ERROR_INVALID_SIZE, //wrong video format size
ASI_ERROR_INVALID_IMGTYPE, //unsupported image formate
ASI_ERROR_OUTOF_BOUNDARY, //the image is out of boundary
ASI_ERROR_TIMEOUT, //timeout
ASI_ERROR_INVALID_SENQUENCE,//stop capture first
ASI_ERROR_BUFFER_TOO_SMALL, //buffer size is not big enough
ASI_ERROR_VIDEO_MODE_ACTIVE,
ASI_ERROR_EXPOSURE_IN_PROGRESS,
ASI_ERROR_GENERAL_ERROR,//general error, eg: value is out of valid range
ASI_ERROR_END
}ASI_ERROR_CODE;
typedef enum ASI_BOOL{
ASI_FALSE =0,
ASI_TRUE
}ASI_BOOL;
typedef struct _ASI_CAMERA_INFO
{
char Name[64]; //the name of the camera, you can display this to the UI
int CameraID; //this is used to control everything of the camera in other functions
long MaxHeight; //the max height of the camera
long MaxWidth; //the max width of the camera
ASI_BOOL IsColorCam;
ASI_BAYER_PATTERN BayerPattern;
int SupportedBins[16]; //1 means bin1 which is supported by every camera, 2 means bin 2 etc.. 0 is the end of supported binning method
ASI_IMG_TYPE SupportedVideoFormat[8]; //this array will content with the support output format type.IMG_END is the end of supported video format
double PixelSize; //the pixel size of the camera, unit is um. such like 5.6um
ASI_BOOL MechanicalShutter;
ASI_BOOL ST4Port;
ASI_BOOL IsCoolerCam;
ASI_BOOL IsUSB3Host;
ASI_BOOL IsUSB3Camera;
float ElecPerADU;
int OffsetLGain;
int OffsetHGain;
char Unused[16];
} ASI_CAMERA_INFO;
typedef enum ASI_CONTROL_TYPE{ //Control type//
ASI_GAIN = 0,
ASI_EXPOSURE,
ASI_GAMMA,
ASI_WB_R,
ASI_WB_B,
ASI_BRIGHTNESS,
ASI_BANDWIDTHOVERLOAD,
ASI_OVERCLOCK,
ASI_TEMPERATURE,// return 10*temperature
ASI_FLIP,
ASI_AUTO_MAX_GAIN,
ASI_AUTO_MAX_EXP,
ASI_AUTO_MAX_BRIGHTNESS,
ASI_HARDWARE_BIN,
ASI_HIGH_SPEED_MODE,
ASI_COOLER_POWER_PERC,
ASI_TARGET_TEMP,
ASI_COOLER_ON
}ASI_CONTROL_TYPE;
typedef struct _ASI_CONTROL_CAPS
{
char Name[64]; //the name of the Control like Exposure, Gain etc..
char Description[128]; //description of this control
long MaxValue;
long MinValue;
long DefaultValue;
ASI_BOOL IsAutoSupported; //support auto set 1, don't support 0
ASI_BOOL IsWritable; //some control like temperature can only be read by some cameras
ASI_CONTROL_TYPE ControlType;//this is used to get value and set value of the control
char Unused[32];
} ASI_CONTROL_CAPS;
typedef enum ASI_EXPOSURE_STATUS {
ASI_EXP_IDLE = 0,//: idle states, you can start exposure now
ASI_EXP_WORKING,//: exposing
ASI_EXP_SUCCESS,// exposure finished and waiting for download
ASI_EXP_FAILED,//:exposure failed, you need to start exposure again
}ASI_EXPOSURE_STATUS;
typedef struct _ASI_ID{
unsigned char id[8];
}ASI_ID;
#ifndef __cplusplus
#define ASI_CONTROL_TYPE int
#define ASI_BOOL int
#define ASI_ERROR_CODE int
#define ASI_FLIP_STATUS int
#define ASI_IMG_TYPE int
#define ASI_GUIDE_DIRECTION int
#define ASI_BAYER_PATTERN int
#endif
#ifdef __cplusplus
extern "C" {
#endif
/***************************************************************************
Descriptions£º
this should be the first API to be called
get number of connected ASI cameras,
Paras£º
return£ºnumber of connected ASI cameras. 1 means 1 camera connected.
***************************************************************************/
ASICAMERA_API int ASIGetNumOfConnectedCameras();
/***************************************************************************
Descriptions£º
get the property of the connected cameras, you can do this without open the camera.
here is the sample code:
int iNumofConnectCameras = ASIGetNumOfConnectedCameras();
ASI_CAMERA_INFO **ppASICameraInfo = (ASI_CAMERA_INFO *)malloc(sizeof(ASI_CAMERA_INFO *)*iNumofConnectCameras);
for(int i = 0; i < iNumofConnectCameras; i++)
ASIGetCameraProperty(pASICameraInfo[i], i);
Paras£º
ASI_CAMERA_INFO *pASICameraInfo: Pointer to structure containing the property of camera
user need to malloc the buffer
int iCameraIndex: 0 means the first connect camera, 1 means the second connect camera
return£º
ASI_SUCCESS: Operation is successful
ASI_ERROR_INVALID_INDEX :no camera connected or index value out of boundary
***************************************************************************/
ASICAMERA_API ASI_ERROR_CODE ASIGetCameraProperty(ASI_CAMERA_INFO *pASICameraInfo, int iCameraIndex);
/***************************************************************************
Descriptions£º
open the camera before any operation to the camera, this function may take some while because it will init the camera too
All APIs below need to open the camera at first.
Paras£º
int CameraID: this is get from the camera property use the API ASIGetCameraProperty
return£º
ASI_SUCCESS: Operation is successful
ASI_ERROR_INVALID_ID :no camera connected or index value out of boundary
ASI_ERROR_CAMERA_REMOVED: failed to find the camera, maybe camera has been removed
***************************************************************************/
ASICAMERA_API ASI_ERROR_CODE ASIOpenCamera(int iCameraID);
/***************************************************************************
Descriptions£º
you need to close the camera to free all the resource
Paras£º
int CameraID: this is get from the camera property use the API ASIGetCameraProperty
return£º
ASI_SUCCESS :it will return success even the camera already closed
ASI_ERROR_INVALID_ID :no camera connected or index value out of boundary
***************************************************************************/
ASICAMERA_API ASI_ERROR_CODE ASICloseCamera(int iCameraID);
/***************************************************************************
Descriptions£º
Get number of controls available for this camera. the camera need be opened at first.
Paras£º
int CameraID: this is get from the camera property use the API ASIGetCameraProperty
int * piNumberOfControls: pointer to an int to save the number of controls
return:
ASI_SUCCESS : Operation is successful
ASI_ERROR_CAMERA_CLOSED : camera didn't open
ASI_ERROR_INVALID_ID :no camera connected or index value out of boundary
***************************************************************************/
ASICAMERA_API ASI_ERROR_CODE ASIGetNumOfControls(int iCameraID, int * piNumberOfControls);
/***************************************************************************
Descriptions£º
Get controls property available for this camera. the camera need be opened at first.
user need to malloc and maintain the buffer.
Paras£º
int CameraID: this is get from the camera property use the API ASIGetCameraProperty
int iControlIndex:
ASI_CONTROL_CAPS * pControlCaps: Pointer to structure containing the property of the control
user need to malloc the buffer
return:
ASI_SUCCESS : Operation is successful
ASI_ERROR_CAMERA_CLOSED : camera didn't open
ASI_ERROR_INVALID_ID :no camera connected or index value out of boundary
***************************************************************************/
ASICAMERA_API ASI_ERROR_CODE ASIGetControlCaps(int iCameraID, int iControlIndex, ASI_CONTROL_CAPS * pControlCaps);
/***************************************************************************
Descriptions£º
Get controls property value and auto value
note:the value of the temperature is the float value * 10 to convert it to long type, control name is "Temperature"
because long is the only type for control
Paras£º
int CameraID: this is get from the camera property use the API ASIGetCameraProperty
int ControlType: this is get from control property use the API ASIGetControlCaps
long *plValue: pointer to the value you want to save the value get from control
ASI_BOOL *pbAuto: pointer to the ASI_BOOL type
return:
ASI_SUCCESS : Operation is successful
ASI_ERROR_CAMERA_CLOSED : camera didn't open
ASI_ERROR_INVALID_ID :no camera connected or index value out of boundary
ASI_ERROR_INVALID_CONTROL_TYPE, //invalid Control type
***************************************************************************/
ASICAMERA_API ASI_ERROR_CODE ASIGetControlValue(int iCameraID, ASI_CONTROL_TYPE ControlType, long *plValue, ASI_BOOL *pbAuto);
/***************************************************************************
Descriptions£º
Set controls property value and auto value
it will return success and set the max value or min value if the value is beyond the boundary
Paras£º
int CameraID: this is get from the camera property use the API ASIGetCameraProperty
int ControlType: this is get from control property use the API ASIGetControlCaps
long lValue: the value set to the control
ASI_BOOL bAuto: set the control auto
return:
ASI_SUCCESS : Operation is successful
ASI_ERROR_CAMERA_CLOSED : camera didn't open
ASI_ERROR_INVALID_ID :no camera connected or index value out of boundary
ASI_ERROR_INVALID_CONTROL_TYPE, //invalid Control type
ASI_ERROR_GENERAL_ERROR,//general error, eg: value is out of valid range
***************************************************************************/
ASICAMERA_API ASI_ERROR_CODE ASISetControlValue(int iCameraID, ASI_CONTROL_TYPE ControlType, long lValue, ASI_BOOL bAuto);
/***************************************************************************
Descriptions£º
set the ROI area before capture.
you must stop capture before call it.
the width and height is the value after binning.
ie. you need to set width to 640 and height to 480 if you want to run at 640X480@BIN2
ASI120's data size must be times of 1024 which means width*height%1024=0
Paras£º
int CameraID: this is get from the camera property use the API ASIGetCameraProperty
int iWidth, the width of the ROI area please make sure that width*height%1024=0
int iHeight, the height of the ROI area. please make sure that width*height%1024=0
int iBin, binning method. bin1=1, bin2=2
ASI_IMG_TYPE Img_type: the output format you want
return:
ASI_SUCCESS : Operation is successful
ASI_ERROR_CAMERA_CLOSED : camera didn't open
ASI_ERROR_INVALID_ID :no camera connected or index value out of boundary
ASI_ERROR_INVALID_SIZE, //wrong video format size
ASI_ERROR_INVALID_IMGTYPE, //unsupported image format, make sure iWidth and iHeight and binning is set correct
***************************************************************************/
ASICAMERA_API ASI_ERROR_CODE ASISetROIFormat(int iCameraID, int iWidth, int iHeight, int iBin, ASI_IMG_TYPE Img_type);
/***************************************************************************
Descriptions£º
Get the current ROI area setting .
Paras£º
int CameraID: this is get from the camera property use the API ASIGetCameraProperty
int *piWidth, pointer to the width of the ROI area
int *piHeight, pointer to the height of the ROI area.
int *piBin, pointer to binning method. bin1=1, bin2=2
ASI_IMG_TYPE *pImg_type: pointer to the output format
return:
ASI_SUCCESS : Operation is successful
ASI_ERROR_CAMERA_CLOSED : camera didn't open
ASI_ERROR_INVALID_ID :no camera connected or index value out of boundary
***************************************************************************/
ASICAMERA_API ASI_ERROR_CODE ASIGetROIFormat(int iCameraID, int *piWidth, int *piHeight, int *piBin, ASI_IMG_TYPE *pImg_type);
/***************************************************************************
Descriptions£º
Set the start position of the ROI area.
you can call this API to move the ROI area when video is streaming
the camera will set the ROI area to the center of the full image as default
at bin2 or bin3 mode, the position is relative to the image after binning
Paras£º
int CameraID: this is get from the camera property use the API ASIGetCameraProperty
int iStartX, pointer to the start X
int iStartY pointer to the start Y
return:
ASI_SUCCESS : Operation is successful
ASI_ERROR_CAMERA_CLOSED : camera didn't open
ASI_ERROR_INVALID_ID :no camera connected or index value out of boundary
ASI_ERROR_OUTOF_BOUNDARY: the start x and start y make the image out of boundary
***************************************************************************/
ASICAMERA_API ASI_ERROR_CODE ASISetStartPos(int iCameraID, int iStartX, int iStartY);
/***************************************************************************
Descriptions£º
Get the start position of current ROI area .
Paras£º
int CameraID: this is get from the camera property use the API ASIGetCameraProperty
int *piStartX, pointer to the start X
int *piStartY pointer to the start Y
return:
ASI_SUCCESS : Operation is successful
ASI_ERROR_CAMERA_CLOSED : camera didn't open
ASI_ERROR_INVALID_ID :no camera connected or index value out of boundary
***************************************************************************/
ASICAMERA_API ASI_ERROR_CODE ASIGetStartPos(int iCameraID, int *piStartX, int *piStartY);
/***************************************************************************
Descriptions£º
Get the droped frames .
drop frames happen when USB is traffic or harddisk write speed is slow
it will reset to 0 after stop capture
Paras£º
int CameraID: this is get from the camera property use the API ASIGetCameraProperty
int *piDropFrames pointer to drop frames
return:
ASI_SUCCESS : Operation is successful
ASI_ERROR_CAMERA_CLOSED : camera didn't open
ASI_ERROR_INVALID_ID :no camera connected or index value out of boundary
***************************************************************************/
ASICAMERA_API ASI_ERROR_CODE ASIGetDroppedFrames(int iCameraID,int *piDropFrames);
/***************************************************************************
Descriptions£º
provide a dark file's path to the function and enable dark subtract
this is used when there is hot pixel or need to do long exposure
you'd better make this dark file from the "dark subtract" funtion
of the "video capture filter" directshow page.
the dark file's size should be the same of camera's max width and height
and should be RGB8 raw format.it will on even you changed the ROI setting
it only correct the hot pixels if out put is 16bit.
it will be remembered in registry. so "Dark subtract" is on next time if you close your app.
Paras£º
int CameraID: this is get from the camera property use the API ASIGetCameraProperty
char *pcBMPPath: the path to the bmp dark file.
bIsSubDarkWorking: check if subtracting dark is working, wrong dark file path may cause it not work
return£º
ASI_SUCCESS : Operation is successful
ASI_ERROR_INVALID_ID :no camera connected or index value out of boundary
ASI_ERROR_CAMERA_CLOSED : camera didn't open
ASI_ERROR_INVALID_PATH, //cannot find the path of the file
ASI_ERROR_INVALID_FILEFORMAT, //the dark file's size should be the same of camera's max width and height
***************************************************************************/
ASICAMERA_API ASI_ERROR_CODE ASIEnableDarkSubtract(int iCameraID, char *pcBMPPath, ASI_BOOL *bIsSubDarkWorking);
/***************************************************************************
Descriptions£º
Disable the dark subtract function.
you'd better call it at start if you don't want to use it.
because dark subtract function is remembered on windows platform
Paras£º
int CameraID: this is get from the camera property use the API ASIGetCameraProperty
return:
ASI_SUCCESS : Operation is successful
ASI_ERROR_INVALID_ID :no camera connected or index value out of boundary
ASI_ERROR_CAMERA_CLOSED : camera didn't open
***************************************************************************/
ASICAMERA_API ASI_ERROR_CODE ASIDisableDarkSubtract(int iCameraID);
/***************************************************************************
Descriptions£º
Start video capture
then you can get the data from the API ASIGetVideoData
Paras£º
int CameraID: this is get from the camera property use the API ASIGetCameraProperty
return:
ASI_SUCCESS : Operation is successful, it will return success if already started
ASI_ERROR_CAMERA_CLOSED : camera didn't open
ASI_ERROR_INVALID_ID :no camera connected or index value out of boundary
***************************************************************************/
ASICAMERA_API ASI_ERROR_CODE ASIStartVideoCapture(int iCameraID);
/***************************************************************************
Descriptions£º
Stop video capture
Paras£º
int CameraID: this is get from the camera property use the API ASIGetCameraProperty
return:
ASI_SUCCESS : Operation is successful, it will return success if already stopped
ASI_ERROR_CAMERA_CLOSED : camera didn't open
ASI_ERROR_INVALID_ID :no camera connected or index value out of boundary
***************************************************************************/
ASICAMERA_API ASI_ERROR_CODE ASIStopVideoCapture(int iCameraID);
/***************************************************************************
Descriptions£º
get data from the video buffer.the buffer is very small
you need to call this API as fast as possible, otherwise frame will be discarded
so the best way is maintain one buffer loop and call this API in a loop
please make sure the buffer size is biger enough to hold one image
otherwise the this API will crash
Paras£º
int CameraID: this is get from the camera property use the API ASIGetCameraProperty
unsigned char* pBuffer, caller need to malloc the buffer, make sure the size is big enough
the size in byte:
8bit mono:width*height
16bit mono:width*height*2
RGB24:width*height*3
int iWaitms, this API will block and wait iWaitms to get one image. the unit is ms
-1 means wait forever. this value is recommend set to exposure*2+500ms
return:
ASI_SUCCESS : Operation is successful
ASI_ERROR_CAMERA_CLOSED : camera didn't open
ASI_ERROR_INVALID_ID :no camera connected or index value out of boundary
ASI_ERROR_TIMEOUT: no image get and timeout
***************************************************************************/
ASICAMERA_API ASI_ERROR_CODE ASIGetVideoData(int iCameraID, unsigned char* pBuffer, long lBuffSize, int iWaitms);
/***************************************************************************
Descriptions£º
PulseGuide of the ST4 port on. this function only work on the module which have ST4 port
Paras£º
int CameraID: this is get from the camera property use the API ASIGetCameraProperty
ASI_GUIDE_DIRECTION direction the direction of guider
return:
ASI_SUCCESS : Operation is successful
ASI_ERROR_CAMERA_CLOSED : camera didn't open
ASI_ERROR_INVALID_ID :no camera connected or index value out of boundary
***************************************************************************/
ASICAMERA_API ASI_ERROR_CODE ASIPulseGuideOn(int iCameraID, ASI_GUIDE_DIRECTION direction);
/***************************************************************************
Descriptions£º
PulseGuide of the ST4 port off. this function only work on the module which have ST4 port
make sure where is ASIPulseGuideOn and there is ASIPulseGuideOff
Paras£º
int CameraID: this is get from the camera property use the API ASIGetCameraProperty
ASI_GUIDE_DIRECTION direction the direction of guider
return:
ASI_SUCCESS : Operation is successful
ASI_ERROR_CAMERA_CLOSED : camera didn't open
ASI_ERROR_INVALID_ID :no camera connected or index value out of boundary
***************************************************************************/
ASICAMERA_API ASI_ERROR_CODE ASIPulseGuideOff(int iCameraID, ASI_GUIDE_DIRECTION direction);
/***************************************************************************
Descriptions£º
Start camera exposure. the following 4 API is usually used when long exposure required
start exposure and check the exposure status then get the data
Paras£º
int CameraID: this is get from the camera property use the API ASIGetCameraProperty
ASI_BOOL bIsDark: means dark frame if there is mechanical shutter on the camera. otherwise useless
return:
ASI_SUCCESS : Operation is successful
ASI_ERROR_CAMERA_CLOSED : camera didn't open
ASI_ERROR_INVALID_ID :no camera connected or index value out of boundary
***************************************************************************/
ASICAMERA_API ASI_ERROR_CODE ASIStartExposure(int iCameraID, ASI_BOOL bIsDark);
/***************************************************************************
Descriptions£º
to cancel the long exposure which is on.
Paras£º
int CameraID: this is get from the camera property use the API ASIGetCameraProperty
return:
ASI_SUCCESS : Operation is successful
ASI_ERROR_CAMERA_CLOSED : camera didn't open
ASI_ERROR_INVALID_ID :no camera connected or index value out of boundary
***************************************************************************/
ASICAMERA_API ASI_ERROR_CODE ASIStopExposure(int iCameraID);
/***************************************************************************
Descriptions£º
to get the exposure status, work with ASIStartExposure.
you can read the data if get ASI_EXP_SUCCESS. or have to restart exposure again
if get ASI_EXP_FAILED
Paras£º
int CameraID: this is get from the camera property use the API ASIGetCameraProperty
ASI_EXPOSURE_STATUS *pExpStatus: the exposure status
return:
ASI_SUCCESS : Operation is successful
ASI_ERROR_CAMERA_CLOSED : camera didn't open
ASI_ERROR_INVALID_ID :no camera connected or index value out of boundary
***************************************************************************/
ASICAMERA_API ASI_ERROR_CODE ASIGetExpStatus(int iCameraID, ASI_EXPOSURE_STATUS *pExpStatus);
/***************************************************************************
Descriptions£º
get data after exposure.
please make sure the buffer size is biger enough to hold one image
otherwise the this API will crash
Paras£º
int CameraID: this is get from the camera property use the API ASIGetCameraProperty
unsigned char* pBuffer, caller need to malloc the buffer, make sure the size is big enough
the size in byte:
8bit mono:width*height
16bit mono:width*height*2
RGB24:width*height*3
return:
ASI_SUCCESS : Operation is successful
ASI_ERROR_CAMERA_CLOSED : camera didn't open
ASI_ERROR_INVALID_ID :no camera connected or index value out of boundary
ASI_ERROR_TIMEOUT: no image get and timeout
***************************************************************************/
ASICAMERA_API ASI_ERROR_CODE ASIGetDataAfterExp(int iCameraID, unsigned char* pBuffer, long lBuffSize);
/***************************************************************************
Descriptions£º
get camera id stored in flash, only available for USB3.0 camera
Paras£º
int CameraID: this is get from the camera property use the API ASIGetCameraProperty
ASI_ID* pID: pointer to ID
return:
ASI_SUCCESS : Operation is successful
ASI_ERROR_CAMERA_CLOSED : camera didn't open
ASI_ERROR_INVALID_ID :no camera connected or index value out of boundary
***************************************************************************/
ASICAMERA_API ASI_ERROR_CODE ASIGetID(int iCameraID, ASI_ID* pID);
/***************************************************************************
Descriptions£º
write camera id to flash, only available for USB3.0 camera
Paras£º
int CameraID: this is get from the camera property use the API ASIGetCameraProperty
ASI_ID ID: ID
return:
ASI_SUCCESS : Operation is successful
ASI_ERROR_CAMERA_CLOSED : camera didn't open
ASI_ERROR_INVALID_ID :no camera connected or index value out of boundary
***************************************************************************/
ASICAMERA_API ASI_ERROR_CODE ASISetID(int iCameraID, ASI_ID ID);
#ifdef __cplusplus
}
#endif
#endif
| bsd-3-clause |
tilia/tilia-vobject | test/v_object/i_tip/broker_process_reply_test.rb | 7897 | require 'test_helper'
require 'v_object/i_tip/broker_tester'
module Tilia
module VObject
class BrokerProcessReplyTest < ITip::BrokerTester
def test_reply_no_original
itip = <<ICS
BEGIN:VCALENDAR
VERSION:2.0
METHOD:REPLY
BEGIN:VEVENT
SEQUENCE:2
UID:foobar
ATTENDEE;PARTSTAT=ACCEPTED:mailto:[email protected]
ORGANIZER:mailto:[email protected]
END:VEVENT
END:VCALENDAR
ICS
old = nil
expected = nil
process(itip, old, expected)
end
def test_reply_accept
itip = <<ICS
BEGIN:VCALENDAR
VERSION:2.0
METHOD:REPLY
BEGIN:VEVENT
ATTENDEE;PARTSTAT=ACCEPTED:mailto:[email protected]
ORGANIZER:mailto:[email protected]
SEQUENCE:2
UID:foobar
END:VEVENT
END:VCALENDAR
ICS
old = <<ICS
BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
SEQUENCE:2
UID:foobar
ATTENDEE:mailto:[email protected]
ORGANIZER:mailto:[email protected]
END:VEVENT
END:VCALENDAR
ICS
expected = <<ICS
BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
SEQUENCE:2
UID:foobar
ATTENDEE;PARTSTAT=ACCEPTED;SCHEDULE-STATUS=2.0:mailto:[email protected]
ORGANIZER:mailto:[email protected]
END:VEVENT
END:VCALENDAR
ICS
process(itip, old, expected)
end
def test_reply_request_status
itip = <<ICS
BEGIN:VCALENDAR
VERSION:2.0
METHOD:REPLY
BEGIN:VEVENT
UID:foobar
REQUEST-STATUS:2.3;foo-bar!
ATTENDEE;PARTSTAT=ACCEPTED:mailto:[email protected]
ORGANIZER:mailto:[email protected]
SEQUENCE:2
UID:foobar
END:VEVENT
END:VCALENDAR
ICS
old = <<ICS
BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
UID:foobar
SEQUENCE:2
ATTENDEE:mailto:[email protected]
ORGANIZER:mailto:[email protected]
END:VEVENT
END:VCALENDAR
ICS
expected = <<ICS
BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
UID:foobar
SEQUENCE:2
ATTENDEE;PARTSTAT=ACCEPTED;SCHEDULE-STATUS=2.3:mailto:[email protected]
ORGANIZER:mailto:[email protected]
END:VEVENT
END:VCALENDAR
ICS
process(itip, old, expected)
end
def test_reply_party_crasher
itip = <<ICS
BEGIN:VCALENDAR
VERSION:2.0
METHOD:REPLY
BEGIN:VEVENT
ATTENDEE;PARTSTAT=ACCEPTED:mailto:[email protected]
ORGANIZER:mailto:[email protected]
SEQUENCE:2
UID:foobar
END:VEVENT
END:VCALENDAR
ICS
old = <<ICS
BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
SEQUENCE:2
UID:foobar
ATTENDEE:mailto:[email protected]
ORGANIZER:mailto:[email protected]
END:VEVENT
END:VCALENDAR
ICS
expected = <<ICS
BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
SEQUENCE:2
UID:foobar
ATTENDEE:mailto:[email protected]
ORGANIZER:mailto:[email protected]
ATTENDEE;PARTSTAT=ACCEPTED:mailto:[email protected]
END:VEVENT
END:VCALENDAR
ICS
process(itip, old, expected)
end
def test_reply_new_exception
# This is a reply to 1 instance of a recurring event. This should
# automatically create an exception.
itip = <<ICS
BEGIN:VCALENDAR
VERSION:2.0
METHOD:REPLY
BEGIN:VEVENT
ATTENDEE;PARTSTAT=ACCEPTED:mailto:[email protected]
ORGANIZER:mailto:[email protected]
SEQUENCE:2
RECURRENCE-ID:20140725T000000Z
UID:foobar
END:VEVENT
END:VCALENDAR
ICS
old = <<ICS
BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
SEQUENCE:2
UID:foobar
RRULE:FREQ=DAILY
DTSTART:20140724T000000Z
DTEND:20140724T010000Z
ATTENDEE:mailto:[email protected]
ORGANIZER:mailto:[email protected]
END:VEVENT
END:VCALENDAR
ICS
expected = <<ICS
BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
SEQUENCE:2
UID:foobar
RRULE:FREQ=DAILY
DTSTART:20140724T000000Z
DTEND:20140724T010000Z
ATTENDEE:mailto:[email protected]
ORGANIZER:mailto:[email protected]
END:VEVENT
BEGIN:VEVENT
SEQUENCE:2
UID:foobar
DTSTART:20140725T000000Z
DTEND:20140725T010000Z
ATTENDEE;PARTSTAT=ACCEPTED:mailto:[email protected]
ORGANIZER:mailto:[email protected]
RECURRENCE-ID:20140725T000000Z
END:VEVENT
END:VCALENDAR
ICS
process(itip, old, expected)
end
def test_reply_new_exception_tz
# This is a reply to 1 instance of a recurring event. This should
# automatically create an exception.
itip = <<ICS
BEGIN:VCALENDAR
VERSION:2.0
METHOD:REPLY
BEGIN:VEVENT
ATTENDEE;PARTSTAT=ACCEPTED:mailto:[email protected]
ORGANIZER:mailto:[email protected]
SEQUENCE:2
RECURRENCE-ID;TZID=America/Toronto:20140725T000000
UID:foobar
END:VEVENT
END:VCALENDAR
ICS
old = <<ICS
BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
SEQUENCE:2
UID:foobar
RRULE:FREQ=DAILY
DTSTART;TZID=America/Toronto:20140724T000000
DTEND;TZID=America/Toronto:20140724T010000
ATTENDEE:mailto:[email protected]
ORGANIZER:mailto:[email protected]
END:VEVENT
END:VCALENDAR
ICS
expected = <<ICS
BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
SEQUENCE:2
UID:foobar
RRULE:FREQ=DAILY
DTSTART;TZID=America/Toronto:20140724T000000
DTEND;TZID=America/Toronto:20140724T010000
ATTENDEE:mailto:[email protected]
ORGANIZER:mailto:[email protected]
END:VEVENT
BEGIN:VEVENT
SEQUENCE:2
UID:foobar
DTSTART;TZID=America/Toronto:20140725T000000
DTEND;TZID=America/Toronto:20140725T010000
ATTENDEE;PARTSTAT=ACCEPTED:mailto:[email protected]
ORGANIZER:mailto:[email protected]
RECURRENCE-ID;TZID=America/Toronto:20140725T000000
END:VEVENT
END:VCALENDAR
ICS
process(itip, old, expected)
end
def test_reply_party_crash_create_excepton
# IN this test there's a recurring event that has an exception. The
# exception is missing the attendee.
#
# The attendee party crashes the instance, so it should show up in the
# resulting object.
itip = <<ICS
BEGIN:VCALENDAR
VERSION:2.0
METHOD:REPLY
BEGIN:VEVENT
ATTENDEE;PARTSTAT=ACCEPTED;CN=Crasher!:mailto:[email protected]
ORGANIZER:mailto:[email protected]
SEQUENCE:2
RECURRENCE-ID:20140725T000000Z
UID:foobar
END:VEVENT
END:VCALENDAR
ICS
old = <<ICS
BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
SEQUENCE:2
UID:foobar
RRULE:FREQ=DAILY
DTSTART:20140724T000000Z
DTEND:20140724T010000Z
ORGANIZER:mailto:[email protected]
END:VEVENT
END:VCALENDAR
ICS
expected = <<ICS
BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
SEQUENCE:2
UID:foobar
RRULE:FREQ=DAILY
DTSTART:20140724T000000Z
DTEND:20140724T010000Z
ORGANIZER:mailto:[email protected]
END:VEVENT
BEGIN:VEVENT
SEQUENCE:2
UID:foobar
DTSTART:20140725T000000Z
DTEND:20140725T010000Z
ORGANIZER:mailto:[email protected]
RECURRENCE-ID:20140725T000000Z
ATTENDEE;PARTSTAT=ACCEPTED;CN=Crasher!:mailto:[email protected]
END:VEVENT
END:VCALENDAR
ICS
process(itip, old, expected)
end
def test_reply_new_exception_no_master_event
# This iTip message would normally create a new exception, but the
# server is not able to create this new instance, because there's no
# master event to clone from.
#
# This test checks if the message is ignored.
itip = <<ICS
BEGIN:VCALENDAR
VERSION:2.0
METHOD:REPLY
BEGIN:VEVENT
ATTENDEE;PARTSTAT=ACCEPTED;CN=Crasher!:mailto:[email protected]
ORGANIZER:mailto:[email protected]
SEQUENCE:2
RECURRENCE-ID:20140725T000000Z
UID:foobar
END:VEVENT
END:VCALENDAR
ICS
old = <<ICS
BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
SEQUENCE:2
UID:foobar
RRULE:FREQ=DAILY
DTSTART:20140724T000000Z
DTEND:20140724T010000Z
RECURRENCE-ID:20140724T000000Z
ORGANIZER:mailto:[email protected]
END:VEVENT
END:VCALENDAR
ICS
expected = nil
process(itip, old, expected)
end
def test_reply_accept_update_rsvp
itip = <<ICS
BEGIN:VCALENDAR
VERSION:2.0
METHOD:REPLY
BEGIN:VEVENT
ATTENDEE;PARTSTAT=ACCEPTED:mailto:[email protected]
ORGANIZER:mailto:[email protected]
SEQUENCE:2
UID:foobar
END:VEVENT
END:VCALENDAR
ICS
old = <<ICS
BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
SEQUENCE:2
UID:foobar
ATTENDEE;RSVP=TRUE:mailto:[email protected]
ORGANIZER:mailto:[email protected]
END:VEVENT
END:VCALENDAR
ICS
expected = <<ICS
BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
SEQUENCE:2
UID:foobar
ATTENDEE;PARTSTAT=ACCEPTED;SCHEDULE-STATUS=2.0:mailto:[email protected]
ORGANIZER:mailto:[email protected]
END:VEVENT
END:VCALENDAR
ICS
process(itip, old, expected)
end
end
end
end
| bsd-3-clause |
jAlpedrinha/DeclRY | declry/views.py | 9652 | from django.core.exceptions import ImproperlyConfigured
from django.core.urlresolvers import reverse
from django.db import transaction
from django.forms.models import inlineformset_factory, modelform_factory
from django.forms.widgets import HiddenInput
from django.shortcuts import get_object_or_404
from vanilla import FormView
from django.utils.translation import ugettext_lazy as _
from declry.forms import BootstrapModelForm
from django import http
from django.utils.decorators import classonlymethod
from django.template import (RequestContext,
loader, TemplateDoesNotExist)
import autocomplete_light
from django.views.decorators.csrf import requires_csrf_token
import logging
import smtplib
from email.mime.text import MIMEText
__author__ = 'jorgeramos'
class ModelFormView(FormView):
model = None
related_model = None
success_url_path = '{}_{}_view'
success_url_args = ''
template_name = "edit.html"
title = _('Edit')
form = BootstrapModelForm
fields = None
hidden_fields = []
exclude = []
formfield_callback = None
instance = None
@classonlymethod
def as_view(cls, **initkwargs):
view = super(ModelFormView, cls).as_view(**initkwargs)
if hasattr(cls, 'title'):
view.label = cls.title
return view
def get_form_class(self):
"""
Returns the form class to use in this view.
"""
if self.form_class:
return self.form_class
elif self.related_model:
widgets = autocomplete_light.get_widgets_dict(self.related_model)
return modelform_factory(self.related_model, widgets = widgets, form = self.form, fields=self.fields, exclude =self.exclude, formfield_callback=self.get_formfield_callback())
elif self.model:
widgets = autocomplete_light.get_widgets_dict(self.model)
return modelform_factory(self.model, widgets = widgets, form = self.form, fields=self.fields, exclude =self.exclude, formfield_callback=self.get_formfield_callback())
msg = "'%s' must either define 'form_class' or define 'model' or override 'get_form_class()'"
raise ImproperlyConfigured(msg % self.__class__.__name__)
def get_form(self, data=None, files=None, **kwargs):
"""
Given `data` and `files` QueryDicts, and optionally other named
arguments, and returns a form.
"""
cls = self.get_form_class()
return cls(instance = self.get_modelform_instance(), data=data, files=files, **kwargs)
def get(self, request, object_id=None, *args, **kwargs):
self.request = request
self.object_id = object_id
form = self.get_form()
context = self.get_context_data(form=form)
return self.render_to_response(context)
def post(self, request, object_id=None):
self.request = request
self.object_id = object_id
if 'go_back' in request.POST:
return self.form_valid(None)
form = self.get_form(data=request.POST, files=request.FILES)
if form.is_valid():
inst= form.save()
if not self.object_id:
self.object_id = inst.pk
self.success_url = self.get_success_url()
return self.form_valid(form)
return self.form_invalid(form)
def get_success_url(self):
return reverse(self.success_url_path.format(self.model._meta.app_label, self.model._meta.module_name),
args=(self.object_id,)) + self.success_url_args
def form_invalid(self, form, **kwargs):
context = self.get_context_data(form=form, **kwargs)
return self.render_to_response(context)
def get_context_data(self, **kwargs):
kwargs['title'] = self.title
kwargs['instance'] = self.get_instance()
kwargs['view'] = self
return kwargs
def get_formfield_callback(self):
def formfield_callback(f, **kwargs):
field = f.formfield(**kwargs)
if f.name in self.hidden_fields:
field.widget = HiddenInput()
return field
return formfield_callback
def get_instance(self):
if self.instance:
return self.instance
if self.request and self.object_id:
return get_object_or_404(self.model, pk=self.object_id)
def get_modelform_instance(self):
return self.get_instance()
class InlineFormView(FormView):
model = None
related_model = None
form = BootstrapModelForm
prefix = "inlineform"
template_name = "inline_edit.html"
title = None
instance = None
success_path = '{}_{}_view'
success_path_args = ''
fields = None
extra = 1
exclude = []
formfield_callback = None
@classonlymethod
def as_view(cls, **initkwargs):
view = super(InlineFormView,cls).as_view(**initkwargs)
if hasattr(cls, 'title'):
view.label = cls.title
return view
def get_form_class(self):
"""
Returns the form class to use in this view.
"""
if self.form_class:
return self.form_class
if self.model and self.related_model:
return inlineformset_factory(self.model, self.related_model, form=self.form, extra=self.extra, exclude = self.exclude,
fields = self.fields, formfield_callback= self.get_formfield_callback())
msg = "'%s' must either define 'form_class' or define 'model' and 'related_model' or override 'get_form_class()'"
raise ImproperlyConfigured(msg % self.__class__.__name__)
def get_form(self, data=None, files=None, **kwargs):
"""
Given `data` and `files` QueryDicts, and optionally other named
arguments, and returns a form.
"""
cls = self.get_form_class()
return cls(prefix = self.prefix, instance=self.get_instance(), data=data, files=files, **kwargs)
def get_context_data(self, **kwargs):
"""
Takes a set of keyword arguments to use as the base context, and
returns a context dictionary to use for the view, additionally adding
in 'view'.
"""
kwargs.update({
'prefix' : self.prefix,
'title': self.title,
'instance' : self.get_instance()
})
kwargs['view'] = self
return kwargs
def get(self, request, object_id, *args, **kwargs):
self.request = request
self.object_id = object_id
form = self.get_form()
context = self.get_context_data(form=form)
return self.render_to_response(context)
def post(self, request, object_id):
self.request = request
self.object_id = object_id
if 'add_{}'.format(self.prefix) in request.POST:
return self.process_add_element()
elif 'go_back' in request.POST:
return self.form_valid(None)
else:
form = self.get_form(data = request.POST, files= request.FILES)
if form.is_valid():
with transaction.commit_on_success():
#try:
form.save()
#except:
# transaction.rollback()
return self.form_valid(form)
return self.form_invalid(form)
def process_add_element(self):
post_copy = self.request.POST.copy()
post_copy['{}-TOTAL_FORMS'.format(self.prefix)] = int(post_copy['{}-TOTAL_FORMS'.format(self.prefix)]) + 1
form = self.get_form(data=post_copy, files=self.request.FILES)
context = self.get_context_data(form=form)
return self.render_to_response(context)
def get_success_url(self):
if self.success_path is None:
msg = "'%s' must define 'success_url' or override 'form_valid()'"
raise ImproperlyConfigured(msg % self.__class__.__name__)
else:
return reverse(self.success_path.format(self.model._meta.app_label, self.model._meta.module_name),
args=(self.object_id,)) + self.success_path_args
def get_instance(self):
if self.instance:
return self.instance
if self.request and self.object_id:
return get_object_or_404(self.model, pk=self.object_id)
def get_formfield_callback(self):
return self.formfield_callback
# This can be called when CsrfViewMiddleware.process_view has not run,
# therefore need @requires_csrf_token in case the template needs
# {% csrf_token %}.
session_logger = logging.getLogger('session')
@requires_csrf_token
def permission_denied(request, template_name='403.html'):
"""
Permission denied (403) handler.
Templates: :template:`403.html`
Context: None
If the template does not exist, an Http403 response containing the text
"403 Forbidden" (as per RFC 2616) will be returned.
"""
print "YAAAA"
email_txt="""
Erro 403
Path: {}
Cookies: {}
User: {}
Roles: {}
Bom trabalho
A Equipa do Scholr
"""
user = request.user if hasattr(request, 'user') else '?'
roles = request.user.roles if hasattr(request, 'user') and hasattr(request.user,'roles') else '---'
session_logger.error(u'{} with cookies {}, user: {}, roles: {}'.format(request.path, request.COOKIES, user, roles))
try:
template = loader.get_template(template_name)
except TemplateDoesNotExist:
return http.HttpResponseForbidden('<h1>403 TESTE</h1>')
return http.HttpResponseForbidden(template.render(RequestContext(request)))
| bsd-3-clause |
KaimingOuyang/HPC-K-Means | papi-5.4.3/src/libpfm4/lib/pfmlib_intel_snb.c | 3987 | /*
* pfmlib_intel_snb.c : Intel Sandy Bridge core PMU
*
* Copyright (c) 2010 Google, Inc
* Contributed by Stephane Eranian <[email protected]>
*
* 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.
*/
/* private headers */
#include "pfmlib_priv.h"
#include "pfmlib_intel_x86_priv.h"
#include "events/intel_snb_events.h"
static const int snb_models[] = {
42, /* Sandy Bridge (Core i7 26xx, 25xx) */
0
};
static const int snb_ep_models[] = {
45, /* Sandy Bridge EP */
0
};
static int
pfm_snb_init(void *this)
{
pfm_intel_x86_cfg.arch_version = 3;
return PFM_SUCCESS;
}
pfmlib_pmu_t intel_snb_support={
.desc = "Intel Sandy Bridge",
.name = "snb",
.pmu = PFM_PMU_INTEL_SNB,
.pme_count = LIBPFM_ARRAY_SIZE(intel_snb_pe),
.type = PFM_PMU_TYPE_CORE,
.supported_plm = INTEL_X86_PLM,
.num_cntrs = 8, /* consider with HT off by default */
.num_fixed_cntrs = 3,
.max_encoding = 2, /* offcore_response */
.pe = intel_snb_pe,
.atdesc = intel_x86_mods,
.flags = PFMLIB_PMU_FL_RAW_UMASK
| INTEL_X86_PMU_FL_ECMASK,
.cpu_family = 6,
.cpu_models = snb_models,
.pmu_detect = pfm_intel_x86_model_detect,
.pmu_init = pfm_snb_init,
.get_event_encoding[PFM_OS_NONE] = pfm_intel_x86_get_encoding,
PFMLIB_ENCODE_PERF(pfm_intel_x86_get_perf_encoding),
.get_event_first = pfm_intel_x86_get_event_first,
.get_event_next = pfm_intel_x86_get_event_next,
.event_is_valid = pfm_intel_x86_event_is_valid,
.validate_table = pfm_intel_x86_validate_table,
.get_event_info = pfm_intel_x86_get_event_info,
.get_event_attr_info = pfm_intel_x86_get_event_attr_info,
PFMLIB_VALID_PERF_PATTRS(pfm_intel_x86_perf_validate_pattrs),
.get_event_nattrs = pfm_intel_x86_get_event_nattrs,
.can_auto_encode = pfm_intel_x86_can_auto_encode,
};
pfmlib_pmu_t intel_snb_ep_support={
.desc = "Intel Sandy Bridge EP",
.name = "snb_ep",
.pmu = PFM_PMU_INTEL_SNB_EP,
.pme_count = LIBPFM_ARRAY_SIZE(intel_snb_pe),
.type = PFM_PMU_TYPE_CORE,
.supported_plm = INTEL_X86_PLM,
.num_cntrs = 8, /* consider with HT off by default */
.num_fixed_cntrs = 3,
.max_encoding = 2, /* offcore_response */
.pe = intel_snb_pe,
.atdesc = intel_x86_mods,
.flags = PFMLIB_PMU_FL_RAW_UMASK
| INTEL_X86_PMU_FL_ECMASK,
.cpu_family = 6,
.cpu_models = snb_ep_models,
.pmu_detect = pfm_intel_x86_model_detect,
.pmu_init = pfm_snb_init,
.get_event_encoding[PFM_OS_NONE] = pfm_intel_x86_get_encoding,
PFMLIB_ENCODE_PERF(pfm_intel_x86_get_perf_encoding),
.get_event_first = pfm_intel_x86_get_event_first,
.get_event_next = pfm_intel_x86_get_event_next,
.event_is_valid = pfm_intel_x86_event_is_valid,
.validate_table = pfm_intel_x86_validate_table,
.get_event_info = pfm_intel_x86_get_event_info,
.get_event_attr_info = pfm_intel_x86_get_event_attr_info,
PFMLIB_VALID_PERF_PATTRS(pfm_intel_x86_perf_validate_pattrs),
.get_event_nattrs = pfm_intel_x86_get_event_nattrs,
.can_auto_encode = pfm_intel_x86_can_auto_encode,
};
| bsd-3-clause |
AlexejK/lombok-intellij-plugin | src/main/java/de/plushnikov/intellij/plugin/processor/handler/singular/EmptyBuilderElementHandler.java | 1477 | package de.plushnikov.intellij.plugin.processor.handler.singular;
import com.intellij.psi.PsiAnnotation;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiField;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.PsiSubstitutor;
import com.intellij.psi.PsiType;
import com.intellij.psi.PsiVariable;
import de.plushnikov.intellij.plugin.processor.field.AccessorsInfo;
import org.jetbrains.annotations.NotNull;
import java.util.List;
class EmptyBuilderElementHandler implements BuilderElementHandler {
@Override
public void addBuilderField(@NotNull List<PsiField> fields, @NotNull PsiVariable psiVariable, @NotNull PsiClass innerClass, @NotNull AccessorsInfo accessorsInfo, @NotNull PsiSubstitutor substitutor) {
}
@Override
public void addBuilderMethod(@NotNull List<PsiMethod> methods, @NotNull PsiVariable psiVariable, @NotNull String fieldName, @NotNull PsiClass innerClass, boolean fluentBuilder, PsiType returnType, String singularName, PsiSubstitutor builderSubstitutor) {
}
@Override
public String createSingularName(PsiAnnotation singularAnnotation, String psiFieldName) {
return psiFieldName;
}
@Override
public void appendBuildPrepare(@NotNull StringBuilder buildMethodParameters, @NotNull PsiVariable psiVariable, @NotNull String fieldName) {
}
@Override
public void appendBuildCall(@NotNull StringBuilder buildMethodParameters, @NotNull String fieldName) {
buildMethodParameters.append(fieldName);
}
}
| bsd-3-clause |
jonathanihm/freeCodeCamp | curriculum/challenges/chinese/08-coding-interview-prep/rosetta-code/factorial.chinese.md | 1381 | ---
title: Factorial
id: 597b2b2a2702b44414742771
challengeType: 5
videoUrl: ''
localeTitle: 阶乘
---
## Description
<section id="description"><p>编写一个函数来返回一个数字的阶乘。 </p><p>一个数字的因子由下式给出: </p> N! = n *(n-1)*(n-2)* ..... * 1 <p>例如:3! = 3 * 2 * 1 = 6 4! = 4 * 3 * 2 * 1 = 24 </p><p>注意:0! = 1 </p></section>
## Instructions
<section id="instructions">
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>factorial</code>是一种功能。
testString: assert(typeof factorial === 'function');
- text: <code>factorial(2)</code>应该返回一个数字。
testString: assert(typeof factorial(2) === 'number');
- text: <code>factorial(3)</code>应该返回6.“)
testString: assert.equal(factorial(3), 6);
- text: <code>factorial(3)</code>应返回120.“)
testString: assert.equal(factorial(5), 120);
- text: '<code>factorial(3)</code>应返回3,628,800。“)'
testString: assert.equal(factorial(10), 3628800);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function factorial (n) {
// Good luck!
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>
| bsd-3-clause |
tcabanski/SouthSideDevToys | SyncDBNantTasks/SyncDatabaseParmsBase.cs | 637 | using System;
using RedGate.Shared.SQL;
using RedGate.SQLCompare.Engine;
namespace SyncDBNantTasks {
public abstract class SyncDatabaseParmsBase {
private DBConnectionInformation connection;
public Database RegisteredDatabase { get; protected set; }
public DBConnectionInformation Connection {
get {
if (connection == null) {
throw new NotImplementedException("Connection not supported");
}
else {
return connection;
}
}
set { connection = value; }
}
}
} | bsd-3-clause |
endlessm/chromium-browser | net/base/network_change_notifier_posix.h | 2993 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef NET_BASE_NETWORK_CHANGE_NOTIFIER_POSIX_H_
#define NET_BASE_NETWORK_CHANGE_NOTIFIER_POSIX_H_
#include <memory>
#include "base/gtest_prod_util.h"
#include "base/macros.h"
#include "base/memory/scoped_refptr.h"
#include "base/memory/weak_ptr.h"
#include "base/sequence_checker.h"
#include "base/synchronization/lock.h"
#include "base/threading/thread.h"
#include "base/threading/thread_checker.h"
#include "net/base/net_export.h"
#include "net/base/network_change_notifier.h"
namespace net {
// A NetworkChangeNotifier that needs to be told about network changes by some
// other object. This class can't directly listen for network changes because on
// ChromeOS and Android only objects running in the browser process can listen
// for network state changes.
class NET_EXPORT NetworkChangeNotifierPosix : public NetworkChangeNotifier {
public:
NetworkChangeNotifierPosix(
NetworkChangeNotifier::ConnectionType initial_connection_type,
NetworkChangeNotifier::ConnectionSubtype initial_connection_subtype);
~NetworkChangeNotifierPosix() override;
// These methods are used to notify this object that a network property has
// changed. These must be called from the thread that owns this object.
void OnDNSChanged();
void OnIPAddressChanged();
void OnConnectionChanged(
NetworkChangeNotifier::ConnectionType connection_type);
void OnConnectionSubtypeChanged(
NetworkChangeNotifier::ConnectionType connection_type,
NetworkChangeNotifier::ConnectionSubtype connection_subtype);
protected:
// NetworkChangeNotifier overrides.
NetworkChangeNotifier::ConnectionType GetCurrentConnectionType()
const override;
void GetCurrentMaxBandwidthAndConnectionType(
double* max_bandwidth_mbps,
ConnectionType* connection_type) const override;
private:
friend class NetworkChangeNotifierPosixTest;
// For testing purposes, allows specifying a SystemDnsConfigChangeNotifier.
// If |system_dns_config_notifier| is nullptr, NetworkChangeNotifier create a
// global one.
NetworkChangeNotifierPosix(
NetworkChangeNotifier::ConnectionType initial_connection_type,
NetworkChangeNotifier::ConnectionSubtype initial_connection_subtype,
SystemDnsConfigChangeNotifier* system_dns_config_notifier);
// Calculates parameters used for network change notifier online/offline
// signals.
static NetworkChangeNotifier::NetworkChangeCalculatorParams
NetworkChangeCalculatorParamsPosix();
THREAD_CHECKER(thread_checker_);
mutable base::Lock lock_;
NetworkChangeNotifier::ConnectionType
connection_type_; // Guarded by |lock_|.
double max_bandwidth_mbps_; // Guarded by |lock_|.
DISALLOW_COPY_AND_ASSIGN(NetworkChangeNotifierPosix);
};
} // namespace net
#endif // NET_BASE_NETWORK_CHANGE_NOTIFIER_POSIX_H_
| bsd-3-clause |
dmitry-urenev/extended-orchard-cms-v10.1 | src/Orchard.Web/Modules/Orchard.SEO/Migrations.cs | 1459 | using System.Data;
using Orchard.ContentManagement.MetaData;
using Orchard.Core.Contents.Extensions;
using Orchard.Data.Migration;
using Orchard.SEO.Services;
namespace Orchard.SEO
{
public class Migrations : DataMigrationImpl
{
public int Create()
{
SchemaBuilder.CreateTable("MetaRecord", table => table
.ContentPartRecord()
.Column<string>("Keywords")
.Column<string>("Title")
.Column<string>("Description")
.Column<string>("Robots")
);
ContentDefinitionManager.AlterPartDefinition(
"MetaPart", cfg => cfg
.WithDescription("Provides meta tags: title, description, keywords, robots")
.Attachable());
SchemaBuilder.CreateTable("RobotsFileRecord",
table => table
.Column<int>("Id", col => col.PrimaryKey().Identity())
.Column<string>("FileContent", col => col.Unlimited()
.WithDefault(@"User-agent: *
Allow: /"))
);
SchemaBuilder.CreateTable("SitemapFileRecord",
table => table
.Column<int>("Id", col => col.PrimaryKey().Identity())
.Column<string>("FileContent", col => col.Unlimited().WithDefault(SitemapService.DefaultFileText))
);
return 1;
}
}
} | bsd-3-clause |
vivyly/fancastic_17 | fancastic_17/fan/migrations/0001_initial.py | 909 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('users', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='FanUser',
fields=[
('user_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to=settings.AUTH_USER_MODEL)),
('slug', models.SlugField(unique=True)),
('is_contributor', models.BooleanField(default=False)),
('desc', models.TextField(blank=True)),
],
options={
'abstract': False,
'verbose_name': 'user',
'verbose_name_plural': 'users',
},
bases=('users.user',),
),
]
| bsd-3-clause |
acericonia/zf2-blog | module/Blog/config/module.config.php | 1534 | <?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
return array(
'service_manager' => array(
'invokables' => array(
'Blog\Service\PostServiceInterface' => 'Blog\Service\PostService'
)
),
'view_manager' => array(
'template_path_stack' => array(
__DIR__ . '/../view',
),
),
'controllers' => array(
'factories' => array(
'Blog\Controller\List' => 'Blog\Factory\ListControllerFactory'
)
),
// This lines opens the configuration for the RouteManager
'router' => array(
// Open configuration for all possible routes
'routes' => array(
// Define a new route called "post"
'post' => array(
// Define the routes type to be "Zend\Mvc\Router\Http\Literal", which is basically just a string
'type' => 'literal',
// Configure the route itself
'options' => array(
// Listen to "/blog" as uri
'route' => '/blog',
// Define default controller and action to be called when this route is matched
'defaults' => array(
'controller' => 'Blog\Controller\List',
'action' => 'index',
)
)
)
)
)
); | bsd-3-clause |
iti-luebeck/SmachApp | app/src/main/java/de/uni_luebeck/iti/smachapp/app/TransitionProperty.java | 6939 | /*
* Copyright (c) 2015, Institute of Computer Engineering, University of Lübeck
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package de.uni_luebeck.iti.smachapp.app;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.HashMap;
import de.uni_luebeck.iti.smachapp.model.BeepColorSensor;
import de.uni_luebeck.iti.smachapp.model.BeepIRSensor;
import de.uni_luebeck.iti.smachapp.model.BeepRobot;
import de.uni_luebeck.iti.smachapp.model.StateMachine;
import de.uni_luebeck.iti.smachapp.model.Transition;
import de.uni_luebeck.iti.smachapp.view.ColorSelector;
import de.uni_luebeck.iti.smachapp.view.IntSlider;
import de.uni_luebeck.iti.smachapp.view.SensorUI;
public class TransitionProperty extends Activity implements TextWatcher {
private Transition transition;
private StateMachine machine;
private int priority;
private int maxPriority;
private HashMap<String, SensorUI> uis = new HashMap<String, SensorUI>();
private TextView priorityField;
private static Transition setupTransition;
private static BeepRobot setupRobot;
private static StateMachine setupMachine;
private static int setupPriority;
private static int setupMaxPriority;
public static int getPriority() {
return setupPriority;
}
public static void setupTransition(Transition t, BeepRobot r, StateMachine m, int pri, int maxPri) {
setupTransition = t;
setupRobot = r;
setupMachine = m;
setupPriority = pri;
setupMaxPriority = maxPri;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transition_property);
transition = setupTransition;
machine = setupMachine;
BeepRobot robot = setupRobot;
priority = setupPriority;
maxPriority = setupMaxPriority;
priorityField = (TextView) findViewById(R.id.priority);
priorityField.setText(String.valueOf(priority));
LinearLayout container = (LinearLayout) findViewById(R.id.sensorContainer);
for (BeepIRSensor sen : robot.getIntSensors()) {
IntSlider slider = new IntSlider(this, sen);
container.addView(slider);
uis.put(sen.getName(), slider);
slider.setToGuard(transition.getSmachableGuard(), true);
slider.setToGuard(transition.getDisabledGuard(), false);
}
for (BeepColorSensor sen : robot.getColorSensors()) {
ColorSelector sel = new ColorSelector(this, sen);
container.addView(sel);
uis.put(sen.getName(), sel);
sel.setToGuard(transition.getSmachableGuard(), true);
sel.setToGuard(transition.getDisabledGuard(), false);
}
EditText text = (EditText) findViewById(R.id.transitionName);
text.setText(transition.getLabel());
text.addTextChangedListener(this);
}
@Override
public void onBackPressed() {
String newName = ((EditText) findViewById(R.id.transitionName)).getText().toString().trim();
if (!newName.equals(transition.getLabel()) && !newName.isEmpty()) {
if (machine.getTransition(newName) == null) {
transition.setLabel(newName);
} else {
Toast toast = Toast.makeText(this, R.string.nameAlreadyExists, Toast.LENGTH_LONG);
toast.show();
return;
}
}
transition.getSmachableGuard().clear();
transition.getDisabledGuard().clear();
for (SensorUI ui : uis.values()) {
if (ui.isChecked()) {
ui.fillGuard(transition.getSmachableGuard());
} else {
ui.fillGuard(transition.getDisabledGuard());
}
}
setupPriority = priority;
finish();
}
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
@Override
public void afterTextChanged(Editable editable) {
String name = editable.toString().trim();
if (!name.equals(transition.getLabel()) && machine.getTransition(name) != null) {
Toast toast = Toast.makeText(this, R.string.nameAlreadyExists, Toast.LENGTH_LONG);
toast.show();
}
if (name.isEmpty()) {
Toast toast = Toast.makeText(this, R.string.empty_name_in_property, Toast.LENGTH_LONG);
toast.show();
}
}
public void increasePriority(View view) {
priority = priority + 1;
if(priority>maxPriority){
priority=maxPriority;
Toast.makeText(this,R.string.max_priority_reached,Toast.LENGTH_SHORT).show();
}
priorityField.setText(String.valueOf(priority));
}
public void decreasePriority(View view) {
priority = priority - 1;
if(priority<0){
priority=0;
Toast.makeText(this,R.string.min_priority_reached,Toast.LENGTH_SHORT).show();
}
priorityField.setText(String.valueOf(priority));
}
}
| bsd-3-clause |
sagargopale/zend-api-dev | vendor/autoload.php | 183 | <?php
// autoload.php @generated by Composer
require_once __DIR__ . '/composer' . '/autoload_real.php';
return ComposerAutoloaderInit29a195fdeafbaf46892c28c394475c18::getLoader();
| bsd-3-clause |
devhood/erp-blpi | module/Database/src/Entity/Purchases.php | 4349 | <?php
namespace Database\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Purchases
*
* @ORM\Table(name="Purchases", indexes={@ORM\Index(name="fk_Purchases_Suppliers1_idx", columns={"supplier_id"})})
* @ORM\Entity
*/
class Purchases
{
/**
* @var integer
*
* @ORM\Column(name="purchase_id", type="integer", precision=0, scale=0, nullable=false, unique=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $purchaseId;
/**
* @var string
*
* @ORM\Column(name="reference_no", type="string", length=45, precision=0, scale=0, nullable=true, unique=false)
*/
private $referenceNo;
/**
* @var \DateTime
*
* @ORM\Column(name="purchase_date", type="date", precision=0, scale=0, nullable=true, unique=false)
*/
private $purchaseDate;
/**
* @var \DateTime
*
* @ORM\Column(name="expected_arrival_date", type="date", precision=0, scale=0, nullable=true, unique=false)
*/
private $expectedArrivalDate;
/**
* @var string
*
* @ORM\Column(name="purchase_status", type="string", length=45, precision=0, scale=0, nullable=true, unique=false)
*/
private $purchaseStatus;
/**
* @var string
*
* @ORM\Column(name="purchase_notes", type="text", precision=0, scale=0, nullable=true, unique=false)
*/
private $purchaseNotes;
/**
* @var \Database\Entity\Suppliers
*
* @ORM\ManyToOne(targetEntity="Database\Entity\Suppliers")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="supplier_id", referencedColumnName="supplier_id", nullable=true)
* })
*/
private $supplier;
/**
* Get purchaseId
*
* @return integer
*/
public function getPurchaseId()
{
return $this->purchaseId;
}
/**
* Set referenceNo
*
* @param string $referenceNo
* @return Purchases
*/
public function setReferenceNo($referenceNo)
{
$this->referenceNo = $referenceNo;
return $this;
}
/**
* Get referenceNo
*
* @return string
*/
public function getReferenceNo()
{
return $this->referenceNo;
}
/**
* Set purchaseDate
*
* @param \DateTime $purchaseDate
* @return Purchases
*/
public function setPurchaseDate($purchaseDate)
{
$this->purchaseDate = $purchaseDate;
return $this;
}
/**
* Get purchaseDate
*
* @return \DateTime
*/
public function getPurchaseDate()
{
return $this->purchaseDate;
}
/**
* Set expectedArrivalDate
*
* @param \DateTime $expectedArrivalDate
* @return Purchases
*/
public function setExpectedArrivalDate($expectedArrivalDate)
{
$this->expectedArrivalDate = $expectedArrivalDate;
return $this;
}
/**
* Get expectedArrivalDate
*
* @return \DateTime
*/
public function getExpectedArrivalDate()
{
return $this->expectedArrivalDate;
}
/**
* Set purchaseStatus
*
* @param string $purchaseStatus
* @return Purchases
*/
public function setPurchaseStatus($purchaseStatus)
{
$this->purchaseStatus = $purchaseStatus;
return $this;
}
/**
* Get purchaseStatus
*
* @return string
*/
public function getPurchaseStatus()
{
return $this->purchaseStatus;
}
/**
* Set purchaseNotes
*
* @param string $purchaseNotes
* @return Purchases
*/
public function setPurchaseNotes($purchaseNotes)
{
$this->purchaseNotes = $purchaseNotes;
return $this;
}
/**
* Get purchaseNotes
*
* @return string
*/
public function getPurchaseNotes()
{
return $this->purchaseNotes;
}
/**
* Set supplier
*
* @param \Database\Entity\Suppliers $supplier
* @return Purchases
*/
public function setSupplier(\Database\Entity\Suppliers $supplier = null)
{
$this->supplier = $supplier;
return $this;
}
/**
* Get supplier
*
* @return \Database\Entity\Suppliers
*/
public function getSupplier()
{
return $this->supplier;
}
}
| bsd-3-clause |
CGATOxford/proj029 | Proj029Pipelines/pipeline_proj029.py | 12528 | """
=====================================================
Analysis for project 29
=====================================================
:Author: Nick Ilott
:Release: $Id$
:Date: |today|
:Tags: Python
"""
# load modules
from ruffus import *
import CGAT.Experiment as E
import logging as L
import CGAT.Database as Database
import CGAT.CSV as CSV
import sys
import os
import re
import shutil
import itertools
import math
import glob
import time
import gzip
import collections
import random
import numpy
import sqlite3
import CGAT.GTF as GTF
import CGAT.IOTools as IOTools
import CGAT.IndexedFasta as IndexedFasta
from rpy2.robjects import r as R
import rpy2.robjects as ro
import rpy2.robjects.vectors as rovectors
from rpy2.rinterface import RRuntimeError
#from pandas import *
import PipelineProj029
###################################################
###################################################
###################################################
# Pipeline configuration
###################################################
# load options from the config file
import CGATPipelines.Pipeline as P
P.getParameters(
["pipeline.ini"])
PARAMS = P.PARAMS
###################################################################
# connecting to database
###################################################################
def connect():
'''connect to database.
This method also attaches to helper databases.
'''
dbh = sqlite3.connect(PARAMS["database"])
return dbh
###################################################################
###################################################################
###################################################################
# This first section deals with collating the information from
# pipeline_metagenomeassembly.py. We produce plots of relative
# abundance correllations etc between different samples
###################################################################
###################################################################
###################################################################
@follows(mkdir("metaphlan.dir"))
@split(os.path.join(PARAMS.get("communities_dir"), PARAMS.get("communities_db")),
"metaphlan.dir/relab.*.matrix")
def buildRelativeAbundanceMatricesMetaphlan(infile, outfiles):
'''
build a matrix combining the relative abundance estimations
for all samples
'''
# filenames to derive tablenames
dirname = PARAMS.get("communities_dir")
exp = "metaphlan.dir/*.relab"
files = glob.glob(os.path.join(dirname, exp))
tablenames = [
os.path.basename(x).replace(".", "_").replace("-", "_") \
for x in files]
tablenames.sort()
for level in ["phylum", "class", "order", "family", "genus", "species"]:
outfile = os.path.join("communities.dir", "relab." + level + ".matrix")
PipelineProj029.buildRelativeAbundanceMatrix(infile,
tablenames,
outfile,
level = level)
###################################################################
###################################################################
###################################################################
@follows(mkdir("kraken.dir"))
@split(os.path.join(PARAMS.get("communities_dir"), PARAMS.get("communities_db")),
"kraken.dir/*norm*.matrix")
def buildAbundanceMatricesKraken(infile, outfiles):
'''
build a matrix combining the rpm estimations
for all samples
'''
# filenames to derive tablenames
dirname = PARAMS.get("communities_dir")
exp = "kraken.dir/*.counts.norm.tsv.gz"
files = glob.glob(os.path.join(dirname, exp))
tablenames = [
"kraken_" + os.path.basename(P.snip(x, ".tsv.gz")).replace(".", "_").replace("-", "_") \
for x in files]
tablenames.sort()
for level in ["phylum", "class", "order", "family", "genus", "species"]:
outfile = os.path.join("kraken.dir", "counts.norm." + level + ".matrix")
PipelineProj029.buildRelativeAbundanceMatrix(infile,
tablenames,
outfile,
level = level)
###################################################################
###################################################################
###################################################################
@follows(mkdir("diamond.dir"))
@split(os.path.join(PARAMS.get("communities_dir"), PARAMS.get("communities_db")),
"diamond.dir/*norm*.matrix")
def buildAbundanceMatricesDiamond(infile, outfiles):
'''
build a matrix combining the rpm estimations
for all samples
'''
# filenames to derive tablenames
dirname = PARAMS.get("communities_dir")
exp = "diamond.dir/*.taxa.count"
files = glob.glob(os.path.join(dirname, exp))
tablenames = [
os.path.basename(x).replace(".", "_").replace("-", "_") \
for x in files]
tablenames.sort()
for level in ["phylum", "class", "order", "family", "genus", "species"]:
outfile = os.path.join("diamond.dir", "counts.norm." + level + ".matrix")
PipelineProj029.buildRelativeAbundanceMatrix(infile,
tablenames,
outfile,
level = level)
###################################################################
###################################################################
###################################################################
COMMUNITIES_TARGETS = []
communities_targets = {"kraken": buildAbundanceMatricesKraken,
"metaphlan": buildRelativeAbundanceMatricesMetaphlan,
"diamond": buildAbundanceMatricesDiamond}
for x in P.asList(PARAMS.get("classifiers")):
COMMUNITIES_TARGETS.append(communities_targets[x])
@transform(COMMUNITIES_TARGETS,
suffix(".matrix"), ".barplot.pdf")
def barplotAbundances(infile, outfile):
'''
barplot the species relative abundances
'''
threshold = PARAMS.get("communities_threshold")
PipelineProj029.barplotAbundances(infile,
outfile,
threshold)
###################################################################
###################################################################
###################################################################
@transform(COMMUNITIES_TARGETS, suffix(".matrix"), ".ratio.tsv")
def calculateFirmicutesBacteroidetesRatio(infile, outfile):
'''
barplot the species relative abundances
'''
threshold = PARAMS.get("communities_threshold")
PipelineProj029.calculateFirmicutesBacteroidetesRatio(infile,
outfile,
threshold)
###################################################################
###################################################################
###################################################################
@transform(calculateFirmicutesBacteroidetesRatio, suffix(".tsv"), ".pdf")
def plotFirmicutesBacteroidetesRatio(infile, outfile):
'''
produce boxplot of firmicutes/bacteroidetes ratio
'''
PipelineProj029.plotFirmicutesBacteroidetesRatio(infile,
outfile)
###################################################################
###################################################################
###################################################################
@transform(calculateFirmicutesBacteroidetesRatio, suffix(".tsv"), ".signif")
def calculateSignificanceOfFirmicutesBacteroidetesRatio(infile, outfile):
'''
use tuleyHSD to calculate significance between groups with
multiple testing correction
'''
PipelineProj029.calculateSignificanceOfFirmicutesBacteroidetesRatio(infile,
outfile)
###################################################################
###################################################################
###################################################################
@jobs_limit(1, "R")
@transform(COMMUNITIES_TARGETS, suffix(".matrix"), ".barplot.numbers.pdf")
def plotHowManySpecies(infile, outfile):
'''
how many samples have how many species?
'''
PipelineProj029.plotHowManySpecies(infile, outfile)
###################################################################
###################################################################
###################################################################
@transform(COMMUNITIES_TARGETS, suffix(".matrix"), ".heatmap.pdf")
def heatmapAbundances(infile, outfile):
'''
heatmap the species relative abundances
'''
threshold = PARAMS.get("communities_threshold")
PipelineProj029.heatmapAbundances(infile,
outfile,
threshold,
"covariates.tsv")
###################################################################
###################################################################
###################################################################
@transform(COMMUNITIES_TARGETS, suffix(".matrix"), ".signif")
def testSignificanceOfAbundances(infile, outfile):
'''
use an anova to test significance. This is not ideal but serves
as a quick look
'''
PipelineProj029.anovaTest(infile,
"covariates.tsv",
outfile,
threshold = PARAMS.get("communities_threshold"),
over = PARAMS.get("communities_over"))
###################################################################
###################################################################
###################################################################
@transform(testSignificanceOfAbundances,
suffix(".signif"),
add_inputs(COMMUNITIES_TARGETS),
".signif.pdf")
def plotSignificantResults(infiles, outfile):
'''
barplot those taxa that are different across groups
'''
inf = infiles[0]
track = P.snip(inf, ".signif")
abundance_file = [m for m in infiles[1] if m.find(track) != -1][0]
threshold = PARAMS.get("communities_threshold")
PipelineProj029.plotSignificantResults(inf, abundance_file, outfile, threshold)
###################################################################
###################################################################
###################################################################
# KEGG analysis
###################################################################
###################################################################
###################################################################
@follows(mkdir("kegg.dir"))
@merge(glob.glob(os.path.join(PARAMS.get("communities_dir"), "kegg.dir/*.kegg.counts")), "kegg.dir/kegg.pathways.matrix")
def combineKeggTables(infiles, outfile):
'''
merge counts for kegg pathways
'''
headers = ",".join(
[re.match(".*.dir/(.*).kegg.counts", x).groups()[0]
for x in infiles])
directory = os.path.dirname(infiles[0])
statement = '''python %(scriptsdir)s/combine_tables.py
--glob=%(directory)s/*.kegg.counts
--headers=%(headers)s
--columns=1
--log=%(outfile)s.log
> %(outfile)s'''
P.run()
#########################################
#########################################
#########################################
@follows(barplotAbundances,
plotFirmicutesBacteroidetesRatio,
calculateSignificanceOfFirmicutesBacteroidetesRatio,
plotHowManySpecies,
heatmapAbundances,
plotSignificantResults)
def full():
pass
#########################################
#########################################
#########################################
if __name__ == "__main__":
sys.exit(P.main(sys.argv))
| bsd-3-clause |
psprint/keyfrog | src/StorageManager.h | 4192 | /*********************************************************************************
* Copyright (C) 2006-2013 by Sebastian Gniazdowski *
* All Rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions *
* are met: *
* 1. Redistributions of source code must retain the above copyright *
* notice, this list of conditions and the following disclaimer. *
* 2. Redistributions in binary form must reproduce the above copyright *
* notice, this list of conditions and the following disclaimer in the *
* documentation and/or other materials provided with the distribution. *
* 3. Neither the name of the Keyfrog 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 REGENTS 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 REGENTS OR CONTRIBUTORS BE LIABLE *
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL *
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS *
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) *
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT *
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY *
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF *
* SUCH DAMAGE. *
*********************************************************************************/
#ifndef KEYFROGSTORAGEMANAGER_H
#define KEYFROGSTORAGEMANAGER_H
#include "Storage.h"
#include <map>
#include <boost/thread/thread.hpp>
#include <boost/thread/xtime.hpp>
namespace keyfrog {
/**
* @author Sebastian Gniazdowski <srnt at users dot sf dot net>
*/
class StorageManager : public Storage {
class StorageManagerCommiter {
StorageManager *m_owner;
boost::xtime m_xt;
public:
StorageManagerCommiter(StorageManager *storageManager) {
m_owner = storageManager;
}
void operator()();
};
/**
* Maps string cluster_begin + "_" + app_group to number of keys pressed
* Idea: remember last used entry because they are used in series?
*/
std::map<std::string, int> m_cache;
/// Synchronizes access to m_cache
boost::mutex m_cache_mutex;
/// Commiter funobj
StorageManagerCommiter *m_commiter;
/// Commiter thread
boost::thread *m_commiterThread;
Storage *m_backend;
public:
StorageManager(Storage *backend);
~StorageManager();
/**
* @brief Connects to given database
*/
virtual bool connect(std::string uri);
/**
* @brief Disconnects from database
*/
virtual void disconnect();
/**
* @brief Gets begining of cluster timestamp for given timestamp
*/
virtual int getClusterStart(int timestamp);
/**
* @brief Records keypresses at actual time
*/
virtual bool addKeyPress(int app_group, int count = 1);
/**
* @brief Records keypresses at given time
*/
virtual bool addKeyPress(int app_group, int timestamp, int count = 1);
};
}
#endif
| bsd-3-clause |
datafolklabs/cement | tests/ext/test_ext_redis.py | 1437 |
import os
from time import sleep
from cement.utils.test import TestApp
from cement.utils.misc import init_defaults
if 'REDIS_HOST' in os.environ.keys():
redis_host = os.environ['REDIS_HOST']
else:
redis_host = 'localhost'
defaults = init_defaults('cache.redis')
defaults['cache.redis']['host'] = redis_host
defaults['cache.redis']['port'] = 6379
defaults['cache.redis']['db'] = 0
class RedisApp(TestApp):
class Meta:
extensions = ['redis']
cache_handler = 'redis'
config_defaults = defaults
def test_redis_set(key):
with RedisApp() as app:
app.cache.set(key, 1001)
assert int(app.cache.get(key)) == 1001
def test_redis_get(key):
with RedisApp() as app:
# get empty value
app.cache.delete(key)
assert app.cache.get(key) is None
# get empty value with fallback
assert app.cache.get(key, 1234) == 1234
def test_redis_delete(key):
with RedisApp() as app:
app.cache.set(key, 1001)
assert int(app.cache.get(key)) == 1001
app.cache.delete(key)
assert app.cache.get(key) is None
def test_redis_purge(key):
with RedisApp() as app:
app.cache.set(key, 1002)
app.cache.purge()
assert app.cache.get(key) is None
def test_redis_expire(key):
with RedisApp() as app:
app.cache.set(key, 1003, time=2)
sleep(3)
assert app.cache.get(key) is None
| bsd-3-clause |
alameluchidambaram/CONNECT | Product/Production/Services/HIEMCore/src/main/java/gov/hhs/fha/nhinc/notify/adapter/proxy/HiemNotifyAdapterWebServiceProxySecured.java | 6017 | /*
* Copyright (c) 2012, United States Government, as represented by the Secretary of Health and Human Services.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the United States Government 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 UNITED STATES GOVERNMENT BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package gov.hhs.fha.nhinc.notify.adapter.proxy;
import gov.hhs.fha.nhinc.adapternotificationconsumersecured.AdapterNotificationConsumerPortSecureType;
import gov.hhs.fha.nhinc.common.nhinccommon.AcknowledgementType;
import gov.hhs.fha.nhinc.common.nhinccommon.AssertionType;
import gov.hhs.fha.nhinc.common.nhinccommon.NhinTargetSystemType;
import gov.hhs.fha.nhinc.hiem.consumerreference.ReferenceParametersHelper;
import gov.hhs.fha.nhinc.hiem.consumerreference.SoapMessageElements;
import gov.hhs.fha.nhinc.hiem.dte.marshallers.NhincCommonAcknowledgementMarshaller;
import gov.hhs.fha.nhinc.hiem.dte.marshallers.WsntSubscribeMarshaller;
import gov.hhs.fha.nhinc.messaging.client.CONNECTCXFClientFactory;
import gov.hhs.fha.nhinc.messaging.client.CONNECTClient;
import gov.hhs.fha.nhinc.messaging.service.port.ServicePortDescriptor;
import gov.hhs.fha.nhinc.nhinclib.NhincConstants;
import gov.hhs.fha.nhinc.nhinclib.NullChecker;
import gov.hhs.fha.nhinc.notify.adapter.proxy.service.HiemNotifyAdapterSecuredServicePortDescriptor;
import gov.hhs.fha.nhinc.webserviceproxy.WebServiceProxyHelper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.oasis_open.docs.wsn.b_2.Notify;
import org.w3c.dom.Element;
/**
*
* @author Jon Hoppesch
*/
public class HiemNotifyAdapterWebServiceProxySecured implements HiemNotifyAdapterProxy {
private static Log log = LogFactory.getLog(HiemNotifyAdapterWebServiceProxySecured.class);
private static WebServiceProxyHelper oProxyHelper = null;
public Element notify(Element notifyElement, SoapMessageElements referenceParametersElements,
AssertionType assertion, NhinTargetSystemType target) throws Exception {
Element responseElement = null;
String url = getWebServiceProxyHelper().getAdapterEndPointFromConnectionManager(
NhincConstants.HIEM_NOTIFY_ADAPTER_SERVICE_SECURED_NAME);
if (NullChecker.isNotNullish(url)) {
WsntSubscribeMarshaller subscribeMarshaller = new WsntSubscribeMarshaller();
Notify notify = subscribeMarshaller.unmarshalNotifyRequest(notifyElement);
String wsAddressingTo = ReferenceParametersHelper.getWsAddressingTo(referenceParametersElements);
if (wsAddressingTo == null) {
wsAddressingTo = url;
}
HiemNotifyAdapterSecuredServicePortDescriptor portDescriptor = new HiemNotifyAdapterSecuredServicePortDescriptor();
CONNECTClient<AdapterNotificationConsumerPortSecureType> client = getCONNECTClientSecured(portDescriptor,
url, assertion, wsAddressingTo);
AcknowledgementType response = (AcknowledgementType) client.invokePort(
AdapterNotificationConsumerPortSecureType.class, "notify", notify);
NhincCommonAcknowledgementMarshaller acknowledgementMarshaller = new NhincCommonAcknowledgementMarshaller();
responseElement = acknowledgementMarshaller.marshal(response);
} else {
log.error("Failed to call the web service (" + NhincConstants.HIEM_NOTIFY_ADAPTER_SERVICE_SECURED_NAME
+ "). The URL is null.");
}
return responseElement;
}
public Element notifySubscribersOfDocument(Element docNotify, AssertionType assertion, NhinTargetSystemType target)
throws Exception {
throw new UnsupportedOperationException("Not supported yet.");
}
public Element notifySubscribersOfCdcBioPackage(Element cdcNotify, AssertionType assertion,
NhinTargetSystemType target) throws Exception {
throw new UnsupportedOperationException("Not supported yet.");
}
protected CONNECTClient<AdapterNotificationConsumerPortSecureType> getCONNECTClientSecured(
ServicePortDescriptor<AdapterNotificationConsumerPortSecureType> portDescriptor, String url,
AssertionType assertion, String wsAddressingTo) {
return CONNECTCXFClientFactory.getInstance().getCONNECTClientSecured(portDescriptor, url, assertion,
wsAddressingTo);
}
protected WebServiceProxyHelper getWebServiceProxyHelper() {
if (oProxyHelper == null) {
oProxyHelper = new WebServiceProxyHelper();
}
return oProxyHelper;
}
}
| bsd-3-clause |
vorobyev/kontrexpert | expert.sql | 38501 | -- phpMyAdmin SQL Dump
-- version 4.6.3
-- https://www.phpmyadmin.net/
--
-- Хост: localhost
-- Время создания: Сен 07 2016 г., 10:58
-- Версия сервера: 5.6.27-log
-- Версия PHP: 5.6.23
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- База данных: `expert`
--
-- --------------------------------------------------------
--
-- Структура таблицы `accounts`
--
CREATE TABLE `accounts` (
`id` int(11) NOT NULL,
`idKontr` int(11) NOT NULL,
`kontrAccount` varchar(40) NOT NULL,
`bankName` text NOT NULL,
`korrAccount` varchar(40) NOT NULL,
`bik` varchar(40) NOT NULL,
`address` text NOT NULL,
`city` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Дамп данных таблицы `accounts`
--
INSERT INTO `accounts` (`id`, `idKontr`, `kontrAccount`, `bankName`, `korrAccount`, `bik`, `address`, `city`) VALUES
(5, 13, '40702810416160009320', 'ФИЛИАЛ N 3652 ВТБ 24 (ПАО)', '30101810100000000738', '042007738', '', 'ВОРОНЕЖ'),
(7, 16, '40702810207000101146', 'БЕЛГОРОДСКОЕ ОТДЕЛЕНИЕ N8592 ПАО СБЕРБАНК', '30101810100000000633', '041403633', '', 'БЕЛГОРОД'),
(8, 17, '40702810310160004803', 'ФИЛИАЛ N 3652 ВТБ 24 (ПАО)', '30101810100000000738', '042007738', '', 'ВОРОНЕЖ'),
(9, 19, '40702810401000000207', 'БФ АО КБ "РУСНАРБАНК"', '30101810300000000802', '041403802', '', 'БЕЛГОРОД'),
(10, 20, '40702810010160009823', 'ФИЛИАЛ N 3652 ВТБ 24 (ПАО)', '30101810100000000738', '042007738', '', 'ВОРОНЕЖ');
-- --------------------------------------------------------
--
-- Структура таблицы `contracts`
--
CREATE TABLE `contracts` (
`id` int(11) NOT NULL,
`idKontr` int(11) NOT NULL,
`dateContract` date NOT NULL,
`numberContract` varchar(20) NOT NULL,
`subj` varchar(255) DEFAULT NULL,
`comments` text
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Дамп данных таблицы `contracts`
--
INSERT INTO `contracts` (`id`, `idKontr`, `dateContract`, `numberContract`, `subj`, `comments`) VALUES
(6, 13, '2016-08-31', '258', 'СОУТ', ''),
(8, 16, '2016-08-30', '260', 'СОУТ', ''),
(9, 17, '2016-09-01', '259', 'СПЕЦИАЛЬНАЯ ОЦЕНКА УСЛОВИЙ ТРУДА', ''),
(10, 19, '2016-09-05', '263', 'СОУТ', ''),
(11, 20, '2016-09-05', '264', 'СОУТ', ''),
(12, 21, '2016-01-11', '001', 'СОУТ', ''),
(13, 22, '2016-01-11', '002', 'СОУТ', ''),
(14, 23, '2016-01-11', '002/1', 'СОУТ', 'выполнен'),
(15, 24, '2016-01-11', '003', 'СОУТ', 'выполнен'),
(16, 25, '2016-01-11', '278567/004', 'СОУТ', ''),
(17, 26, '2016-01-11', '005', 'СОУТ', 'выполнен'),
(18, 27, '2016-01-11', '006', 'СОУТ', 'выполнен'),
(19, 27, '2016-01-11', '007', 'СОУТ', 'выполнен'),
(20, 27, '2016-01-11', '008', 'СОУТ', 'выполнен'),
(21, 28, '2016-01-12', '010', 'СОУТ', 'выполнен'),
(22, 29, '2016-01-13', '011', 'СОУТ', 'выполнен'),
(23, 30, '2016-01-13', '012', 'СОУТ', 'выполнен'),
(24, 31, '2016-01-13', '013', '3700', 'выполнен'),
(25, 32, '2016-01-13', '014', 'СОУТ', 'выполнен'),
(26, 33, '2016-01-13', 'Д/с 8', 'ПК', 'выполнен'),
(27, 34, '2016-01-14', '014/1', 'ПК', 'выполнен'),
(28, 35, '2016-01-15', '016', 'СОУТ', 'выполнен'),
(29, 36, '2016-01-18', '017', 'СОУТ', 'выполнен'),
(30, 37, '2016-01-18', '018', 'СОУТ', ''),
(31, 38, '2016-02-24', '019', 'НТД', 'выполнен'),
(32, 39, '2016-01-20', '020', 'СОУТ', 'выполнен'),
(33, 40, '2016-01-21', '022', 'СОУТ', 'выполнен'),
(34, 41, '2016-01-21', '023', 'СОУТ', 'выполнен'),
(35, 42, '2016-01-22', '024', 'СОУТ', 'выполнен'),
(36, 43, '2016-01-25', '025', 'СОУТ', 'выполнен'),
(37, 44, '2016-01-26', '027', 'СОУТ', 'выполнен'),
(38, 45, '2016-01-20', '028', 'СОУТ', 'выполнен 09.2016'),
(39, 46, '2016-02-01', '029', 'СОУТ', 'выполнен'),
(40, 47, '2016-01-21', '024/1', 'СОУТ', 'выполнен'),
(41, 48, '2016-02-02', '030-ПК', 'ПК', 'выполнен'),
(42, 49, '2016-02-03', '031-ПК', 'ПК', ''),
(43, 50, '2016-02-03', '032-ПК', 'ПК', ''),
(44, 52, '2016-02-04', '033', 'СОУТ', 'выполнен'),
(45, 53, '2016-02-05', '034', 'СОУТ', 'выполнен'),
(46, 54, '2016-02-08', '035', 'СОУТ', 'выполнен');
-- --------------------------------------------------------
--
-- Структура таблицы `history_contracts`
--
CREATE TABLE `history_contracts` (
`id` int(11) NOT NULL,
`idContr` int(11) NOT NULL,
`dateContr` datetime NOT NULL,
`volumeJob` text NOT NULL,
`summ` varchar(36) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Дамп данных таблицы `history_contracts`
--
INSERT INTO `history_contracts` (`id`, `idContr`, `dateContr`, `volumeJob`, `summ`) VALUES
(7, 6, '2016-08-31 10:54:54', '2', '2800'),
(9, 8, '2016-09-01 16:41:14', '20', '33000'),
(10, 9, '2016-09-02 10:18:45', '9', '14400'),
(11, 10, '2016-09-05 11:04:25', '12', '19000'),
(12, 11, '2016-09-05 14:58:30', '1', '1400'),
(13, 12, '2016-09-06 14:44:39', '5', '9600'),
(14, 13, '2016-09-06 14:48:18', '2', '3200'),
(15, 14, '2016-09-06 14:50:00', '22', '35200'),
(16, 15, '2016-09-06 14:53:20', '342', '513570'),
(17, 16, '2016-09-06 15:06:00', '1354', '1544400'),
(18, 17, '2016-09-06 15:08:40', '129', '132000'),
(19, 18, '2016-09-06 15:12:36', '124', '99000'),
(20, 19, '2016-09-06 15:13:30', '130', '99500'),
(21, 20, '2016-09-06 15:14:09', '131', '99800'),
(22, 21, '2016-09-06 15:23:05', '74', '94540'),
(23, 22, '2016-09-06 15:28:20', '8', '12800'),
(24, 23, '2016-09-06 15:34:49', '10', '16800'),
(25, 24, '2016-09-06 15:37:00', '2', ''),
(26, 25, '2016-09-06 15:40:13', '20', '33000'),
(27, 26, '2016-09-06 15:45:09', '', '3920'),
(28, 27, '2016-09-06 15:47:40', '', '10800'),
(29, 28, '2016-09-06 15:50:54', '52', '80000'),
(30, 29, '2016-09-06 15:53:33', '30', '48000'),
(31, 30, '2016-09-06 15:57:31', '1', '2500'),
(32, 31, '2016-09-06 16:00:41', '', '15000'),
(33, 32, '2016-09-06 16:14:46', '2', '3200'),
(34, 33, '2016-09-06 16:17:57', '22', '43300'),
(35, 34, '2016-09-06 16:21:04', '21', '36800'),
(36, 35, '2016-09-07 10:30:31', '6', '8400'),
(37, 36, '2016-09-07 10:34:22', '4', '6800'),
(38, 37, '2016-09-07 10:36:17', '9', '15300'),
(39, 38, '2016-09-07 10:38:56', '86', '99990'),
(40, 39, '2016-09-07 10:42:32', '28', '37000'),
(41, 40, '2016-09-07 10:45:01', '28', '41160'),
(42, 41, '2016-09-07 10:47:39', '', '15210'),
(43, 42, '2016-09-07 10:50:34', '', '180000'),
(44, 43, '2016-09-07 10:54:30', '', '76906'),
(45, 44, '2016-09-07 10:57:26', '16', '15500'),
(46, 45, '2016-09-07 11:14:05', '2', '3400'),
(47, 46, '2016-09-07 11:48:45', '21', '29000');
-- --------------------------------------------------------
--
-- Структура таблицы `organizations`
--
CREATE TABLE `organizations` (
`id` int(11) NOT NULL,
`rukovod` text,
`fullName` text NOT NULL,
`name` text NOT NULL,
`name1c` varchar(255) NOT NULL,
`inn` varchar(20) NOT NULL,
`kpp` varchar(20) DEFAULT NULL,
`okpo` varchar(20) DEFAULT NULL,
`ogrn` varchar(20) DEFAULT NULL,
`dateReg` date NOT NULL,
`address` text NOT NULL,
`addressfact` text,
`saved` varchar(35) DEFAULT NULL,
`phone` text,
`email` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Дамп данных таблицы `organizations`
--
INSERT INTO `organizations` (`id`, `rukovod`, `fullName`, `name`, `name1c`, `inn`, `kpp`, `okpo`, `ogrn`, `dateReg`, `address`, `addressfact`, `saved`, `phone`, `email`) VALUES
(13, 'ДИРЕКТОР ИЩЕНКО ЮРИЙ ИВАНОВИЧ', 'ОБЩЕСТВО С ОГРАНИЧЕННОЙ ОТВЕТСТВЕННОСТЬЮ "ЭЛИТИУМ"', 'ООО "ЭЛИТИУМ"', 'ЭЛИТИУМ ООО', '3123359652', '312301001', '', '1153123001778', '2016-09-01', '308010, Белгородская Область, Белгород Город, Урожайная Улица, ДОМ 1', '308010, Белгородская Область, Белгород Город, Урожайная Улица, ДОМ 1', NULL, '89192801082', '[email protected]'),
(14, 'ГЛАВНЫЙ ВРАЧ КУРБАНИСМАИЛОВ ДЖАФЕР КУРБАНИСМАИЛОВИЧ', 'ОБЛАСТНОЕ ГОСУДАРСТВЕННОЕ БЮДЖЕТНОЕ УЧРЕЖДЕНИЕ ЗДРАВООХРАНЕНИЯ "РОВЕНЬСКАЯ ЦЕНТРАЛЬНАЯ РАЙОННАЯ БОЛЬНИЦА"', 'ОГБУЗ "РОВЕНЬСКАЯ ЦРБ"', 'РОВЕНЬСКАЯ ЦРБ ОГБУЗ', '3117000921', '311701001', '', '1023102158991', '2016-08-31', '309740, Белгородская Область, Ровеньский Район, Ровеньки Поселок, М.Горького Улица, 52', '', NULL, '', ''),
(16, 'ДИРЕКТОР ЧИГАРЕВ ГЕННАДИЙ ИВАНОВИЧ', 'ОБЩЕСТВО С ОГРАНИЧЕННОЙ ОТВЕТСТВЕННОСТЬЮ НАУЧНО-ПРОИЗВОДСТВЕННАЯ ФИРМА "ГЕОС"', 'ООО НПФ "ГЕОС"', 'НПФ ГЕОС ООО', '3125002182', '312301001', '', '1023101644631', '2016-09-01', '308000, Белгородская Область, Белгород Город, Студенческая Улица, 4', '308000, Белгородская Область, Белгород Город, Студенческая Улица, 4', NULL, '(4722)31-21-02', '[email protected]'),
(17, 'ДИРЕКТОР ПРИСТАВКА ВЛАДИМИР АЛЕКСАНДРОВИЧ', 'ОБЩЕСТВО С ОГРАНИЧЕННОЙ ОТВЕТСТВЕННОСТЬЮ "ПРОЗРЕНИЕ ПЛЮС"', 'ООО "ПРОЗРЕНИЕ ПЛЮС"', 'ПРОЗРЕНИЕ ПЛЮС ООО', '3123352456', '312301001', '', '1143123016739', '2016-09-02', '308000, Белгородская Область, Белгород Город, Костюкова Улица, 36Б', '308000, Белгородская Область, Белгород Город, Костюкова Улица, 36Б', NULL, '(4722) 25-73-77, 89102205538', ''),
(18, 'ГЛАВНЫЙ ВРАЧ МИЗЕНКО ИВАН ВАСИЛЬЕВИЧ', 'ОБЛАСТНОЕ ГОСУДАРСТВЕННОЕ БЮДЖЕТНОЕ УЧРЕЖДЕНИЕ ЗДРАВООХРАНЕНИЯ "ВОЛОКОНОВСКАЯ ЦЕНТРАЛЬНАЯ РАЙОННАЯ БОЛЬНИЦА"', 'ОГБУЗ "ВОЛОКОНОВСКАЯ ЦРБ"', 'ВОЛОКОНОВСКАЯ ЦРБ ОГБУЗ', '3106001916', '310601001', '', '1023100738430', '2016-09-02', '309650, Белгородская Область, Волоконовский Район, Волоконовка Поселок, Курочкина Улица, 1', '309650, Белгородская Область, Волоконовский Район, Волоконовка Поселок, Курочкина Улица, 1', NULL, '89205931205', '[email protected]'),
(19, 'ДИРЕКТОР ПРОКУДИН ИГОРЬ НИКОЛАЕВИЧ', 'ОБЩЕСТВО С ОГРАНИЧЕННОЙ ОТВЕТСТВЕННОСТЬЮ "СТОМАТОЛОГ И Я"', 'ООО "СТОМАТОЛОГ И Я"', 'СТОМАТОЛОГ И Я ООО', '3102020611', '312301001', '', '1053100526940', '2016-09-05', '308001, Белгородская Область, Белгород Город, Белгородский Проспект, 54', '308001, Белгородская Область, Белгород Город, Белгородский Проспект, 54', NULL, '(4722) 40-60-66', '[email protected]'),
(20, 'ГЕНЕРАЛЬНЫЙ ДИРЕКТОР КОРОЛЕВ РОМАН МИХАЙЛОВИЧ', 'ОБЩЕСТВО С ОГРАНИЧЕННОЙ ОТВЕТСТВЕННОСТЬЮ "ПИЦЦА ФЕНИКС"', 'ООО "ПИЦЦА ФЕНИКС"', 'ПИЦЦА ФЕНИКС ООО', '3123198370', '312301001', '89683380', '1093123007955', '2016-09-05', '308000, Белгородская Область, Белгород Город, Щорса Улица, ДОМ 52', '308000, Белгородская Область, Белгород Город, Щорса Улица, ДОМ 52', NULL, '', '[email protected], [email protected]'),
(21, 'ДИРЕКТОР СКЛЯРЕНКО ВИКТОР ВЛАДИМИРОВИЧ', 'ОБЩЕСТВО С ОГРАНИЧЕННОЙ ОТВЕТСТВЕННОСТЬЮ "ДАЛЬ"', 'ООО "ДАЛЬ"', 'ДАЛЬ ООО', '3103005454', '310301001', '', '1123116000501', '2016-09-06', '309341, Белгородская Область, Борисовский Район, Борисовка Поселок, Новоборисовская Улица, 24', '309341, Белгородская Область, Борисовский Район, Борисовка Поселок, Новоборисовская Улица, 24', NULL, '(47246)53210', ''),
(22, 'УПРАВЛЯЮЩИЙ МАРЧЕНКО АЛЕКСАНДР ЕВГЕНЬЕВИЧ', 'ОБЩЕСТВО С ОГРАНИЧЕННОЙ ОТВЕТСТВЕННОСТЬЮ "ЛУЧШЕЕ ИЗ ИНДИИ"', 'ООО "ЛУЧШЕЕ ИЗ ИНДИИ"', 'ЛУЧШЕЕ ИЗ ИНДИИ ООО', '6713012056', '671301001', '', '1126713000083', '2016-09-06', '216790, Смоленская Область, Руднянский Район, Рудня Город, Киреева Улица, 193', '216790, Смоленская Область, Руднянский Район, Рудня Город, Киреева Улица, 193', NULL, '', ''),
(23, 'ГЕНЕРАЛЬНЫЙ ДИРЕКТОР ВЕРПЕТА СЕРГЕЙ ВАСИЛЬЕВИЧ', 'ОБЩЕСТВО С ОГРАНИЧЕННОЙ ОТВЕТСТВЕННОСТЬЮ "ЧАСТНАЯ ОХРАННАЯ ОРГАНИЗАЦИЯ "БАЯЗЕТ"', 'ООО "ЧОО "БАЯЗЕТ"', 'ЧОО БАЯЗЕТ" ООО', '3120081511', '312001001', '', '1053104000333', '2016-09-06', '309290, Белгородская Область, Шебекино Город, Октябрьская Улица, 11', '309290, Белгородская Область, Шебекино Город, Октябрьская Улица, 11', NULL, '(47248)25600', ''),
(24, 'ГЕНЕРАЛЬНЫЙ ДИРЕКТОР ВАЩЕНКО АЛЕКСАНДР ИВАНОВИЧ', 'ОБЩЕСТВО С ОГРАНИЧЕННОЙ ОТВЕТСТВЕННОСТЬЮ "БЕЛЭНЕРГОМАШ-БЗЭМ"', 'ООО "БЕЛЭНЕРГОМАШ-БЗЭМ"', 'БЕЛЭНЕРГОМАШ-БЗЭМ ООО', '3123315768', '312301001', '', '1133123000801', '2016-09-06', '308017, Белгородская Область, Белгород Город, Волчанская Улица, ДОМ 165', '308017, Белгородская Область, Белгород Город, Волчанская Улица, ДОМ 165', NULL, '', ''),
(25, '', 'АКЦИОНЕРНОЕ ОБЩЕСТВО "ОСКОЛЬСКИЙ ЭЛЕКТРОМЕТАЛЛУРГИЧЕСКИЙ КОМБИНАТ"', 'АО "ОЭМК"', 'ОЭМК АО', '3128005752', '312801001', '', '1023102358620', '2016-09-06', '309515, Белгородская Область, Старый Оскол Город, проспект Алексея Угарова Проспект, 218 ЗДАНИЕ 2', '309515, Белгородская Область, Старый Оскол Город, проспект Алексея Угарова Проспект, 218 ЗДАНИЕ 2', NULL, '', ''),
(26, 'ГЕНЕРАЛЬНЫЙ ДИРЕКТОР СЛОВЕЦКИЙ АНТОН КАЗИМИРОВИЧ', 'ОБЩЕСТВО С ОГРАНИЧЕННОЙ ОТВЕТСТВЕННОСТЬЮ "ТРАНСЮЖСТРОЙ - ПГС"', 'ООО "ТЮС - ПГС"', 'ТЮС - ПГС ООО', '3123136631', '312301001', '', '1063123135680', '2016-09-06', '308012, Белгородская Область, Белгород Город, Костюкова Улица, 36 Б', '308012, Белгородская Область, Белгород Город, Костюкова Улица, 36 Б', NULL, '(4722)583820', ''),
(27, 'ГЛАВНЫЙ ВРАЧ ДРУЖИНИН СЕРГЕЙ ВАЛЕНТИНОВИЧ', 'ОБЛАСТНОЕ ГОСУДАРСТВЕННОЕ БЮДЖЕТНОЕ УЧРЕЖДЕНИЕ ЗДРАВООХРАНЕНИЯ "ГОРОДСКАЯ БОЛЬНИЦА № 2 ГОРОДА СТАРОГО ОСКОЛА"', 'ОГБУЗ "ГБ № 2 Г. СТАРОГО ОСКОЛА"', 'ГБ № 2 Г. СТАРОГО ОСКОЛА ОГБУЗ', '3128020310', '312801001', '', '1023102363371', '2016-09-06', '309500, Белгородская Область, Старый Оскол Город, Ублинские горы Улица, 1А', '309500, Белгородская Область, Старый Оскол Город, Ублинские горы Улица, 1А', NULL, '', ''),
(28, 'ГЕНЕРАЛЬНЫЙ ДИРЕКТОР СТАРОКОЖЕВ ВИКТОР ВЛАДИМИРОВИЧ', 'ОБЩЕСТВО С ОГРАНИЧЕННОЙ ОТВЕТСТВЕННОСТЬЮ "ГАЗЭНЕРГОСЕТЬ БЕЛГОРОД"', 'ООО "ГЭС БЕЛГОРОД"', 'ГЭС БЕЛГОРОД ООО', '3123215499', '312301001', '', '1103123008042', '2016-09-06', '308017, Белгородская Область, Белгород Город, Разуменская Улица, 1', '308017, Белгородская Область, Белгород Город, Разуменская Улица, 1', NULL, '(4722)739300', ''),
(29, 'ПРЕЗИДЕНТ СУЯЗОВА ИРИНА ВИКТОРОВНА', 'БЕЛГОРОДСКАЯ ОБЛАСТНАЯ НОТАРИАЛЬНАЯ ПАЛАТА (АССОЦИАЦИЯ)', 'БНП', ' БНП', '3125018560', '312301001', '', '1023100000978', '2016-09-06', '308012, Белгородская Область, Белгород Город, Костюкова Улица, 34', '308012, Белгородская Область, Белгород Город, Костюкова Улица, 34', NULL, '(4722)555038', ''),
(30, 'ДИРЕКТОР ДОЛГОДУШ АЛЕКСАНДР ИВАНОВИЧ', 'ОБЩЕСТВО С ОГРАНИЧЕННОЙ ОТВЕТСТВЕННОСТЬЮ "БОРИСОВКАХИМИЯ"', 'ООО "БОРИСОВКАХИМИЯ"', 'БОРИСОВКАХИМИЯ ООО', '3103005165', '310301001', '', '1113116000073', '2016-09-06', '309341, Белгородская Область, Борисовский Район, Борисовка Поселок, Новоборисовская Улица, 17', '309341, Белгородская Область, Борисовский Район, Борисовка Поселок, Новоборисовская Улица, 17', NULL, '(47246)50818', ''),
(31, '', 'ОБЩЕСТВО С ОГРАНИЧЕННОЙ ОТВЕТСТВЕННОСТЬЮ "СВИНОКОМПЛЕКС КАЛИНОВСКИЙ"', 'ООО "СВИНОКОМПЛЕКС КАЛИНОВСКИЙ"', 'СВИНОКОМПЛЕКС КАЛИНОВСКИЙ ООО', '3115006318', '311501001', '', '1093130001854', '2016-09-06', '309026, Белгородская Область, Прохоровский Район, Холодное Село', '309026, Белгородская Область, Прохоровский Район, Холодное Село', NULL, '', ''),
(32, 'ДИРЕКТОР ФОМЕНКО АЛЕКСАНДР ПЕТРОВИЧ', 'ОБЩЕСТВО С ОГРАНИЧЕННОЙ ОТВЕТСТВЕННОСТЬЮ "МОНТАЖГРУПП31"', 'ООО "МОНТАЖГРУПП31"', 'МОНТАЖГРУПП31 ООО', '3123374636', '312301001', '', '1153123016386', '2016-09-06', '308000, Белгородская Область, Белгород Город, Щорса Улица, ДОМ 62', '308000, Белгородская Область, Белгород Город, Щорса Улица, ДОМ 62', NULL, '', ''),
(33, 'ГЕНЕРАЛЬНЫЙ ДИРЕКТОР КЛАДОВ АЛЕКСАНДР АЛЕКСАНДРОВИЧ', 'ЗАКРЫТОЕ АКЦИОНЕРНОЕ ОБЩЕСТВО "ПРИОСКОЛЬЕ"', 'ЗАО "ПРИОСКОЛЬЕ"', 'ПРИОСКОЛЬЕ ЗАО', '3123100360', '311401001', '', '1033107033882', '2016-09-06', '309614, Белгородская Область, Новооскольский Район, Холки Станция', '309614, Белгородская Область, Новооскольский Район, Холки Станция', NULL, '', ''),
(34, 'ДИРЕКТОР ГОНТАРЕВА НАТАЛЬЯ ВАСИЛЬЕВНА', 'ОТКРЫТОЕ АКЦИОНЕРНОЕ ОБЩЕСТВО "ЗИНАИДИНСКОЕ ХЛЕБОПРИЕМНОЕ ПРЕДПРИЯТИЕ"', 'ОАО "ЗИНАИДИНСКОЕ ХПП"', 'ЗИНАИДИНСКОЕ ХПП ОАО', '3116000580', '311601001', '', '1033103500011', '2016-09-06', '309310, Белгородская Область, Ракитянский Район, Ракитное Поселок, Гагарина Улица, 7 "А"', '309310, Белгородская Область, Ракитянский Район, Ракитное Поселок, Гагарина Улица, 7 "А"', NULL, '', ''),
(35, 'ГЕНЕРАЛЬНЫЙ ДИРЕКТОР БЕРЕСТОВОЙ ДМИТРИЙ ВИКТОРОВИЧ', 'ОБЩЕСТВО С ОГРАНИЧЕННОЙ ОТВЕТСТВЕННОСТЬЮ "ОХОТНИЧИЙ КОМПЛЕКС "БЕЛОРЕЧЬЕ"', 'ООО "ОК "БЕЛОРЕЧЬЕ"', 'ОК БЕЛОРЕЧЬЕ" ООО', '3120012740', '311001001', '', '1043104000840', '2016-09-06', '309206, Белгородская Область, Корочанский Район, Алексеевка Село, Мирошникова Улица, 1Д', '309206, Белгородская Область, Корочанский Район, Алексеевка Село, Мирошникова Улица, 1Д', NULL, '(47231)35219', ''),
(36, 'ДИРЕКТОР МЯЧИКОВ АЛЕКСАНДР ВИТАЛЬЕВИЧ', 'ОБЩЕСТВО С ОГРАНИЧЕННОЙ ОТВЕТСТВЕННОСТЬЮ "СОКОЛ"', 'ООО "СОКОЛ"', 'СОКОЛ ООО', '3123138188', '312301001', '', '1063123138781', '2016-09-06', '308010, Белгородская Область, Белгород Город, Б.Хмельницкого Проспект, 137', '308010, Белгородская Область, Белгород Город, Б.Хмельницкого Проспект, 137', NULL, '', ''),
(37, 'Индивидуальный предприниматель МИРОНЕНКО ВИКТОР ЮРЬЕВИЧ', 'ИП МИРОНЕНКО ВИКТОР ЮРЬЕВИЧ', 'ИП МИРОНЕНКО В.Ю.', 'МИРОНЕНКО В.Ю. ИП', '312200088635', '', '', '304312219700060', '2016-09-06', '', 'Белгородская область, г. Алексеевка, с.Ильинка, ул. Ленина 9/1', NULL, '89194345272', ''),
(38, 'ДИРЕКТОР РЖЕВСКИЙ ВЛАДИМИР ИВАНОВИЧ', 'МУНИЦИПАЛЬНОЕ ОБЩЕОБРАЗОВАТЕЛЬНОЕ УЧРЕЖДЕНИЕ БЕЛОЗОРОВСКАЯ ОСНОВНАЯ ОБЩЕОБРАЗОВАТЕЛЬНАЯ ШКОЛА АЛЕКСЕЕВСКОГО РАЙОНА БЕЛГОРОДСКОЙ ОБЛАСТИ', 'МОУ БЕЛОЗОРОВСКАЯ ООШ', 'БЕЛОЗОРОВСКАЯ ООШ МОУ', '3122008235', '312201001', '', '1033106501944', '2016-09-06', '309807, Белгородская Область, Алексеевский Район, Ковалево Село, Центральная Улица, 66', '309807, Белгородская Область, Алексеевский Район, Ковалево Село, Центральная Улица, 66', NULL, '', ''),
(39, 'ГЕНЕРАЛЬНЫЙ ДИРЕКТОР ЯГОДИНА СВЕТЛАНА ВЛАДИМИРОВНА', 'ОБЩЕСТВО С ОГРАНИЧЕННОЙ ОТВЕТСТВЕННОСТЬЮ "ЮРИДИЧЕСКАЯ ФИРМА "БЕЛЮРИКОН"', 'ООО "ЮРИДИЧЕСКАЯ ФИРМА "БЕЛЮРИКОН"', 'ЮРИДИЧЕСКАЯ ФИРМА БЕЛЮРИКОН" ООО', '3123195066', '312301001', '', '1093123003940', '2016-09-06', '308000, Белгородская Область, Белгород Город, Князя Трубецкого Улица, 60 А', '308000, Белгородская Область, Белгород Город, Князя Трубецкого Улица, 60 А', NULL, '(4722)334397', ''),
(40, 'ГЕНЕРАЛЬНЫЙ ДИРЕКТОР БОГДАНОВА ЛЮБОВЬ НИКОЛАЕВНА', 'ОБЩЕСТВО С ОГРАНИЧЕННОЙ ОТВЕТСТВЕННОСТЬЮ "АЛЬЯНС"', 'ООО "АЛЬЯНС"', 'АЛЬЯНС ООО', '6730067016', '673001001', '', '1066731116858', '2016-09-06', '214000, Смоленская Область, Смоленск Город, Октябрьской Революции Улица, 9', '214000, Смоленская Область, Смоленск Город, Октябрьской Революции Улица, 9', NULL, '(4812)700100', ''),
(41, 'ДИРЕКТОР КИРЕЕВА ЕЛЕНА ОЛЕГОВНА', 'ЧАСТНОЕ ДОШКОЛЬНОЕ ОБРАЗОВАТЕЛЬНОЕ УЧРЕЖДЕНИЕ "ИЗЮМИНКА"', 'ЧДОУ "ИЗЮМИНКА"', 'ИЗЮМИНКА ЧДОУ', '3123231229', '312301001', '', '1113100001178', '2016-09-06', '308036, Белгородская Область, Белгород Город, Славянская Улица, 9 "Б"', '308036, Белгородская Область, Белгород Город, Славянская Улица, 9 "Б"', NULL, '(4722)424089', ''),
(42, 'ГЕНЕРАЛЬНЫЙ ДИРЕКТОР ЗАГОРУЙКО ВАЛЕРИЙ НИКОЛАЕВИЧ', 'ОБЩЕСТВО С ОГРАНИЧЕННОЙ ОТВЕТСТВЕННОСТЬЮ "ПРОИЗВОДСТВЕННОЕ ОБЪЕДИНЕНИЕ БЕЛЭЛЕКТРОМАШИНА"', 'ООО "ПО БЕЛЭЛЕКТРОМАШИНА"', 'ПО БЕЛЭЛЕКТРОМАШИНА ООО', '3123378020', '312301001', '', '1153123019884', '2016-09-07', '308017, Белгородская Область, Белгород Город, Константина Заслонова Улица, ДОМ 88', '308017, Белгородская Область, Белгород Город, Константина Заслонова Улица, ДОМ 88', NULL, '', ''),
(43, 'Индивидуальный предприниматель ГАРКОВЕНКО СЕРГЕЙ АЛЕКСЕЕВИЧ', 'ИП ГАРКОВЕНКО СЕРГЕЙ АЛЕКСЕЕВИЧ', 'ИП ГАРКОВЕНКО С.А.', 'ГАРКОВЕНКО С.А. ИП', '312300524846', '', '', '304312307800238', '2016-09-07', '', 'г. Белгород, б-р Юности 23/30', NULL, '', ''),
(44, 'ГЕНЕРАЛЬНЫЙ ДИРЕКТОР БАРАННИКОВ ВЛАДИМИР ДМИТРИЕВИЧ', 'ОБЩЕСТВО С ОГРАНИЧЕННОЙ ОТВЕТСТВЕННОСТЬЮ "КОНТРОЛЬ-БЕЛОГОРЬЕ"', 'ООО "КОНТРОЛЬ-БЕЛОГОРЬЕ"', 'КОНТРОЛЬ-БЕЛОГОРЬЕ ООО', '3123202242', '312301001', '', '1093123013224', '2016-09-07', '308019, Белгородская Область, Белгород Город, Ворошилова Улица, 2-Б', '308019, Белгородская Область, Белгород Город, Ворошилова Улица, 2-Б', NULL, '', ''),
(45, 'РУКОВОДИТЕЛЬ ПУШКАРСКАЯ ИРИНА ЕВГЕНЬЕВНА', 'ФЕДЕРАЛЬНОЕ КАЗЕННОЕ УЧРЕЖДЕНИЕ "ГЛАВНОЕ БЮРО МЕДИКО-СОЦИАЛЬНОЙ ЭКСПЕРТИЗЫ ПО БЕЛГОРОДСКОЙ ОБЛАСТИ" МИНИСТЕРСТВА ТРУДА И СОЦИАЛЬНОЙ ЗАЩИТЫ РОССИЙСКОЙ ФЕДЕРАЦИИ', 'ФКУ "ГБ МСЭ ПО БЕЛГОРОДСКОЙ ОБЛАСТИ" МИНТРУДА РОССИИ."', 'ГБ МСЭ ПО БЕЛГОРОДСКОЙ ОБЛАСТИ МИНТРУДА РОССИИ." ФКУ', '3123113850', '312301001', '', '1043107048160', '2016-09-07', '308006, Белгородская Область, Белгород Город, Корочанская Улица, 48', '308006, Белгородская Область, Белгород Город, Корочанская Улица, 48', NULL, '', ''),
(46, 'ДИРЕКТОР МАУ "МФЦ Г. БЕЛГОРОДА" ЧЕПЕЛЕВА ТАТЬЯНА ДМИТРИЕВНА', 'МУНИЦИПАЛЬНОЕ АВТОНОМНОЕ УЧРЕЖДЕНИЕ "МНОГОФУНКЦИОНАЛЬНЫЙ ЦЕНТР ПРЕДОСТАВЛЕНИЯ ГОСУДАРСТВЕННЫХ И МУНИЦИПАЛЬНЫХ УСЛУГ ГОРОДА БЕЛГОРОДА"', 'МАУ "МФЦ Г.БЕЛГОРОДА"', 'МФЦ Г.БЕЛГОРОДА МАУ', '3123349069', '312301001', '', '1143123013340', '2016-09-07', '308036, Белгородская Область, Белгород Город, Есенина Улица, ДОМ 9 КОРПУС 4', '308036, Белгородская Область, Белгород Город, Есенина Улица, ДОМ 9 КОРПУС 4', NULL, '', ''),
(47, 'ГЕНЕРАЛЬНЫЙ ДИРЕКТОР ВОЛКОВ МИХАИЛ ЮРЬЕВИЧ', 'СТРАХОВОЕ ПУБЛИЧНОЕ АКЦИОНЕРНОЕ ОБЩЕСТВО "ИНГОССТРАХ"', 'СПАО "ИНГОССТРАХ"', 'ИНГОССТРАХ СПАО', '7705042179', '775001001', '', '1027739362474', '2016-09-07', '117997, Москва Город, Пятницкая Улица, 12 СТР.2', '117997, Москва Город, Пятницкая Улица, 12 СТР.2', NULL, '(4722)265955', ''),
(48, 'ГЕНЕРАЛЬНЫЙ ДИРЕКТОР ГАЛИЦКИЙ СЕРГЕЙ АНАТОЛЬЕВИЧ', 'ОБЩЕСТВО С ОГРАНИЧЕННОЙ ОТВЕТСТВЕННОСТЬЮ "БЕЛГОРОДСКИЕ ГРАНУЛИРОВАННЫЕ КОРМА"', 'ООО "БЕЛГРАНКОРМ"', 'БЕЛГРАНКОРМ ООО', '3116003662', '311601001', '', '1023101180321', '2016-09-07', '309300, Белгородская Область, Ракитянский Район, Пролетарский Поселок, Борисовское Шоссе, 1', '309300, Белгородская Область, Ракитянский Район, Пролетарский Поселок, Борисовское Шоссе, 1', NULL, '', ''),
(49, 'ДИРЕКТОР БУДНИК ВАСИЛИЙ ФИЛИППОВИЧ', 'АКЦИОНЕРНОЕ ОБЩЕСТВО "МЕЛСТРОМ"', 'АО "МЕЛСТРОМ"', 'МЕЛСТРОМ АО', '3102002179', '310201001', '', '1023100508342', '2016-09-07', '308571, Белгородская Область, Белгородский Район, Петропавловка Село, Заводская Улица, 1 А', '308571, Белгородская Область, Белгородский Район, Петропавловка Село, Заводская Улица, 1 А', NULL, '', ''),
(50, 'ГЕНЕРАЛЬНЫЙ ДИРЕКТОР БАШКАТОВ ВЛАДИМИР ВАСИЛЬЕВИЧ', 'АКЦИОНЕРНОЕ ОБЩЕСТВО "БЕЛГОРОДСКИЙ ЗАВОД ГОРНОГО МАШИНОСТРОЕНИЯ"', 'АО "ГОРМАШ"', 'ГОРМАШ АО', '3124013819', '312301001', '', '1023101645522', '2016-09-07', '308000, Белгородская Область, Белгород Город, Сумская Улица, 72', '308000, Белгородская Область, Белгород Город, Сумская Улица, 72', NULL, '', ''),
(51, 'ГЕНЕРАЛЬНЫЙ ДИРЕКТОР ТИТОВСКИЙ СЕРГЕЙ АЛЕКСАНДРОВИЧ', 'ОТКРЫТОЕ АКЦИОНЕРНОЕ ОБЩЕСТВО "ПРИОСКОЛЬЕ-АГРО СЕМЕНА"', 'ОАО "ПРИОСКОЛЬЕ-АГРО СЕМЕНА"', 'ПРИОСКОЛЬЕ-АГРО СЕМЕНА ОАО', '3113001603', '311301001', '', '1083116000472', '2016-09-07', '309420, Белгородская Область, Краснояружский Район, Красная Яруга Поселок, Центральная Улица, 75', '309420, Белгородская Область, Краснояружский Район, Красная Яруга Поселок, Центральная Улица, 75', NULL, '', ''),
(52, 'ГЕНЕРАЛЬНЫЙ ДИРЕКТОР ТИТОВСКИЙ СЕРГЕЙ АЛЕКСАНДРОВИЧ', 'ОТКРЫТОЕ АКЦИОНЕРНОЕ ОБЩЕСТВО "ПРИОСКОЛЬЕ-АГРО СЕМЕНА"', 'ОАО "ПРИОСКОЛЬЕ-АГРО СЕМЕНА"', 'ПРИОСКОЛЬЕ-АГРО СЕМЕНА ОАО', '3113001603', '311301001', '', '1083116000472', '2016-09-07', '309420, Белгородская Область, Краснояружский Район, Красная Яруга Поселок, Центральная Улица, 75', '309420, Белгородская Область, Краснояружский Район, Красная Яруга Поселок, Центральная Улица, 75', NULL, '', ''),
(53, 'Индивидуальный предприниматель АНАЦКИЙ АЛЕКСАНДР ВЛАДИМИРОВИЧ', 'ИП АНАЦКИЙ АЛЕКСАНДР ВЛАДИМИРОВИЧ', 'ИП АНАЦКИЙ А.В.', 'АНАЦКИЙ А.В. ИП', '312332651847', '', '', '314313025900034', '2016-09-07', '', 'г. Строитель, ул. Жукова 5/93', NULL, '', ''),
(54, 'ДИРЕКТОР АЛЕКСАНДРОВА ОЛЬГА ЛЕОНИДОВНА', 'ОБЩЕСТВО С ОГРАНИЧЕННОЙ ОТВЕТСТВЕННОСТЬЮ "ЛИДЕР СТРОЙ ПЛЮС"', 'ООО "ЛИДЕР СТРОЙ ПЛЮС"', 'ЛИДЕР СТРОЙ ПЛЮС ООО', '3123349774', '312301001', '', '1143123014055', '2016-09-07', '308023, Белгородская Область, Белгород Город, Промышленный Проезд, 5', '308023, Белгородская Область, Белгород Город, Промышленный Проезд, 5', NULL, '(4722)316097', '');
-- --------------------------------------------------------
--
-- Структура таблицы `payments_contracts`
--
CREATE TABLE `payments_contracts` (
`id` int(11) NOT NULL,
`idContr` int(11) NOT NULL,
`datePayment` date NOT NULL,
`summ` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Дамп данных таблицы `payments_contracts`
--
INSERT INTO `payments_contracts` (`id`, `idContr`, `datePayment`, `summ`) VALUES
(1, 12, '2016-01-28', 9600),
(2, 15, '2016-06-22', 513570),
(3, 14, '2016-05-18', 17600),
(4, 14, '2016-06-14', 17600),
(5, 16, '2016-04-05', 340800),
(6, 16, '2016-07-04', 460800),
(7, 17, '2016-01-21', 66000),
(8, 17, '2016-03-16', 66000),
(9, 18, '2016-03-02', 99000),
(10, 19, '2016-03-03', 99500),
(11, 20, '2016-03-11', 99800),
(12, 21, '2016-01-29', 47270),
(13, 21, '2016-03-11', 47270),
(14, 22, '2016-02-04', 12800),
(15, 23, '2016-01-29', 16800),
(16, 24, '2016-02-04', 3700),
(17, 25, '2016-02-01', 33000),
(18, 26, '2016-01-15', 3920),
(19, 27, '2016-02-16', 10800),
(20, 28, '2016-02-03', 20000),
(21, 28, '2016-04-11', 20000),
(22, 28, '2016-06-09', 40000),
(23, 29, '2016-01-29', 24000),
(24, 29, '2016-09-01', 24000),
(25, 30, '2016-01-18', 2500),
(26, 31, '2016-03-10', 15000),
(27, 32, '2016-01-29', 3200),
(28, 33, '2016-02-02', 15155),
(29, 33, '2016-03-01', 15155),
(30, 33, '2016-03-30', 12990),
(31, 34, '2016-02-02', 16800),
(32, 34, '2016-09-02', 20000),
(33, 35, '2016-02-12', 8400),
(34, 36, '2016-01-29', 6800),
(35, 37, '2016-02-03', 15300),
(36, 38, '2016-01-28', 99990),
(37, 39, '2016-04-06', 37000),
(38, 40, '2016-02-19', 41160),
(39, 41, '2016-02-11', 15210),
(40, 41, '2016-02-11', 15210),
(41, 42, '2016-03-11', 45000),
(42, 42, '2016-07-14', 45000),
(43, 43, '2016-04-06', 38453),
(44, 44, '2016-02-19', 15500),
(45, 44, '2016-02-19', 15500),
(46, 44, '2016-02-19', 15500),
(47, 45, '2016-02-16', 3400),
(48, 46, '2016-02-18', 29000);
-- --------------------------------------------------------
--
-- Структура таблицы `user`
--
CREATE TABLE `user` (
`id` int(11) NOT NULL,
`name` varchar(32) NOT NULL,
`password` varchar(32) NOT NULL,
`email` varchar(255) NOT NULL,
`authKey` varchar(32) NOT NULL,
`accessToken` varchar(32) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Дамп данных таблицы `user`
--
INSERT INTO `user` (`id`, `name`, `password`, `email`, `authKey`, `accessToken`) VALUES
(1, 'expert', '2954d7eb52fa433ed9f060be50bdc926', '', '2954d7eb52fa', '2954d7eb52fa4');
--
-- Индексы сохранённых таблиц
--
--
-- Индексы таблицы `accounts`
--
ALTER TABLE `accounts`
ADD PRIMARY KEY (`id`);
--
-- Индексы таблицы `contracts`
--
ALTER TABLE `contracts`
ADD PRIMARY KEY (`id`);
--
-- Индексы таблицы `history_contracts`
--
ALTER TABLE `history_contracts`
ADD PRIMARY KEY (`id`);
--
-- Индексы таблицы `organizations`
--
ALTER TABLE `organizations`
ADD PRIMARY KEY (`id`);
--
-- Индексы таблицы `payments_contracts`
--
ALTER TABLE `payments_contracts`
ADD PRIMARY KEY (`id`);
--
-- Индексы таблицы `user`
--
ALTER TABLE `user`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `name` (`name`);
--
-- AUTO_INCREMENT для сохранённых таблиц
--
--
-- AUTO_INCREMENT для таблицы `accounts`
--
ALTER TABLE `accounts`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11;
--
-- AUTO_INCREMENT для таблицы `contracts`
--
ALTER TABLE `contracts`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=47;
--
-- AUTO_INCREMENT для таблицы `history_contracts`
--
ALTER TABLE `history_contracts`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=48;
--
-- AUTO_INCREMENT для таблицы `organizations`
--
ALTER TABLE `organizations`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=55;
--
-- AUTO_INCREMENT для таблицы `payments_contracts`
--
ALTER TABLE `payments_contracts`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=49;
--
-- AUTO_INCREMENT для таблицы `user`
--
ALTER TABLE `user`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
| bsd-3-clause |
endlessm/chromium-browser | net/websockets/websocket_basic_stream_test.cc | 39587 | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Tests for WebSocketBasicStream. Note that we do not attempt to verify that
// frame parsing itself functions correctly, as that is covered by the
// WebSocketFrameParser tests.
#include "net/websockets/websocket_basic_stream.h"
#include <stddef.h>
#include <stdint.h>
#include <string.h> // for memcpy() and memset().
#include <utility>
#include "base/big_endian.h"
#include "base/containers/span.h"
#include "base/optional.h"
#include "base/stl_util.h"
#include "net/base/io_buffer.h"
#include "net/base/privacy_mode.h"
#include "net/base/test_completion_callback.h"
#include "net/log/test_net_log.h"
#include "net/socket/connect_job.h"
#include "net/socket/socket_tag.h"
#include "net/socket/socket_test_util.h"
#include "net/socket/ssl_client_socket.h"
#include "net/test/gtest_util.h"
#include "net/test/test_with_task_environment.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using net::test::IsError;
using net::test::IsOk;
namespace net {
namespace {
#define WEBSOCKET_BASIC_STREAM_TEST_DEFINE_CONSTANT(name, value) \
const char k##name[] = value; \
const size_t k##name##Size = base::size(k##name) - 1
WEBSOCKET_BASIC_STREAM_TEST_DEFINE_CONSTANT(SampleFrame, "\x81\x06Sample");
WEBSOCKET_BASIC_STREAM_TEST_DEFINE_CONSTANT(
PartialLargeFrame,
"\x81\x7F\x00\x00\x00\x00\x7F\xFF\xFF\xFF"
"chromiunum ad pasco per loca insanis pullum manducat frumenti");
const size_t kLargeFrameHeaderSize = 10;
WEBSOCKET_BASIC_STREAM_TEST_DEFINE_CONSTANT(MultipleFrames,
"\x81\x01X\x81\x01Y\x81\x01Z");
WEBSOCKET_BASIC_STREAM_TEST_DEFINE_CONSTANT(EmptyFirstFrame, "\x01\x00");
WEBSOCKET_BASIC_STREAM_TEST_DEFINE_CONSTANT(EmptyMiddleFrame, "\x00\x00");
WEBSOCKET_BASIC_STREAM_TEST_DEFINE_CONSTANT(EmptyFinalTextFrame, "\x81\x00");
WEBSOCKET_BASIC_STREAM_TEST_DEFINE_CONSTANT(EmptyFinalContinuationFrame,
"\x80\x00");
WEBSOCKET_BASIC_STREAM_TEST_DEFINE_CONSTANT(ValidPong, "\x8A\x00");
// This frame encodes a payload length of 7 in two bytes, which is always
// invalid.
WEBSOCKET_BASIC_STREAM_TEST_DEFINE_CONSTANT(InvalidFrame,
"\x81\x7E\x00\x07Invalid");
// Control frames must have the FIN bit set. This one does not.
WEBSOCKET_BASIC_STREAM_TEST_DEFINE_CONSTANT(PingFrameWithoutFin, "\x09\x00");
// Control frames must have a payload of 125 bytes or less. This one has
// a payload of 126 bytes.
WEBSOCKET_BASIC_STREAM_TEST_DEFINE_CONSTANT(
126BytePong,
"\x8a\x7e\x00\x7eZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ"
"ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ");
WEBSOCKET_BASIC_STREAM_TEST_DEFINE_CONSTANT(CloseFrame,
"\x88\x09\x03\xe8occludo");
WEBSOCKET_BASIC_STREAM_TEST_DEFINE_CONSTANT(WriteFrame,
"\x81\x85\x00\x00\x00\x00Write");
WEBSOCKET_BASIC_STREAM_TEST_DEFINE_CONSTANT(MaskedEmptyPong,
"\x8A\x80\x00\x00\x00\x00");
const WebSocketMaskingKey kNulMaskingKey = {{'\0', '\0', '\0', '\0'}};
const WebSocketMaskingKey kNonNulMaskingKey = {
{'\x0d', '\x1b', '\x06', '\x17'}};
// A masking key generator function which generates the identity mask,
// ie. "\0\0\0\0".
WebSocketMaskingKey GenerateNulMaskingKey() { return kNulMaskingKey; }
// A masking key generation function which generates a fixed masking key with no
// nul characters.
WebSocketMaskingKey GenerateNonNulMaskingKey() { return kNonNulMaskingKey; }
// A subclass of StaticSocketDataProvider modified to require that all data
// expected to be read or written actually is.
class StrictStaticSocketDataProvider : public StaticSocketDataProvider {
public:
StrictStaticSocketDataProvider(base::span<const MockRead> reads,
base::span<const MockWrite> writes,
bool strict_mode)
: StaticSocketDataProvider(reads, writes), strict_mode_(strict_mode) {}
~StrictStaticSocketDataProvider() override {
if (strict_mode_) {
EXPECT_EQ(read_count(), read_index());
EXPECT_EQ(write_count(), write_index());
}
}
private:
const bool strict_mode_;
};
// A fixture for tests which only perform normal socket operations.
class WebSocketBasicStreamSocketTest : public TestWithTaskEnvironment {
protected:
WebSocketBasicStreamSocketTest()
: common_connect_job_params_(
&factory_,
nullptr /* host_resolver */,
nullptr /* http_auth_cache */,
nullptr /* http_auth_handler_factory */,
nullptr /* spdy_session_pool */,
nullptr /* quic_supported_versions */,
nullptr /* quic_stream_factory */,
nullptr /* proxy_delegate */,
nullptr /* http_user_agent_settings */,
nullptr /* ssl_client_context */,
nullptr /* socket_performance_watcher_factory */,
nullptr /* network_quality_estimator */,
nullptr /* net_log */,
nullptr /* websocket_endpoint_lock_manager */),
pool_(1, 1, &common_connect_job_params_),
generator_(&GenerateNulMaskingKey),
expect_all_io_to_complete_(true) {}
~WebSocketBasicStreamSocketTest() override {
// stream_ has a reference to socket_data_ (via MockTCPClientSocket) and so
// should be destroyed first.
stream_.reset();
}
std::unique_ptr<ClientSocketHandle> MakeTransportSocket(
base::span<const MockRead> reads,
base::span<const MockWrite> writes) {
socket_data_ = std::make_unique<StrictStaticSocketDataProvider>(
reads, writes, expect_all_io_to_complete_);
socket_data_->set_connect_data(MockConnect(SYNCHRONOUS, OK));
factory_.AddSocketDataProvider(socket_data_.get());
auto transport_socket = std::make_unique<ClientSocketHandle>();
scoped_refptr<ClientSocketPool::SocketParams> null_params;
ClientSocketPool::GroupId group_id(
HostPortPair("a", 80), ClientSocketPool::SocketType::kHttp,
PrivacyMode::PRIVACY_MODE_DISABLED, NetworkIsolationKey(),
false /* disable_secure_dns */);
transport_socket->Init(
group_id, null_params, base::nullopt /* proxy_annotation_tag */, MEDIUM,
SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
CompletionOnceCallback(), ClientSocketPool::ProxyAuthCallback(), &pool_,
NetLogWithSource());
return transport_socket;
}
void SetHttpReadBuffer(const char* data, size_t size) {
http_read_buffer_ = base::MakeRefCounted<GrowableIOBuffer>();
http_read_buffer_->SetCapacity(size);
memcpy(http_read_buffer_->data(), data, size);
http_read_buffer_->set_offset(size);
}
void CreateStream(base::span<const MockRead> reads,
base::span<const MockWrite> writes) {
stream_ = WebSocketBasicStream::CreateWebSocketBasicStreamForTesting(
MakeTransportSocket(reads, writes), http_read_buffer_, sub_protocol_,
extensions_, generator_);
}
std::unique_ptr<SocketDataProvider> socket_data_;
MockClientSocketFactory factory_;
const CommonConnectJobParams common_connect_job_params_;
MockTransportClientSocketPool pool_;
std::vector<std::unique_ptr<WebSocketFrame>> frames_;
TestCompletionCallback cb_;
scoped_refptr<GrowableIOBuffer> http_read_buffer_;
std::string sub_protocol_;
std::string extensions_;
WebSocketBasicStream::WebSocketMaskingKeyGeneratorFunction generator_;
bool expect_all_io_to_complete_;
std::unique_ptr<WebSocketBasicStream> stream_;
};
// A test fixture for the common case of tests that only perform a single read.
class WebSocketBasicStreamSocketSingleReadTest
: public WebSocketBasicStreamSocketTest {
protected:
void CreateRead(const MockRead& read) {
reads_[0] = read;
CreateStream(reads_, base::span<MockWrite>());
}
MockRead reads_[1];
};
// A test fixture for tests that perform chunked reads.
class WebSocketBasicStreamSocketChunkedReadTest
: public WebSocketBasicStreamSocketTest {
protected:
// Specify the behaviour if there aren't enough chunks to use all the data. If
// LAST_FRAME_BIG is specified, then the rest of the data will be
// put in the last chunk. If LAST_FRAME_NOT_BIG is specified, then the last
// frame will be no bigger than the rest of the frames (but it can be smaller,
// if not enough data remains).
enum LastFrameBehaviour {
LAST_FRAME_BIG,
LAST_FRAME_NOT_BIG
};
// Prepares a read from |data| of |data_size|, split into |number_of_chunks|,
// each of |chunk_size| (except that the last chunk may be larger or
// smaller). All reads must be either SYNCHRONOUS or ASYNC (not a mixture),
// and errors cannot be simulated. Once data is exhausted, further reads will
// return 0 (ie. connection closed).
void CreateChunkedRead(IoMode mode,
const char data[],
size_t data_size,
int chunk_size,
size_t number_of_chunks,
LastFrameBehaviour last_frame_behaviour) {
reads_.clear();
const char* start = data;
for (size_t i = 0; i < number_of_chunks; ++i) {
int len = chunk_size;
const bool is_last_chunk = (i == number_of_chunks - 1);
if ((last_frame_behaviour == LAST_FRAME_BIG && is_last_chunk) ||
static_cast<int>(data + data_size - start) < len) {
len = static_cast<int>(data + data_size - start);
}
reads_.push_back(MockRead(mode, start, len));
start += len;
}
CreateStream(reads_, base::span<MockWrite>());
}
std::vector<MockRead> reads_;
};
// Test fixture for write tests.
class WebSocketBasicStreamSocketWriteTest
: public WebSocketBasicStreamSocketTest {
protected:
// All write tests use the same frame, so it is easiest to create it during
// test creation.
void SetUp() override { PrepareWriteFrame(); }
// Creates a WebSocketFrame with a wire format matching kWriteFrame and adds
// it to |frames_|.
void PrepareWriteFrame() {
auto frame =
std::make_unique<WebSocketFrame>(WebSocketFrameHeader::kOpCodeText);
const size_t payload_size =
kWriteFrameSize - (WebSocketFrameHeader::kBaseHeaderSize +
WebSocketFrameHeader::kMaskingKeyLength);
auto buffer = base::MakeRefCounted<IOBuffer>(payload_size);
frame_buffers_.push_back(buffer);
memcpy(buffer->data(), kWriteFrame + kWriteFrameSize - payload_size,
payload_size);
frame->payload = buffer->data();
WebSocketFrameHeader& header = frame->header;
header.final = true;
header.masked = true;
header.payload_length = payload_size;
frames_.push_back(std::move(frame));
}
// TODO(yoichio): Make this type std::vector<std::string>.
std::vector<scoped_refptr<IOBuffer>> frame_buffers_;
};
TEST_F(WebSocketBasicStreamSocketTest, ConstructionWorks) {
CreateStream(base::span<MockRead>(), base::span<MockWrite>());
}
TEST_F(WebSocketBasicStreamSocketSingleReadTest, SyncReadWorks) {
CreateRead(MockRead(SYNCHRONOUS, kSampleFrame, kSampleFrameSize));
int result = stream_->ReadFrames(&frames_, cb_.callback());
EXPECT_THAT(result, IsOk());
ASSERT_EQ(1U, frames_.size());
EXPECT_EQ(UINT64_C(6), frames_[0]->header.payload_length);
EXPECT_TRUE(frames_[0]->header.final);
}
TEST_F(WebSocketBasicStreamSocketSingleReadTest, AsyncReadWorks) {
CreateRead(MockRead(ASYNC, kSampleFrame, kSampleFrameSize));
int result = stream_->ReadFrames(&frames_, cb_.callback());
ASSERT_THAT(result, IsError(ERR_IO_PENDING));
EXPECT_THAT(cb_.WaitForResult(), IsOk());
ASSERT_EQ(1U, frames_.size());
EXPECT_EQ(UINT64_C(6), frames_[0]->header.payload_length);
// Don't repeat all the tests from SyncReadWorks; just enough to be sure the
// frame was really read.
}
// ReadFrames will not return a frame whose header has not been wholly received.
TEST_F(WebSocketBasicStreamSocketChunkedReadTest, HeaderFragmentedSync) {
CreateChunkedRead(
SYNCHRONOUS, kSampleFrame, kSampleFrameSize, 1, 2, LAST_FRAME_BIG);
int result = stream_->ReadFrames(&frames_, cb_.callback());
EXPECT_THAT(result, IsOk());
ASSERT_EQ(1U, frames_.size());
EXPECT_EQ(UINT64_C(6), frames_[0]->header.payload_length);
}
// The same behaviour applies to asynchronous reads.
TEST_F(WebSocketBasicStreamSocketChunkedReadTest, HeaderFragmentedAsync) {
CreateChunkedRead(
ASYNC, kSampleFrame, kSampleFrameSize, 1, 2, LAST_FRAME_BIG);
int result = stream_->ReadFrames(&frames_, cb_.callback());
ASSERT_THAT(result, IsError(ERR_IO_PENDING));
EXPECT_THAT(cb_.WaitForResult(), IsOk());
ASSERT_EQ(1U, frames_.size());
EXPECT_EQ(UINT64_C(6), frames_[0]->header.payload_length);
}
// If it receives an incomplete header in a synchronous call, then has to wait
// for the rest of the frame, ReadFrames will return ERR_IO_PENDING.
TEST_F(WebSocketBasicStreamSocketTest, HeaderFragmentedSyncAsync) {
MockRead reads[] = {MockRead(SYNCHRONOUS, kSampleFrame, 1),
MockRead(ASYNC, kSampleFrame + 1, kSampleFrameSize - 1)};
CreateStream(reads, base::span<MockWrite>());
int result = stream_->ReadFrames(&frames_, cb_.callback());
ASSERT_THAT(result, IsError(ERR_IO_PENDING));
EXPECT_THAT(cb_.WaitForResult(), IsOk());
ASSERT_EQ(1U, frames_.size());
EXPECT_EQ(UINT64_C(6), frames_[0]->header.payload_length);
}
// An extended header should also return ERR_IO_PENDING if it is not completely
// received.
TEST_F(WebSocketBasicStreamSocketTest, FragmentedLargeHeader) {
MockRead reads[] = {
MockRead(SYNCHRONOUS, kPartialLargeFrame, kLargeFrameHeaderSize - 1),
MockRead(SYNCHRONOUS, ERR_IO_PENDING)};
CreateStream(reads, base::span<MockWrite>());
EXPECT_THAT(stream_->ReadFrames(&frames_, cb_.callback()),
IsError(ERR_IO_PENDING));
}
// A frame that does not arrive in a single read should be broken into separate
// frames.
TEST_F(WebSocketBasicStreamSocketSingleReadTest, LargeFrameFirstChunk) {
CreateRead(MockRead(SYNCHRONOUS, kPartialLargeFrame, kPartialLargeFrameSize));
EXPECT_THAT(stream_->ReadFrames(&frames_, cb_.callback()), IsOk());
ASSERT_EQ(1U, frames_.size());
EXPECT_FALSE(frames_[0]->header.final);
EXPECT_EQ(kPartialLargeFrameSize - kLargeFrameHeaderSize,
static_cast<size_t>(frames_[0]->header.payload_length));
}
// If only the header of a data frame arrives, we should receive a frame with a
// zero-size payload.
TEST_F(WebSocketBasicStreamSocketSingleReadTest, HeaderOnlyChunk) {
CreateRead(MockRead(SYNCHRONOUS, kPartialLargeFrame, kLargeFrameHeaderSize));
EXPECT_THAT(stream_->ReadFrames(&frames_, cb_.callback()), IsOk());
ASSERT_EQ(1U, frames_.size());
EXPECT_EQ(nullptr, frames_[0]->payload);
EXPECT_EQ(0U, frames_[0]->header.payload_length);
EXPECT_EQ(WebSocketFrameHeader::kOpCodeText, frames_[0]->header.opcode);
}
// If the header and the body of a data frame arrive seperately, we should see
// them as separate frames.
TEST_F(WebSocketBasicStreamSocketTest, HeaderBodySeparated) {
MockRead reads[] = {
MockRead(SYNCHRONOUS, kPartialLargeFrame, kLargeFrameHeaderSize),
MockRead(ASYNC,
kPartialLargeFrame + kLargeFrameHeaderSize,
kPartialLargeFrameSize - kLargeFrameHeaderSize)};
CreateStream(reads, base::span<MockWrite>());
EXPECT_THAT(stream_->ReadFrames(&frames_, cb_.callback()), IsOk());
ASSERT_EQ(1U, frames_.size());
EXPECT_EQ(nullptr, frames_[0]->payload);
EXPECT_EQ(WebSocketFrameHeader::kOpCodeText, frames_[0]->header.opcode);
frames_.clear();
EXPECT_THAT(stream_->ReadFrames(&frames_, cb_.callback()),
IsError(ERR_IO_PENDING));
EXPECT_THAT(cb_.WaitForResult(), IsOk());
ASSERT_EQ(1U, frames_.size());
EXPECT_EQ(kPartialLargeFrameSize - kLargeFrameHeaderSize,
frames_[0]->header.payload_length);
EXPECT_EQ(WebSocketFrameHeader::kOpCodeContinuation,
frames_[0]->header.opcode);
}
// Every frame has a header with a correct payload_length field.
TEST_F(WebSocketBasicStreamSocketChunkedReadTest, LargeFrameTwoChunks) {
const size_t kChunkSize = 16;
CreateChunkedRead(ASYNC,
kPartialLargeFrame,
kPartialLargeFrameSize,
kChunkSize,
2,
LAST_FRAME_NOT_BIG);
TestCompletionCallback cb[2];
ASSERT_THAT(stream_->ReadFrames(&frames_, cb[0].callback()),
IsError(ERR_IO_PENDING));
EXPECT_THAT(cb[0].WaitForResult(), IsOk());
ASSERT_EQ(1U, frames_.size());
EXPECT_EQ(kChunkSize - kLargeFrameHeaderSize,
frames_[0]->header.payload_length);
frames_.clear();
ASSERT_THAT(stream_->ReadFrames(&frames_, cb[1].callback()),
IsError(ERR_IO_PENDING));
EXPECT_THAT(cb[1].WaitForResult(), IsOk());
ASSERT_EQ(1U, frames_.size());
EXPECT_EQ(kChunkSize, frames_[0]->header.payload_length);
}
// Only the final frame of a fragmented message has |final| bit set.
TEST_F(WebSocketBasicStreamSocketChunkedReadTest, OnlyFinalChunkIsFinal) {
static const size_t kFirstChunkSize = 4;
CreateChunkedRead(ASYNC,
kSampleFrame,
kSampleFrameSize,
kFirstChunkSize,
2,
LAST_FRAME_BIG);
TestCompletionCallback cb[2];
ASSERT_THAT(stream_->ReadFrames(&frames_, cb[0].callback()),
IsError(ERR_IO_PENDING));
EXPECT_THAT(cb[0].WaitForResult(), IsOk());
ASSERT_EQ(1U, frames_.size());
ASSERT_FALSE(frames_[0]->header.final);
frames_.clear();
ASSERT_THAT(stream_->ReadFrames(&frames_, cb[1].callback()),
IsError(ERR_IO_PENDING));
EXPECT_THAT(cb[1].WaitForResult(), IsOk());
ASSERT_EQ(1U, frames_.size());
ASSERT_TRUE(frames_[0]->header.final);
}
// All frames after the first have their opcode changed to Continuation.
TEST_F(WebSocketBasicStreamSocketChunkedReadTest, ContinuationOpCodeUsed) {
const size_t kFirstChunkSize = 3;
const int kChunkCount = 3;
// The input data is one frame with opcode Text, which arrives in three
// separate chunks.
CreateChunkedRead(ASYNC,
kSampleFrame,
kSampleFrameSize,
kFirstChunkSize,
kChunkCount,
LAST_FRAME_BIG);
TestCompletionCallback cb[kChunkCount];
ASSERT_THAT(stream_->ReadFrames(&frames_, cb[0].callback()),
IsError(ERR_IO_PENDING));
EXPECT_THAT(cb[0].WaitForResult(), IsOk());
ASSERT_EQ(1U, frames_.size());
EXPECT_EQ(WebSocketFrameHeader::kOpCodeText, frames_[0]->header.opcode);
// This test uses a loop to verify that the opcode for every frames generated
// after the first is converted to Continuation.
for (int i = 1; i < kChunkCount; ++i) {
frames_.clear();
ASSERT_THAT(stream_->ReadFrames(&frames_, cb[i].callback()),
IsError(ERR_IO_PENDING));
EXPECT_THAT(cb[i].WaitForResult(), IsOk());
ASSERT_EQ(1U, frames_.size());
EXPECT_EQ(WebSocketFrameHeader::kOpCodeContinuation,
frames_[0]->header.opcode);
}
}
// Multiple frames that arrive together should be parsed correctly.
TEST_F(WebSocketBasicStreamSocketSingleReadTest, ThreeFramesTogether) {
CreateRead(MockRead(SYNCHRONOUS, kMultipleFrames, kMultipleFramesSize));
EXPECT_THAT(stream_->ReadFrames(&frames_, cb_.callback()), IsOk());
ASSERT_EQ(3U, frames_.size());
EXPECT_TRUE(frames_[0]->header.final);
EXPECT_TRUE(frames_[1]->header.final);
EXPECT_TRUE(frames_[2]->header.final);
}
// ERR_CONNECTION_CLOSED must be returned on close.
TEST_F(WebSocketBasicStreamSocketSingleReadTest, SyncClose) {
CreateRead(MockRead(SYNCHRONOUS, "", 0));
EXPECT_EQ(ERR_CONNECTION_CLOSED,
stream_->ReadFrames(&frames_, cb_.callback()));
}
TEST_F(WebSocketBasicStreamSocketSingleReadTest, AsyncClose) {
CreateRead(MockRead(ASYNC, "", 0));
ASSERT_THAT(stream_->ReadFrames(&frames_, cb_.callback()),
IsError(ERR_IO_PENDING));
EXPECT_THAT(cb_.WaitForResult(), IsError(ERR_CONNECTION_CLOSED));
}
// The result should be the same if the socket returns
// ERR_CONNECTION_CLOSED. This is not expected to happen on an established
// connection; a Read of size 0 is the expected behaviour. The key point of this
// test is to confirm that ReadFrames() behaviour is identical in both cases.
TEST_F(WebSocketBasicStreamSocketSingleReadTest, SyncCloseWithErr) {
CreateRead(MockRead(SYNCHRONOUS, ERR_CONNECTION_CLOSED));
EXPECT_EQ(ERR_CONNECTION_CLOSED,
stream_->ReadFrames(&frames_, cb_.callback()));
}
TEST_F(WebSocketBasicStreamSocketSingleReadTest, AsyncCloseWithErr) {
CreateRead(MockRead(ASYNC, ERR_CONNECTION_CLOSED));
ASSERT_THAT(stream_->ReadFrames(&frames_, cb_.callback()),
IsError(ERR_IO_PENDING));
EXPECT_THAT(cb_.WaitForResult(), IsError(ERR_CONNECTION_CLOSED));
}
TEST_F(WebSocketBasicStreamSocketSingleReadTest, SyncErrorsPassedThrough) {
// ERR_INSUFFICIENT_RESOURCES here represents an arbitrary error that
// WebSocketBasicStream gives no special handling to.
CreateRead(MockRead(SYNCHRONOUS, ERR_INSUFFICIENT_RESOURCES));
EXPECT_EQ(ERR_INSUFFICIENT_RESOURCES,
stream_->ReadFrames(&frames_, cb_.callback()));
}
TEST_F(WebSocketBasicStreamSocketSingleReadTest, AsyncErrorsPassedThrough) {
CreateRead(MockRead(ASYNC, ERR_INSUFFICIENT_RESOURCES));
ASSERT_THAT(stream_->ReadFrames(&frames_, cb_.callback()),
IsError(ERR_IO_PENDING));
EXPECT_THAT(cb_.WaitForResult(), IsError(ERR_INSUFFICIENT_RESOURCES));
}
// If we get a frame followed by a close, we should receive them separately.
TEST_F(WebSocketBasicStreamSocketChunkedReadTest, CloseAfterFrame) {
// The chunk size equals the data size, so the second chunk is 0 size, closing
// the connection.
CreateChunkedRead(SYNCHRONOUS,
kSampleFrame,
kSampleFrameSize,
kSampleFrameSize,
2,
LAST_FRAME_NOT_BIG);
EXPECT_THAT(stream_->ReadFrames(&frames_, cb_.callback()), IsOk());
EXPECT_EQ(1U, frames_.size());
frames_.clear();
EXPECT_EQ(ERR_CONNECTION_CLOSED,
stream_->ReadFrames(&frames_, cb_.callback()));
}
// Synchronous close after an async frame header is handled by a different code
// path.
TEST_F(WebSocketBasicStreamSocketTest, AsyncCloseAfterIncompleteHeader) {
MockRead reads[] = {MockRead(ASYNC, kSampleFrame, 1U),
MockRead(SYNCHRONOUS, "", 0)};
CreateStream(reads, base::span<MockWrite>());
ASSERT_THAT(stream_->ReadFrames(&frames_, cb_.callback()),
IsError(ERR_IO_PENDING));
EXPECT_THAT(cb_.WaitForResult(), IsError(ERR_CONNECTION_CLOSED));
}
// When Stream::Read returns ERR_CONNECTION_CLOSED we get the same result via a
// slightly different code path.
TEST_F(WebSocketBasicStreamSocketTest, AsyncErrCloseAfterIncompleteHeader) {
MockRead reads[] = {MockRead(ASYNC, kSampleFrame, 1U),
MockRead(SYNCHRONOUS, ERR_CONNECTION_CLOSED)};
CreateStream(reads, base::span<MockWrite>());
ASSERT_THAT(stream_->ReadFrames(&frames_, cb_.callback()),
IsError(ERR_IO_PENDING));
EXPECT_THAT(cb_.WaitForResult(), IsError(ERR_CONNECTION_CLOSED));
}
// An empty first frame is not ignored.
TEST_F(WebSocketBasicStreamSocketSingleReadTest, EmptyFirstFrame) {
CreateRead(MockRead(SYNCHRONOUS, kEmptyFirstFrame, kEmptyFirstFrameSize));
EXPECT_THAT(stream_->ReadFrames(&frames_, cb_.callback()), IsOk());
ASSERT_EQ(1U, frames_.size());
EXPECT_EQ(nullptr, frames_[0]->payload);
EXPECT_EQ(0U, frames_[0]->header.payload_length);
}
// An empty frame in the middle of a message is ignored.
TEST_F(WebSocketBasicStreamSocketTest, EmptyMiddleFrame) {
MockRead reads[] = {
MockRead(SYNCHRONOUS, kEmptyFirstFrame, kEmptyFirstFrameSize),
MockRead(SYNCHRONOUS, kEmptyMiddleFrame, kEmptyMiddleFrameSize),
MockRead(SYNCHRONOUS, ERR_IO_PENDING)};
CreateStream(reads, base::span<MockWrite>());
EXPECT_THAT(stream_->ReadFrames(&frames_, cb_.callback()), IsOk());
EXPECT_EQ(1U, frames_.size());
frames_.clear();
EXPECT_THAT(stream_->ReadFrames(&frames_, cb_.callback()),
IsError(ERR_IO_PENDING));
}
// An empty frame in the middle of a message that arrives separately is still
// ignored.
TEST_F(WebSocketBasicStreamSocketTest, EmptyMiddleFrameAsync) {
MockRead reads[] = {
MockRead(SYNCHRONOUS, kEmptyFirstFrame, kEmptyFirstFrameSize),
MockRead(ASYNC, kEmptyMiddleFrame, kEmptyMiddleFrameSize),
// We include a pong message to verify the middle frame was actually
// processed.
MockRead(ASYNC, kValidPong, kValidPongSize)};
CreateStream(reads, base::span<MockWrite>());
EXPECT_THAT(stream_->ReadFrames(&frames_, cb_.callback()), IsOk());
EXPECT_EQ(1U, frames_.size());
frames_.clear();
ASSERT_THAT(stream_->ReadFrames(&frames_, cb_.callback()),
IsError(ERR_IO_PENDING));
EXPECT_THAT(cb_.WaitForResult(), IsOk());
ASSERT_EQ(1U, frames_.size());
EXPECT_EQ(WebSocketFrameHeader::kOpCodePong, frames_[0]->header.opcode);
}
// An empty final frame is not ignored.
TEST_F(WebSocketBasicStreamSocketSingleReadTest, EmptyFinalFrame) {
CreateRead(
MockRead(SYNCHRONOUS, kEmptyFinalTextFrame, kEmptyFinalTextFrameSize));
EXPECT_THAT(stream_->ReadFrames(&frames_, cb_.callback()), IsOk());
ASSERT_EQ(1U, frames_.size());
EXPECT_EQ(nullptr, frames_[0]->payload);
EXPECT_EQ(0U, frames_[0]->header.payload_length);
}
// An empty middle frame is ignored with a final frame present.
TEST_F(WebSocketBasicStreamSocketTest, ThreeFrameEmptyMessage) {
MockRead reads[] = {
MockRead(SYNCHRONOUS, kEmptyFirstFrame, kEmptyFirstFrameSize),
MockRead(SYNCHRONOUS, kEmptyMiddleFrame, kEmptyMiddleFrameSize),
MockRead(SYNCHRONOUS,
kEmptyFinalContinuationFrame,
kEmptyFinalContinuationFrameSize)};
CreateStream(reads, base::span<MockWrite>());
EXPECT_THAT(stream_->ReadFrames(&frames_, cb_.callback()), IsOk());
ASSERT_EQ(1U, frames_.size());
EXPECT_EQ(WebSocketFrameHeader::kOpCodeText, frames_[0]->header.opcode);
frames_.clear();
EXPECT_THAT(stream_->ReadFrames(&frames_, cb_.callback()), IsOk());
ASSERT_EQ(1U, frames_.size());
EXPECT_TRUE(frames_[0]->header.final);
}
// If there was a frame read at the same time as the response headers (and the
// handshake succeeded), then we should parse it.
TEST_F(WebSocketBasicStreamSocketTest, HttpReadBufferIsUsed) {
SetHttpReadBuffer(kSampleFrame, kSampleFrameSize);
CreateStream(base::span<MockRead>(), base::span<MockWrite>());
EXPECT_THAT(stream_->ReadFrames(&frames_, cb_.callback()), IsOk());
ASSERT_EQ(1U, frames_.size());
ASSERT_TRUE(frames_[0]->payload);
EXPECT_EQ(UINT64_C(6), frames_[0]->header.payload_length);
}
// Check that a frame whose header partially arrived at the end of the response
// headers works correctly.
TEST_F(WebSocketBasicStreamSocketSingleReadTest,
PartialFrameHeaderInHttpResponse) {
SetHttpReadBuffer(kSampleFrame, 1);
CreateRead(MockRead(ASYNC, kSampleFrame + 1, kSampleFrameSize - 1));
ASSERT_THAT(stream_->ReadFrames(&frames_, cb_.callback()),
IsError(ERR_IO_PENDING));
EXPECT_THAT(cb_.WaitForResult(), IsOk());
ASSERT_EQ(1U, frames_.size());
ASSERT_TRUE(frames_[0]->payload);
EXPECT_EQ(UINT64_C(6), frames_[0]->header.payload_length);
EXPECT_EQ(WebSocketFrameHeader::kOpCodeText, frames_[0]->header.opcode);
}
// Check that a control frame which partially arrives at the end of the response
// headers works correctly.
TEST_F(WebSocketBasicStreamSocketSingleReadTest,
PartialControlFrameInHttpResponse) {
const size_t kPartialFrameBytes = 3;
SetHttpReadBuffer(kCloseFrame, kPartialFrameBytes);
CreateRead(MockRead(ASYNC,
kCloseFrame + kPartialFrameBytes,
kCloseFrameSize - kPartialFrameBytes));
ASSERT_THAT(stream_->ReadFrames(&frames_, cb_.callback()),
IsError(ERR_IO_PENDING));
EXPECT_THAT(cb_.WaitForResult(), IsOk());
ASSERT_EQ(1U, frames_.size());
EXPECT_EQ(WebSocketFrameHeader::kOpCodeClose, frames_[0]->header.opcode);
EXPECT_EQ(kCloseFrameSize - 2, frames_[0]->header.payload_length);
EXPECT_EQ(std::string(frames_[0]->payload, kCloseFrameSize - 2),
std::string(kCloseFrame + 2, kCloseFrameSize - 2));
}
// Check that a control frame which partially arrives at the end of the response
// headers works correctly. Synchronous version (unlikely in practice).
TEST_F(WebSocketBasicStreamSocketSingleReadTest,
PartialControlFrameInHttpResponseSync) {
const size_t kPartialFrameBytes = 3;
SetHttpReadBuffer(kCloseFrame, kPartialFrameBytes);
CreateRead(MockRead(SYNCHRONOUS,
kCloseFrame + kPartialFrameBytes,
kCloseFrameSize - kPartialFrameBytes));
EXPECT_THAT(stream_->ReadFrames(&frames_, cb_.callback()), IsOk());
ASSERT_EQ(1U, frames_.size());
EXPECT_EQ(WebSocketFrameHeader::kOpCodeClose, frames_[0]->header.opcode);
}
// Check that an invalid frame results in an error.
TEST_F(WebSocketBasicStreamSocketSingleReadTest, SyncInvalidFrame) {
CreateRead(MockRead(SYNCHRONOUS, kInvalidFrame, kInvalidFrameSize));
EXPECT_EQ(ERR_WS_PROTOCOL_ERROR,
stream_->ReadFrames(&frames_, cb_.callback()));
}
TEST_F(WebSocketBasicStreamSocketSingleReadTest, AsyncInvalidFrame) {
CreateRead(MockRead(ASYNC, kInvalidFrame, kInvalidFrameSize));
ASSERT_THAT(stream_->ReadFrames(&frames_, cb_.callback()),
IsError(ERR_IO_PENDING));
EXPECT_THAT(cb_.WaitForResult(), IsError(ERR_WS_PROTOCOL_ERROR));
}
// A control frame without a FIN flag is invalid and should not be passed
// through to higher layers. RFC6455 5.5 "All control frames ... MUST NOT be
// fragmented."
TEST_F(WebSocketBasicStreamSocketSingleReadTest, ControlFrameWithoutFin) {
CreateRead(
MockRead(SYNCHRONOUS, kPingFrameWithoutFin, kPingFrameWithoutFinSize));
EXPECT_EQ(ERR_WS_PROTOCOL_ERROR,
stream_->ReadFrames(&frames_, cb_.callback()));
EXPECT_TRUE(frames_.empty());
}
// A control frame over 125 characters is invalid. RFC6455 5.5 "All control
// frames MUST have a payload length of 125 bytes or less". Since we use a
// 125-byte buffer to assemble fragmented control frames, we need to detect this
// error before attempting to assemble the fragments.
TEST_F(WebSocketBasicStreamSocketSingleReadTest, OverlongControlFrame) {
CreateRead(MockRead(SYNCHRONOUS, k126BytePong, k126BytePongSize));
EXPECT_EQ(ERR_WS_PROTOCOL_ERROR,
stream_->ReadFrames(&frames_, cb_.callback()));
EXPECT_TRUE(frames_.empty());
}
// A control frame over 125 characters should still be rejected if it is split
// into multiple chunks.
TEST_F(WebSocketBasicStreamSocketChunkedReadTest, SplitOverlongControlFrame) {
const size_t kFirstChunkSize = 16;
expect_all_io_to_complete_ = false;
CreateChunkedRead(SYNCHRONOUS,
k126BytePong,
k126BytePongSize,
kFirstChunkSize,
2,
LAST_FRAME_BIG);
EXPECT_EQ(ERR_WS_PROTOCOL_ERROR,
stream_->ReadFrames(&frames_, cb_.callback()));
EXPECT_TRUE(frames_.empty());
}
TEST_F(WebSocketBasicStreamSocketChunkedReadTest,
AsyncSplitOverlongControlFrame) {
const size_t kFirstChunkSize = 16;
expect_all_io_to_complete_ = false;
CreateChunkedRead(ASYNC,
k126BytePong,
k126BytePongSize,
kFirstChunkSize,
2,
LAST_FRAME_BIG);
ASSERT_THAT(stream_->ReadFrames(&frames_, cb_.callback()),
IsError(ERR_IO_PENDING));
EXPECT_THAT(cb_.WaitForResult(), IsError(ERR_WS_PROTOCOL_ERROR));
// The caller should not call ReadFrames() again after receiving an error
// other than ERR_IO_PENDING.
EXPECT_TRUE(frames_.empty());
}
// In the synchronous case, ReadFrames assembles the whole control frame before
// returning.
TEST_F(WebSocketBasicStreamSocketChunkedReadTest, SyncControlFrameAssembly) {
const size_t kChunkSize = 3;
CreateChunkedRead(
SYNCHRONOUS, kCloseFrame, kCloseFrameSize, kChunkSize, 3, LAST_FRAME_BIG);
EXPECT_THAT(stream_->ReadFrames(&frames_, cb_.callback()), IsOk());
ASSERT_EQ(1U, frames_.size());
EXPECT_EQ(WebSocketFrameHeader::kOpCodeClose, frames_[0]->header.opcode);
}
// In the asynchronous case, the callback is not called until the control frame
// has been completely assembled.
TEST_F(WebSocketBasicStreamSocketChunkedReadTest, AsyncControlFrameAssembly) {
const size_t kChunkSize = 3;
CreateChunkedRead(
ASYNC, kCloseFrame, kCloseFrameSize, kChunkSize, 3, LAST_FRAME_BIG);
ASSERT_THAT(stream_->ReadFrames(&frames_, cb_.callback()),
IsError(ERR_IO_PENDING));
EXPECT_THAT(cb_.WaitForResult(), IsOk());
ASSERT_EQ(1U, frames_.size());
EXPECT_EQ(WebSocketFrameHeader::kOpCodeClose, frames_[0]->header.opcode);
}
// A frame with a 1MB payload that has to be read in chunks.
TEST_F(WebSocketBasicStreamSocketChunkedReadTest, OneMegFrame) {
// This should be equal to the definition of kReadBufferSize in
// websocket_basic_stream.cc.
const int kReadBufferSize = 32 * 1024;
const uint64_t kPayloadSize = 1 << 20;
const size_t kWireSize = kPayloadSize + kLargeFrameHeaderSize;
const size_t kExpectedFrameCount =
(kWireSize + kReadBufferSize - 1) / kReadBufferSize;
std::unique_ptr<char[]> big_frame(new char[kWireSize]);
memcpy(big_frame.get(), "\x81\x7F", 2);
base::WriteBigEndian(big_frame.get() + 2, kPayloadSize);
memset(big_frame.get() + kLargeFrameHeaderSize, 'A', kPayloadSize);
CreateChunkedRead(ASYNC,
big_frame.get(),
kWireSize,
kReadBufferSize,
kExpectedFrameCount,
LAST_FRAME_BIG);
for (size_t frame = 0; frame < kExpectedFrameCount; ++frame) {
frames_.clear();
ASSERT_THAT(stream_->ReadFrames(&frames_, cb_.callback()),
IsError(ERR_IO_PENDING));
EXPECT_THAT(cb_.WaitForResult(), IsOk());
ASSERT_EQ(1U, frames_.size());
size_t expected_payload_size = kReadBufferSize;
if (frame == 0) {
expected_payload_size = kReadBufferSize - kLargeFrameHeaderSize;
} else if (frame == kExpectedFrameCount - 1) {
expected_payload_size = kLargeFrameHeaderSize;
}
EXPECT_EQ(expected_payload_size, frames_[0]->header.payload_length);
}
}
// A frame with reserved flag(s) set that arrives in chunks should only have the
// reserved flag(s) set on the first chunk when split.
TEST_F(WebSocketBasicStreamSocketChunkedReadTest, ReservedFlagCleared) {
static const char kReservedFlagFrame[] = "\x41\x05Hello";
const size_t kReservedFlagFrameSize = base::size(kReservedFlagFrame) - 1;
const size_t kChunkSize = 5;
CreateChunkedRead(ASYNC,
kReservedFlagFrame,
kReservedFlagFrameSize,
kChunkSize,
2,
LAST_FRAME_BIG);
TestCompletionCallback cb[2];
ASSERT_THAT(stream_->ReadFrames(&frames_, cb[0].callback()),
IsError(ERR_IO_PENDING));
EXPECT_THAT(cb[0].WaitForResult(), IsOk());
ASSERT_EQ(1U, frames_.size());
EXPECT_TRUE(frames_[0]->header.reserved1);
frames_.clear();
ASSERT_THAT(stream_->ReadFrames(&frames_, cb[1].callback()),
IsError(ERR_IO_PENDING));
EXPECT_THAT(cb[1].WaitForResult(), IsOk());
ASSERT_EQ(1U, frames_.size());
EXPECT_FALSE(frames_[0]->header.reserved1);
}
// Check that writing a frame all at once works.
TEST_F(WebSocketBasicStreamSocketWriteTest, WriteAtOnce) {
MockWrite writes[] = {MockWrite(SYNCHRONOUS, kWriteFrame, kWriteFrameSize)};
CreateStream(base::span<MockRead>(), writes);
EXPECT_THAT(stream_->WriteFrames(&frames_, cb_.callback()), IsOk());
}
// Check that completely async writing works.
TEST_F(WebSocketBasicStreamSocketWriteTest, AsyncWriteAtOnce) {
MockWrite writes[] = {MockWrite(ASYNC, kWriteFrame, kWriteFrameSize)};
CreateStream(base::span<MockRead>(), writes);
ASSERT_THAT(stream_->WriteFrames(&frames_, cb_.callback()),
IsError(ERR_IO_PENDING));
EXPECT_THAT(cb_.WaitForResult(), IsOk());
}
// Check that writing a frame to an extremely full kernel buffer (so that it
// ends up being sent in bits) works. The WriteFrames() callback should not be
// called until all parts have been written.
TEST_F(WebSocketBasicStreamSocketWriteTest, WriteInBits) {
MockWrite writes[] = {MockWrite(SYNCHRONOUS, kWriteFrame, 4),
MockWrite(ASYNC, kWriteFrame + 4, 4),
MockWrite(ASYNC, kWriteFrame + 8, kWriteFrameSize - 8)};
CreateStream(base::span<MockRead>(), writes);
ASSERT_THAT(stream_->WriteFrames(&frames_, cb_.callback()),
IsError(ERR_IO_PENDING));
EXPECT_THAT(cb_.WaitForResult(), IsOk());
}
// Check that writing a Pong frame with a nullptr body works.
TEST_F(WebSocketBasicStreamSocketWriteTest, WriteNullptrPong) {
MockWrite writes[] = {
MockWrite(SYNCHRONOUS, kMaskedEmptyPong, kMaskedEmptyPongSize)};
CreateStream(base::span<MockRead>(), writes);
auto frame =
std::make_unique<WebSocketFrame>(WebSocketFrameHeader::kOpCodePong);
WebSocketFrameHeader& header = frame->header;
header.final = true;
header.masked = true;
header.payload_length = 0;
std::vector<std::unique_ptr<WebSocketFrame>> frames;
frames.push_back(std::move(frame));
EXPECT_THAT(stream_->WriteFrames(&frames, cb_.callback()), IsOk());
}
// Check that writing with a non-nullptr mask works correctly.
TEST_F(WebSocketBasicStreamSocketTest, WriteNonNulMask) {
std::string masked_frame = std::string("\x81\x88");
masked_frame += std::string(kNonNulMaskingKey.key, 4);
masked_frame += "jiggered";
MockWrite writes[] = {
MockWrite(SYNCHRONOUS, masked_frame.data(), masked_frame.size())};
generator_ = &GenerateNonNulMaskingKey;
CreateStream(base::span<MockRead>(), writes);
auto frame =
std::make_unique<WebSocketFrame>(WebSocketFrameHeader::kOpCodeText);
const std::string unmasked_payload = "graphics";
const size_t payload_size = unmasked_payload.size();
auto buffer = base::MakeRefCounted<IOBuffer>(payload_size);
memcpy(buffer->data(), unmasked_payload.data(), payload_size);
frame->payload = buffer->data();
WebSocketFrameHeader& header = frame->header;
header.final = true;
header.masked = true;
header.payload_length = payload_size;
frames_.push_back(std::move(frame));
EXPECT_THAT(stream_->WriteFrames(&frames_, cb_.callback()), IsOk());
}
TEST_F(WebSocketBasicStreamSocketTest, GetExtensionsWorks) {
extensions_ = "inflate-uuencode";
CreateStream(base::span<MockRead>(), base::span<MockWrite>());
EXPECT_EQ("inflate-uuencode", stream_->GetExtensions());
}
TEST_F(WebSocketBasicStreamSocketTest, GetSubProtocolWorks) {
sub_protocol_ = "cyberchat";
CreateStream(base::span<MockRead>(), base::span<MockWrite>());
EXPECT_EQ("cyberchat", stream_->GetSubProtocol());
}
} // namespace
} // namespace net
| bsd-3-clause |
wantedtobehaunted/replicator-clone | lib/utils.lua | 1517 |
function enum(names)
local rv = {}
for i, name in ipairs(names) do
rv[name] = i
end
return rv
end
function difference(num1, num2)
if num1 > num2 then
return num1 - num2
else
return num2 - num1
end
end
function concat(t1,t2)
for i = 1,#t2 do
t1[#t1+1] = t2[i]
end
return t1
end
function comparePosition(pos1, pos2)
return (pos1.x == pos2.x and pos1.y == pos2.y and pos1.z == pos2.z)
end
function copy(original)
local success, data = serpent.load(serpent.dump(original))
if not success then
error('Error copying data')
end
return data
end
RandomWalk = class('RandomWalk')
function RandomWalk:initialize(startingPos)
if startingPos then
self.position = startingPos
else
self.position = {x=0, y=0}
end
self.visited = {}
self.visited[self.position.x .. self.position.y] = true
end
function RandomWalk:next()
local pos = {x=self.position.x, y=self.position.y}
local moves = {
{'x', 1}, {'x', -1},
{'y', 1}, {'y', -1},
}
for i=1,4 do
local move = table.remove(moves, math.random(1, #moves))
pos[move[1]] = self.position[move[1]] + move[2]
if not self.visited[pos.x .. pos.y] then
self.visited[pos.x .. pos.y] = true
self.position = pos
return pos
end
end
return false
end
function isTurtle(item)
return item and (item.name == 'computercraft:CC-Turtle' or
item.name == 'computercraft:CC-TurtleExpanded' or
item.name == 'computercraft:CC-TurtleAdvanced')
end
| bsd-3-clause |
yubo/program | ds/计算几何模板/pku_1066_Treasure Hunt.cpp | 3649 | #include <stdio.h>
#include <iostream>
#include <math.h>
using namespace std;
#define eps 1e-6
struct TPoint
{
double x, y;
};
struct TLine
{
TPoint p1, p2;
};
double max(double x, double y)
{
//±È½ÏÁ½¸öÊýµÄ´óС£¬·µ»Ø´óµÄÊý
if(x > y) return x;
else return y;
}
double min(double x, double y)
{
//±È½ÏÁ½¸öÊýµÄ´óС£¬·µ»ØÐ¡µÄÊý
if(x < y) return x;
else return y;
}
double multi(TPoint p1, TPoint p2, TPoint p0)
{
//ÇóʸÁ¿[p0, p1], [p0, p2]µÄ²æ»ý
//p0ÊǶ¥µã
return (p1.x - p0.x) * (p2.y - p0.y) - (p2.x - p0.x) * (p1.y - p0.y);
//Èô½á¹ûµÈÓÚ0£¬ÔòÕâÈýµã¹²Ïß
//Èô½á¹û´óÓÚ0£¬Ôòp0p2ÔÚp0p1µÄÄæÊ±Õë·½Ïò
//Èô½á¹ûСÓÚ0£¬Ôòp0p2ÔÚp0p1µÄ˳ʱÕë·½Ïò
}
bool isIntersected(TPoint s1, TPoint e1, TPoint s2, TPoint e2)
{
//ÅжÏÏß¶ÎÊÇ·ñÏཻ
//1.¿ìËÙÅųâÊÔÑéÅжÏÒÔÁ½ÌõÏß¶ÎΪ¶Ô½ÇÏßµÄÁ½¸ö¾ØÐÎÊÇ·ñÏཻ
//2.¿çÁ¢ÊÔÑé
if(
(max(s1.x, e1.x) >= min(s2.x, e2.x)) &&
(max(s2.x, e2.x) >= min(s1.x, e1.x)) &&
(max(s1.y, e1.y) >= min(s2.y, e2.y)) &&
(max(s2.y, e2.y) >= min(s1.y, e1.y)) &&
(multi(s2, e1, s1) * multi(e1, e2, s1) >= 0) &&
(multi(s1, e2, s2) * multi(e2, e1, s2) >= 0)
) return true;
return false;
}
int main()
{
//freopen("in.in", "r", stdin);
//freopen("out.out", "w", stdout);
int ca, n, i, j, t, ltmp, qn;
double tmp[100];
TPoint p0, point[80];
TPoint Q[300];
TLine line[40];
while(scanf("%d", &n) != EOF){
t = 0;
for(i = 0;i < n;i++ ){
scanf("%lf%lf%lf%lf", &line[i].p1.x, &line[i].p1.y,
&line[i].p2.x, &line[i].p2.y);
point[t++] = line[i].p1;
point[t++] = line[i].p2;
}
scanf("%lf%lf", &p0.x, &p0.y);
//x = 0ÕâÌõÏßÉϵÄ
ltmp = 1;
tmp[0] = 0.0;
for(i = 0;i < t;i++){
if(fabs(point[i].x) < eps) tmp[ltmp++] = point[i].y;
}
tmp[ltmp++] = 100.0;
sort(tmp, tmp + ltmp);
qn = 0;
for(i = 1;i < ltmp;i++){
Q[qn].x = 0.0;
Q[qn++].y = (tmp[i - 1] + tmp[i]) / 2;
}
//y = 0ÕâÌõÏßÉÏ
ltmp = 1;
tmp[0]= 0.0;
for(i = 0;i < t;i++){
if(fabs(point[i].y) < eps) tmp[ltmp++] = point[i].x;
}
tmp[ltmp++] = 100.0;
sort(tmp, tmp + ltmp);
for(i = 1;i < ltmp;i++){
Q[qn].x = (tmp[i - 1] + tmp[i]) / 2;
Q[qn++].y = 0.0;
}
//x = 100 ÕâÌõÏßÉÏ
ltmp = 1;
tmp[0] = 0.0;
for(i = 0;i < t;i++){
if(fabs(point[i].x - 100) < eps) tmp[ltmp++] = point[i].y;
}
tmp[ltmp++] = 100.0;
sort(tmp, tmp + ltmp);
for(i = 1;i < ltmp;i++){
Q[qn].x = 100.0;
Q[qn++].y = (tmp[i - 1] + tmp[i]) / 2;
}
//y = 100ÕâÌõÏß
ltmp = 1;
tmp[0] = 0.0;
for(i = 0;i < t;i++){
if(fabs(point[i].y - 100.0) < eps) tmp[ltmp++] = point[i].x;
}
tmp[ltmp++] = 100.0;
sort(tmp, tmp + ltmp);
for(i = 1;i < ltmp;i++){
Q[qn].x = (tmp[i - 1] + tmp[i]) / 2;
Q[qn++].y = 100.0;
}
int ans = 9999999, ans1;
for(i = 0;i < qn;i++){
ans1 = 0;
for(j = 0;j < n;j++){
if(isIntersected(line[j].p1, line[j].p2, Q[i], p0)) ans1++;
}
if(ans1 < ans) ans = ans1;
}
printf("Number of doors = %d\n", ans + 1);
}
return 0;
}
| bsd-3-clause |
yuyichao/OpenBLAS | lapack-netlib/LAPACKE/src/lapacke_dormlq_work.c | 5079 | /*****************************************************************************
Copyright (c) 2014, Intel Corp.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Intel Corporation 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.
*****************************************************************************
* Contents: Native middle-level C interface to LAPACK function dormlq
* Author: Intel Corporation
* Generated November 2015
*****************************************************************************/
#include "lapacke_utils.h"
lapack_int LAPACKE_dormlq_work( int matrix_layout, char side, char trans,
lapack_int m, lapack_int n, lapack_int k,
const double* a, lapack_int lda,
const double* tau, double* c, lapack_int ldc,
double* work, lapack_int lwork )
{
lapack_int info = 0;
lapack_int r;
lapack_int lda_t, ldc_t;
double *a_t = NULL, *c_t = NULL;
if( matrix_layout == LAPACK_COL_MAJOR ) {
/* Call LAPACK function and adjust info */
LAPACK_dormlq( &side, &trans, &m, &n, &k, a, &lda, tau, c, &ldc, work,
&lwork, &info );
if( info < 0 ) {
info = info - 1;
}
} else if( matrix_layout == LAPACK_ROW_MAJOR ) {
r = LAPACKE_lsame( side, 'l' ) ? m : n;
lda_t = MAX(1,k);
ldc_t = MAX(1,m);
/* Check leading dimension(s) */
if( lda < r ) {
info = -8;
LAPACKE_xerbla( "LAPACKE_dormlq_work", info );
return info;
}
if( ldc < n ) {
info = -11;
LAPACKE_xerbla( "LAPACKE_dormlq_work", info );
return info;
}
/* Query optimal working array(s) size if requested */
if( lwork == -1 ) {
LAPACK_dormlq( &side, &trans, &m, &n, &k, a, &lda_t, tau, c, &ldc_t,
work, &lwork, &info );
return (info < 0) ? (info - 1) : info;
}
/* Allocate memory for temporary array(s) */
if( LAPACKE_lsame( side, 'l' ) ) {
a_t = (double*)LAPACKE_malloc( sizeof(double) * lda_t * MAX(1,m) );
} else {
a_t = (double*)LAPACKE_malloc( sizeof(double) * lda_t * MAX(1,n) );
}
if( a_t == NULL ) {
info = LAPACK_TRANSPOSE_MEMORY_ERROR;
goto exit_level_0;
}
c_t = (double*)LAPACKE_malloc( sizeof(double) * ldc_t * MAX(1,n) );
if( c_t == NULL ) {
info = LAPACK_TRANSPOSE_MEMORY_ERROR;
goto exit_level_1;
}
/* Transpose input matrices */
if( LAPACKE_lsame( side, 'l' ) ){
LAPACKE_dge_trans( matrix_layout, k, m, a, lda, a_t, lda_t );
} else {
LAPACKE_dge_trans( matrix_layout, k, n, a, lda, a_t, lda_t );
}
LAPACKE_dge_trans( matrix_layout, m, n, c, ldc, c_t, ldc_t );
/* Call LAPACK function and adjust info */
LAPACK_dormlq( &side, &trans, &m, &n, &k, a_t, &lda_t, tau, c_t, &ldc_t,
work, &lwork, &info );
if( info < 0 ) {
info = info - 1;
}
/* Transpose output matrices */
LAPACKE_dge_trans( LAPACK_COL_MAJOR, m, n, c_t, ldc_t, c, ldc );
/* Release memory and exit */
LAPACKE_free( c_t );
exit_level_1:
LAPACKE_free( a_t );
exit_level_0:
if( info == LAPACK_TRANSPOSE_MEMORY_ERROR ) {
LAPACKE_xerbla( "LAPACKE_dormlq_work", info );
}
} else {
info = -1;
LAPACKE_xerbla( "LAPACKE_dormlq_work", info );
}
return info;
}
| bsd-3-clause |
ryonley/codeconductor | public/css/style.css | 1496 | body {
padding-top: 60px;
padding-bottom: 40px;
}
.zf-green {
color: #68b604;
}
.btn-success {
background-color: #57a900;
background-image: -moz-linear-gradient(top, #70d900, #57a900);
background-image: -ms-linear-gradient(top, #70d900, #57a900);
background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#70d900), to(#57a900));
background-image: -webkit-linear-gradient(top, #70d900, #57a900);
background-image: -o-linear-gradient(top, #70d900, #57a900);
background-image: linear-gradient(top, #70d900, #57a900);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#70d900', endColorstr='#57a900', GradientType=0);
}
.btn-success:hover,
.btn-success:active,
.btn-success.active,
.btn-success.disabled,
.btn-success[disabled] {
background-color: #57a900;
}
.btn-success:active, .btn-success.active {
background-color: #57a900;
}
div.container a.brand {
background: url("../img/cclogo.png") no-repeat scroll 0 5px transparent;
margin-left: 0;
padding: 10px 20px 10px 28px;
}
/*************************************************************/
.border-right{
border-right: 2px solid #000;
}
.border-bottom{
border-bottom: 2px solid #000;
}
.border-left{
border-left: 2px solid #000;
}
#gameboard {
}
#gameboard td {
width: 10px;
height: 10px;
padding: 20px;
}
.enabled {
cursor: pointer;
}
#gameboard td.enabled:hover {
background-color: #d0d0d0;
}
.highlight{
background-color: yellow;
} | bsd-3-clause |
chunshen1987/DistributionSampling | src/Distribution.h | 2908 | /*=========================================================================
*
* Copyright 2011-2013 The University of North Carolina at Chapel Hill
* All rights reserved.
*
* Licensed under the MADAI Software License. You may obtain a copy of
* this license at
*
* https://madai-public.cs.unc.edu/visualization/software-license/
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef madai_Distribution_h_included
#define madai_Distribution_h_included
#include "Random.h"
namespace madai {
/** \class Distribution
*
* Base class for distributions. */
class Distribution {
public:
Distribution();
virtual ~Distribution();
/** Return a copy of this object.
*
* The caller is responsible for deleting the object with the
* operator 'delete'.
* \return A copy of this object. */
virtual Distribution * Clone() const = 0;
/** Get the log of the probability density function evaluated at x.
*
* \param x The argument to the probability density function.
* \return The log of the probability density function evaluated at
* x. */
virtual double GetLogProbabilityDensity(double x) const = 0;
/** Get the derivative of the log of the probability density function
* evaluated at x.
*
* \param x The argument to the probability density function.
* return The derivative of the log of the probability density.
*/
virtual double GetGradientLogProbabilityDensity(double x) const = 0;
/** Get the probability density function evaluated at x.
*
* \param x The argument to the probability density function.
* \return The result of evaluating the probability density function
* at x. */
virtual double GetProbabilityDensity(double x) const = 0;
/** Get the percentile for the given argument.
*
* Returns the value at which the cumulative distribution function
* equals the input argument.
*
* \param percentile The percentage of the distribution in the range
[0, 1].
* \return The percentile value. */
virtual double GetPercentile(double percentile) const = 0;
/** Get a random sample from this distribution
*
* \param r An instance of the Random generator class.
* \return The random sample from the distribution. */
virtual double GetSample(madai::Random & r) const = 0;
/**
Returns E[x] */
virtual double GetExpectedValue() const = 0;
/**
Returns sqrt(E[(x - E[x])^2]) */
virtual double GetStandardDeviation() const = 0;
protected:
};
} // namespace madai
#endif // madai_Distribution_h_included
| bsd-3-clause |
paul99/clank | gpu/command_buffer/common/constants.h | 1508 | // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef GPU_COMMAND_BUFFER_COMMON_CONSTANTS_H_
#define GPU_COMMAND_BUFFER_COMMON_CONSTANTS_H_
#include "../common/types.h"
namespace gpu {
typedef int32 CommandBufferOffset;
const CommandBufferOffset kInvalidCommandBufferOffset = -1;
// This enum must stay in sync with NPDeviceContext3DError.
namespace error {
enum Error {
kNoError,
kInvalidSize,
kOutOfBounds,
kUnknownCommand,
kInvalidArguments,
kLostContext,
kGenericError,
kDeferCommandUntilSwapBuffersAck
};
// Return true if the given error code is an actual error.
inline bool IsError(Error error) {
return error != kNoError && error != kDeferCommandUntilSwapBuffersAck;
}
// Provides finer grained information about why the context was lost.
enum ContextLostReason {
// This context definitely provoked the loss of context.
kGuilty,
// This context definitely did not provoke the loss of context.
kInnocent,
// It is unknown whether this context provoked the loss of context.
kUnknown
};
}
// Invalid shared memory Id, returned by RegisterSharedMemory in case of
// failure.
const int32 kInvalidSharedMemoryId = -1;
// Common Command Buffer shared memory transfer buffer ID.
const int32 kCommandBufferSharedMemoryId = 4;
} // namespace gpu
#endif // GPU_COMMAND_BUFFER_COMMON_CONSTANTS_H_
| bsd-3-clause |
timbod7/veditor | ErrVal.hs | 1843 | module ErrVal where
-- ErrVal captures a value, or an error state indicating
-- that the value could not be computed. The error state
-- includes a "reason" message and context information on
-- where the error occurred.
--
-- Instances of Functor, Applicative, Monad, Num, and Fractional are
-- provided.
import Control.Monad
import Control.Applicative
data ErrVal a = EValue a
| Error { ereason :: String, econtext :: [String] }
deriving (Eq,Ord,Show)
instance Functor ErrVal where
fmap f (EValue a) = EValue (f a)
fmap _ (Error e c) = Error e c
instance Applicative ErrVal where
pure = EValue
(EValue f) <*> (EValue a) = EValue (f a)
(Error e c) <*> _ = Error e c
_ <*> (Error e c) = Error e c
instance Monad ErrVal where
return = pure
(EValue a) >>= f = f a
(Error e c ) >>= f = Error e c
eVal a = EValue a
eErr s = Error s []
eContext :: String -> ErrVal a -> ErrVal a
eContext c ev@(EValue v) = ev
eContext c (Error msg cs) = Error msg (c:cs)
evMaybe :: Maybe a -> String -> ErrVal a
evMaybe (Just v) _ = eVal v
evMaybe _ s = eErr s
evFilter :: [ErrVal a] -> [a]
evFilter = foldr f []
where
f (EValue a) as = a:as
f _ as= as
evlift1 :: (a->a) -> ErrVal a -> ErrVal a
evlift1 f e = pure f <*> e
evlift2 :: (a->a->a) -> ErrVal a -> ErrVal a -> ErrVal a
evlift2 f e1 e2 = pure f <*> e1 <*> e2
instance Num a => Num (ErrVal a) where
(+) = evlift2 (+)
(-) = evlift2 (-)
(*) = evlift2 (*)
negate = evlift1 negate
abs = evlift1 abs
signum = evlift1 signum
fromInteger i = eVal (fromInteger i)
instance Fractional a => Fractional (ErrVal a) where
fromRational r = eVal (fromRational r)
(/) = evlift2 (/)
errval :: (a -> b) -> (String -> b) -> (ErrVal a) -> b
errval fa fe (EValue a) = fa a
errval fa fe (Error e c) = fe e
| bsd-3-clause |
NCIP/c3pr | codebase/projects/core/db/SQLServer/static-data-delete.sql | 280 | DELETE FROM CONTACT_MECHANISMS;
DELETE FROM RESEARCH_STAFF;
DELETE FROM HC_SITE_INVESTIGATORS;
DELETE FROM INVESTIGATORS;
DELETE FROM IDENTIFIERS;
DELETE FROM ORGANIZATIONS WHERE ID BETWEEN 10000 AND 10005;
DELETE FROM ADDRESSES WHERE ID BETWEEN 10000 AND 10005; | bsd-3-clause |
suiGn/orgboat | cod/php/add_rectsk.php | 4190 | <?php
/*
* recurrent homeworks
* */
include "utils.php";
session_start();
//si no hay sesion iniciada
if(!isset($_SESSION["usrUserName"]) )
{
//retornar al index (login)
header("location: ../../index.php");
exit();
}
//verificar que viene el campo activity del form
if(isset($_POST["cmb_activity"] ))
{
$task = mysql_real_escape_string($_POST['recTaskName']);
$remind_by = mysql_real_escape_string($_POST['dayWeekMonth']);
//obtener el dato dependiendo si sera por semana o por mes
if($remind_by == 'weekly')
{
//dia en que se asignara
$remind_day = mysql_real_escape_string($_POST['week_day']);
}
else
{
//dia en que se asignara la tarea
$remind_day = mysql_real_escape_string($_POST['monthDay']);
}
//dia que se debera realizar dicha actividad
if($remind_by == 'weekly')
{
//dia en que se realizara
$due_day = mysql_real_escape_string($_POST['due_weekday']);
}
else
{
//dia en que se asignara
$due_day = mysql_real_escape_string($_POST['monthly_day']);
}
$points = mysql_real_escape_string($_POST["hw_points"]);
$actID = mysql_real_escape_string($_POST["cmb_activity"]);
$type_hw = mysql_real_escape_string($_POST["type_hw"]);
$asignatorID = $_SESSION['usrID'];
$profileID = $_SESSION['profileID'];
$notify = isset($_POST["notify"]);
$result = mysql_query("INSERT into recurringTasks (task, remind_by, remind_day, due_day, notify_email, actID, asignatorID, state, points, type)
values ('$task','$remind_by', '$remind_day', '$due_day', '$notify', '$actID', '$asignatorID', 'assigned', '$points', '$type_hw')");
//ATENCION: AQUI IRA LA CONSULTA DE INSERCION DE EVENTO EN MYSQL
if(isset($_POST["notify"]))
{
$email = get_value('usrTable', 'usrEmail', 'usrID', $profileID);
$body = "
<html>
<head>
<title> OrgBoat Recurrent Task </title>
<style>
p {font-family: 'Courier New', Courier, 'Lucida Sans Typewriter', 'Lucida Typewriter', monospace; color:#4F4F4F;}
h3 {
font-size: 16px;
line-height: 1.5em;
color: #2D465F;
font-family: Courier New;
font-style: normal;
font-weight: bold;
}
h5 {
color:#000000;
}
h6 {
color:#000000;
}
</style>
</head>
<body>
<h3>OrgBoat</h3>
<p>You have been assigned a new task:</p></br>
<p> - $task.</p></br>
<h5>Visit:http://www.orgboat.com to see it.</br>
Do Not Reply to this e-mail address.</h5>
</body>
</html>";
$headers = 'Content-type: text/html; charset=iso-8859-1' . "\r\n".
'From: [email protected]' . "\r\n" .
'Reply-To: [email protected]' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($email, "New Task", $body , $headers);
}
//if this homework is public
if($type_hw == 'Public')
{
if($assignator == -1)
{
$assignatorName = "Admin";
}
else
{
$assignatorName = get_value('usrTable', 'usrUserName', 'usrID', $assignator);
}
/*
//agregar esta accion a newsTable
$creatorID = $_SESSION["usrID"];
$divID = get_value('usrTable', 'divID', 'usrID', $usrID);
$usrUserName = get_value('usrTable', 'usrUserName', 'usrID', $usrID);
mysql_query("insert into newsTable(title, description, newdate, divID, creatorID)
values('Added homework', 'The homework $hmwrk was added to the user $usrUserName',
NOW(), '$divID', '$creatorID') ");
*/
}
if($result)
header("location: ../../web/admin.php?msg=Recurring task added !&tabpage=1");
else
header("location: ../../web/admin.php?error=Sorry something went wrong!&tabpage=1");
}
else
{
header("location: ../../web/admin.php?error=No POST data on add_rescttsk.php&tabpage=1");
}
?>
</body>
</html>
| bsd-3-clause |
merlin86/TeamPlanets | bots/sage0/sagebot.hpp | 3431 | // sagebot.hpp - SageBot class definition
// sage - A TeamPlanets bot written for MachineZone job application
//
// Copyright (c) 2015 Vadim Litvinov <[email protected]>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. Neither the name of the author 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 AUTHOR AND CONTRIBUTORS ``AS IS'' AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
// OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE.
#ifndef _TEAMPLANETS_SAGE_SAGE_HPP_
#define _TEAMPLANETS_SAGE_SAGE_HPP_
#include <vector>
#include "bot.hpp"
#include "utils.hpp"
namespace sage {
class SageBot: public Bot {
private:
typedef std::vector<team_planets::planet_id> neighbors_list;
typedef std::vector<neighbors_list> neighborhoods_list;
public:
DISABLE_COPY(SageBot)
SageBot(): num_ships_per_reinforcement_(10), planets_mean_distance_(0),
neighborhood_radius_multiplier_(1), neighborhood_radius_(0) {}
virtual ~SageBot() {}
protected:
virtual void init_();
virtual void perform_turn_();
neighbors_list& neighbors_(team_planets::planet_id planet) { return neighborhoods_[planet - 1]; }
const neighbors_list& neighbors_(team_planets::planet_id planet) const { return neighborhoods_[planet - 1]; }
bool is_frontline_(team_planets::planet_id id) const;
unsigned int num_ships_to_take_a_planet_(team_planets::planet_id src, team_planets::planet_id dst) const;
void take_attack_decisions_();
void process_backline_planet_(team_planets::planet_id id);
private:
unsigned int compute_planets_mean_distance_() const;
void compute_planets_neighborhoods_();
// User defined bot parameters
const unsigned int num_ships_per_reinforcement_;
// Precomputed map parameters
unsigned int planets_mean_distance_;
unsigned int neighborhood_radius_multiplier_;
unsigned int neighborhood_radius_;
// Precomputed planets neighborhoods
neighborhoods_list neighborhoods_;
// Per turn data structures
std::vector<team_planets::planet_id> frontline_planets_;
std::vector<team_planets::planet_id> backline_planets_;
};
}
#endif
| bsd-3-clause |
wangxin39/xstat | XStatAPI/docs/api/cn/iaicc/smgk/dao/ISmgkHistoryInfoDao.html | 14060 | <!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_05) on Mon Sep 15 09:30:36 CST 2008 -->
<TITLE>
ISmgkHistoryInfoDao (ÉñÃØ¹Ë¿Í¹ÜÀíÆ½Ì¨ API)
</TITLE>
<META NAME="date" CONTENT="2008-09-15">
<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="ISmgkHistoryInfoDao (ÉñÃØ¹Ë¿Í¹ÜÀíÆ½Ì¨ API)";
}
}
</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="Ìø¹ýµ¼º½Á´½Ó"></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>¸ÅÊö</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Èí¼þ°ü</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Àà</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/ISmgkHistoryInfoDao.html"><FONT CLASS="NavBarFont1"><B>ʹÓÃ</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Ê÷</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Òѹýʱ</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Ë÷Òý</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>°ïÖú</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../cn/iaicc/smgk/dao/ISitePopedomInfoDao.html" title="cn.iaicc.smgk.dao ÖеĽӿÚ"><B>ÉÏÒ»¸öÀà</B></A>
<A HREF="../../../../cn/iaicc/smgk/dao/ISmgkInfoDao.html" title="cn.iaicc.smgk.dao ÖеĽӿÚ"><B>ÏÂÒ»¸öÀà</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?cn/iaicc/smgk/dao/ISmgkHistoryInfoDao.html" target="_top"><B>¿ò¼Ü</B></A>
<A HREF="ISmgkHistoryInfoDao.html" target="_top"><B>ÎÞ¿ò¼Ü</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>ËùÓÐÀà</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>ËùÓÐÀà</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
ÕªÒª£º ǶÌ× | ×Ö¶Î | ¹¹Ôì·½·¨ | <A HREF="#method_summary">·½·¨</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
ÏêϸÐÅÏ¢£º ×Ö¶Î | ¹¹Ôì·½·¨ | <A HREF="#method_detail">·½·¨</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<!-- ======== START OF CLASS DATA ======== -->
<H2>
<FONT SIZE="-1">
cn.iaicc.smgk.dao</FONT>
<BR>
½Ó¿Ú ISmgkHistoryInfoDao</H2>
<DL>
<DT><B>ËùÓÐÒÑ֪ʵÏÖÀࣺ</B> <DD><A HREF="../../../../cn/iaicc/smgk/dao/hibernate/SmgkHistoryInfoDao.html" title="cn.iaicc.smgk.dao.hibernate ÖеÄÀà">SmgkHistoryInfoDao</A></DD>
</DL>
<HR>
<DL>
<DT><PRE>public interface <B>ISmgkHistoryInfoDao</B></DL>
</PRE>
<P>
<HR>
<P>
<!-- ========== METHOD SUMMARY =========== -->
<A NAME="method_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>·½·¨ÕªÒª</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../cn/iaicc/smgk/dao/ISmgkHistoryInfoDao.html#delete(cn.iaicc.smgk.po.SmgkHistoryInfo)">delete</A></B>(<A HREF="../../../../cn/iaicc/smgk/po/SmgkHistoryInfo.html" title="cn.iaicc.smgk.po ÖеÄÀà">SmgkHistoryInfo</A> data)</CODE>
<BR>
ɾ³ýÉñÃØ¹Ë¿Í²âÊÔÃ÷ϸÐÅÏ¢</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> java.util.List<<A HREF="../../../../cn/iaicc/smgk/po/SmgkHistoryInfo.html" title="cn.iaicc.smgk.po ÖеÄÀà">SmgkHistoryInfo</A>></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../cn/iaicc/smgk/dao/ISmgkHistoryInfoDao.html#findByPage(int, int)">findByPage</A></B>(int firstResult,
int maxResult)</CODE>
<BR>
ͨ¹ýÖ¸¶¨µÄÆðʼÊýºÍ½áÊøÊýµÃµ½Ò»¸ö¼¯ºÏ</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../cn/iaicc/smgk/po/SmgkHistoryInfo.html" title="cn.iaicc.smgk.po ÖеÄÀà">SmgkHistoryInfo</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../cn/iaicc/smgk/dao/ISmgkHistoryInfoDao.html#getSmgkHistoryInfo(java.lang.Long)">getSmgkHistoryInfo</A></B>(java.lang.Long testHistoryID)</CODE>
<BR>
»ñÈ¡ÉñÃØ¹Ë¿Í²âÊÔÃ÷ϸÐÅÏ¢</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> java.util.List<<A HREF="../../../../cn/iaicc/smgk/po/SmgkHistoryInfo.html" title="cn.iaicc.smgk.po ÖеÄÀà">SmgkHistoryInfo</A>></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../cn/iaicc/smgk/dao/ISmgkHistoryInfoDao.html#getSmgkHistoryInfoList()">getSmgkHistoryInfoList</A></B>()</CODE>
<BR>
»ñÈ¡ÉñÃØ¹Ë¿Í²âÊÔÃ÷ϸÐÅÏ¢Áбí</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../cn/iaicc/smgk/dao/ISmgkHistoryInfoDao.html#getTotal()">getTotal</A></B>()</CODE>
<BR>
ͨ¹ýÖ¸¶¨µÄÆðʼÊý»ñÈ¡×ܼ¯ºÏ</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../cn/iaicc/smgk/dao/ISmgkHistoryInfoDao.html#save(cn.iaicc.smgk.po.SmgkHistoryInfo)">save</A></B>(<A HREF="../../../../cn/iaicc/smgk/po/SmgkHistoryInfo.html" title="cn.iaicc.smgk.po ÖеÄÀà">SmgkHistoryInfo</A> data)</CODE>
<BR>
±£´æÉñÃØ¹Ë¿Í²âÊÔÃ÷ϸÐÅÏ¢</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../cn/iaicc/smgk/dao/ISmgkHistoryInfoDao.html#update(cn.iaicc.smgk.po.SmgkHistoryInfo)">update</A></B>(<A HREF="../../../../cn/iaicc/smgk/po/SmgkHistoryInfo.html" title="cn.iaicc.smgk.po ÖеÄÀà">SmgkHistoryInfo</A> data)</CODE>
<BR>
¸üÐÂÉñÃØ¹Ë¿Í²âÊÔÃ÷ϸÐÅÏ¢</TD>
</TR>
</TABLE>
<P>
<!-- ============ METHOD DETAIL ========== -->
<A NAME="method_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>·½·¨ÏêϸÐÅÏ¢</B></FONT></TH>
</TR>
</TABLE>
<A NAME="save(cn.iaicc.smgk.po.SmgkHistoryInfo)"><!-- --></A><H3>
save</H3>
<PRE>
void <B>save</B>(<A HREF="../../../../cn/iaicc/smgk/po/SmgkHistoryInfo.html" title="cn.iaicc.smgk.po ÖеÄÀà">SmgkHistoryInfo</A> data)</PRE>
<DL>
<DD>±£´æÉñÃØ¹Ë¿Í²âÊÔÃ÷ϸÐÅÏ¢
<P>
<DD><DL>
<DT><B>²ÎÊý£º</B><DD><CODE>data</CODE> - ÉñÃØ¹Ë¿Í²âÊÔÃ÷ϸÐÅÏ¢</DL>
</DD>
</DL>
<HR>
<A NAME="update(cn.iaicc.smgk.po.SmgkHistoryInfo)"><!-- --></A><H3>
update</H3>
<PRE>
void <B>update</B>(<A HREF="../../../../cn/iaicc/smgk/po/SmgkHistoryInfo.html" title="cn.iaicc.smgk.po ÖеÄÀà">SmgkHistoryInfo</A> data)</PRE>
<DL>
<DD>¸üÐÂÉñÃØ¹Ë¿Í²âÊÔÃ÷ϸÐÅÏ¢
<P>
<DD><DL>
<DT><B>²ÎÊý£º</B><DD><CODE>data</CODE> - ÉñÃØ¹Ë¿Í²âÊÔÃ÷ϸÐÅÏ¢</DL>
</DD>
</DL>
<HR>
<A NAME="delete(cn.iaicc.smgk.po.SmgkHistoryInfo)"><!-- --></A><H3>
delete</H3>
<PRE>
void <B>delete</B>(<A HREF="../../../../cn/iaicc/smgk/po/SmgkHistoryInfo.html" title="cn.iaicc.smgk.po ÖеÄÀà">SmgkHistoryInfo</A> data)</PRE>
<DL>
<DD>ɾ³ýÉñÃØ¹Ë¿Í²âÊÔÃ÷ϸÐÅÏ¢
<P>
<DD><DL>
<DT><B>²ÎÊý£º</B><DD><CODE>data</CODE> - ÉñÃØ¹Ë¿Í²âÊÔÃ÷ϸÐÅÏ¢</DL>
</DD>
</DL>
<HR>
<A NAME="getSmgkHistoryInfo(java.lang.Long)"><!-- --></A><H3>
getSmgkHistoryInfo</H3>
<PRE>
<A HREF="../../../../cn/iaicc/smgk/po/SmgkHistoryInfo.html" title="cn.iaicc.smgk.po ÖеÄÀà">SmgkHistoryInfo</A> <B>getSmgkHistoryInfo</B>(java.lang.Long testHistoryID)</PRE>
<DL>
<DD>»ñÈ¡ÉñÃØ¹Ë¿Í²âÊÔÃ÷ϸÐÅÏ¢
<P>
<DD><DL>
<DT><B>²ÎÊý£º</B><DD><CODE>testHistoryID</CODE> - ÉñÃØ¹Ë¿Í²âÊÔÃ÷ϸÐÅÏ¢±àºÅ
<DT><B>·µ»Ø£º</B><DD>ÉñÃØ¹Ë¿Í²âÊÔÃ÷ϸÐÅÏ¢</DL>
</DD>
</DL>
<HR>
<A NAME="getSmgkHistoryInfoList()"><!-- --></A><H3>
getSmgkHistoryInfoList</H3>
<PRE>
java.util.List<<A HREF="../../../../cn/iaicc/smgk/po/SmgkHistoryInfo.html" title="cn.iaicc.smgk.po ÖеÄÀà">SmgkHistoryInfo</A>> <B>getSmgkHistoryInfoList</B>()</PRE>
<DL>
<DD>»ñÈ¡ÉñÃØ¹Ë¿Í²âÊÔÃ÷ϸÐÅÏ¢Áбí
<P>
<DD><DL>
<DT><B>·µ»Ø£º</B><DD>ÉñÃØ¹Ë¿Í²âÊÔÃ÷ϸÐÅÏ¢Áбí</DL>
</DD>
</DL>
<HR>
<A NAME="findByPage(int, int)"><!-- --></A><H3>
findByPage</H3>
<PRE>
java.util.List<<A HREF="../../../../cn/iaicc/smgk/po/SmgkHistoryInfo.html" title="cn.iaicc.smgk.po ÖеÄÀà">SmgkHistoryInfo</A>> <B>findByPage</B>(int firstResult,
int maxResult)</PRE>
<DL>
<DD>ͨ¹ýÖ¸¶¨µÄÆðʼÊýºÍ½áÊøÊýµÃµ½Ò»¸ö¼¯ºÏ
<P>
<DD><DL>
<DT><B>²ÎÊý£º</B><DD><CODE>firstResult</CODE> - ¿ªÊ¼Ò³<DD><CODE>maxResult</CODE> -
<DT><B>·µ»Ø£º</B><DD>ÉñÃØ¹Ë¿Í²âÊÔÃ÷ϸÐÅÏ¢</DL>
</DD>
</DL>
<HR>
<A NAME="getTotal()"><!-- --></A><H3>
getTotal</H3>
<PRE>
int <B>getTotal</B>()</PRE>
<DL>
<DD>ͨ¹ýÖ¸¶¨µÄÆðʼÊý»ñÈ¡×ܼ¯ºÏ
<P>
<DD><DL>
<DT><B>·µ»Ø£º</B><DD>×ÜÊý</DL>
</DD>
</DL>
<!-- ========= END OF CLASS DATA ========= -->
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Ìø¹ýµ¼º½Á´½Ó"></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>¸ÅÊö</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Èí¼þ°ü</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Àà</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/ISmgkHistoryInfoDao.html"><FONT CLASS="NavBarFont1"><B>ʹÓÃ</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Ê÷</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Òѹýʱ</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Ë÷Òý</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>°ïÖú</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../cn/iaicc/smgk/dao/ISitePopedomInfoDao.html" title="cn.iaicc.smgk.dao ÖеĽӿÚ"><B>ÉÏÒ»¸öÀà</B></A>
<A HREF="../../../../cn/iaicc/smgk/dao/ISmgkInfoDao.html" title="cn.iaicc.smgk.dao ÖеĽӿÚ"><B>ÏÂÒ»¸öÀà</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?cn/iaicc/smgk/dao/ISmgkHistoryInfoDao.html" target="_top"><B>¿ò¼Ü</B></A>
<A HREF="ISmgkHistoryInfoDao.html" target="_top"><B>ÎÞ¿ò¼Ü</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>ËùÓÐÀà</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>ËùÓÐÀà</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
ÕªÒª£º ǶÌ× | ×Ö¶Î | ¹¹Ôì·½·¨ | <A HREF="#method_summary">·½·¨</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
ÏêϸÐÅÏ¢£º ×Ö¶Î | ¹¹Ôì·½·¨ | <A HREF="#method_detail">·½·¨</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
<i>Copyright © 2008 ±±¾©°¬µÏÖÇÈíÐÅÏ¢¼¼ÊõÓÐÏÞÔðÈι«Ë¾. All Rights Reserved.</i><br/><i><a href=http://www.idea-soft.cn target=_blank>http://www.idea-soft.cn</a></i> <i><a href=http://www.iaicc.cn target=_blank>http://www.iaicc.cn</a></i> <i><a href=http://www.xsaas.org target=_blank>http://www.xsaas.org</a></i>
</BODY>
</HTML>
| bsd-3-clause |
jakefoster/ncore-ioc | src/_unittests.org.ncore.Ioc/NewTests.cs | 6200 | using System;
using System.Configuration;
using System.Diagnostics;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using org.ncore.Ioc;
namespace _unittests.org.ncore.Ioc
{
/// <summary>
/// Summary description for NewTests
/// </summary>
[TestClass]
public class NewTests
{
public NewTests()
{
//
// TODO: Add constructor logic here
//
}
private TestContext testContextInstance;
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
#region Additional test attributes
//
// You can use the following additional attributes as you write your tests:
//
// Use ClassInitialize to run code before running the first test in the class
// [ClassInitialize()]
// public static void MyClassInitialize(TestContext testContext) { }
//
// Use ClassCleanup to run code after all tests in a class have run
// [ClassCleanup()]
// public static void MyClassCleanup() { }
//
// Use TestInitialize to run code before running each test
// [TestInitialize()]
// public void MyTestInitialize() { }
//
// Use TestCleanup to run code after each test has run
// [TestCleanup()]
// public void MyTestCleanup() { }
//
#endregion
[TestMethod]
public void Instance_dynamic_works_creates_new()
{
// ARRANGE
Locator.Registry.Clear();
Locator.Add( new LocatorType( "MyClass", typeof( MyClassA ) ) { AllowSave = false } );
// ACT
dynamic myClass = New.Instance( "MyClass" );
string greeting = myClass.Greet( "Uni" );
// ASSERT
Assert.AreEqual( "Hello Uni from MyClassA", greeting );
Assert.IsNull( Locator.Registry[ "MyClass" ].Instance );
}
[TestMethod]
public void Instance_dynamic_works_creates_new_with_anonymous_injector_registry()
{
// ARRANGE
Locator.Registry.Clear();
Locator.Add( new LocatorType( "MyClass", typeof( MyClassA ) ) { AllowSave = false } );
// ACT
dynamic myClass = New.Instance( "MyClass", new { FieldA = "Inject this value", ParamB = "Inject this too" } );
string greeting = myClass.Greet( "Uni" );
// ASSERT
Assert.AreEqual( "Hello Uni from MyClassA", greeting );
Assert.IsNull( Locator.Registry[ "MyClass" ].Instance );
}
[TestMethod]
public void Instance_dynamic_works_creates_new_with_typed_injector_registry()
{
// ARRANGE
Locator.Registry.Clear();
Locator.Add( new LocatorType( "MyClass", typeof( MyClassA ) ) { AllowSave = false } );
// ACT
dynamic myClass = New.Instance( "MyClass",
new InjectorRegistry{
{ "FieldA", "Inject this value" },
{ "PropertyB", "Inject this too" }
} );
string greeting = myClass.Greet( "Uni" );
// ASSERT
Assert.AreEqual( "Hello Uni from MyClassA", greeting );
Assert.IsNull( Locator.Registry[ "MyClass" ].Instance );
}
[TestMethod]
public void Instance_dynamic_works_creates_new_with_constructor_params()
{
// ARRANGE
Locator.Registry.Clear();
Locator.Add( new LocatorType( "MyClass", typeof( MyClassA ) ) { AllowSave = false } );
// ACT
dynamic myClass = New.Instance( "MyClass", constructorParams: new object[] { "My ParamA value", "My ParamB value" } );
string greeting = myClass.Greet( "Uni" );
// ASSERT
Assert.AreEqual( "Hello Uni from MyClassA", greeting );
Assert.IsNull( Locator.Registry[ "MyClass" ].Instance );
}
[TestMethod]
public void Instance_typed_from_type_works_creates_new()
{
// ARRANGE
Locator.Registry.Clear();
Locator.Add( new LocatorType( typeof( IMyClass ), typeof( MyClassA ) ) { AllowSave = false } );
// ACT
IMyClass myClass = New.Instance<IMyClass>();
string greeting = myClass.Greet( "Uni" );
// ASSERT
Assert.AreEqual( "Hello Uni from MyClassA", greeting );
Assert.IsNull( Locator.Registry[ typeof( IMyClass ).FullName ].Instance );
}
[TestMethod]
public void Instance_typed_from_string_works_creates_new()
{
// ARRANGE
Locator.Registry.Clear();
Locator.Add( new LocatorType( "MyClass", typeof( MyClassA ) ) { AllowSave = false } );
// ACT
IMyClass myClass = New.Instance<IMyClass>("MyClass");
string greeting = myClass.Greet( "Uni" );
// ASSERT
Assert.AreEqual( "Hello Uni from MyClassA", greeting );
Assert.IsNull( Locator.Registry[ "MyClass" ].Instance );
}
public interface IMyClass
{
string Greet( string name );
}
public class MyClassA : IMyClass
{
public string Greeter = "MyClassA";
public string FieldA;
public string PropertyB {get;set;}
public string Greet( string name )
{
return "Hello " + name + " from " + Greeter;
}
public MyClassA()
{ }
public MyClassA( string paramA, string paramB )
{
FieldA = paramA;
PropertyB = paramB;
}
}
}
}
| bsd-3-clause |
loopCM/chromium | webkit/appcache/appcache_url_request_job_unittest.cc | 27756 | // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <stack>
#include <utility>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/callback.h"
#include "base/compiler_specific.h"
#include "base/pickle.h"
#include "base/synchronization/waitable_event.h"
#include "base/threading/thread.h"
#include "net/base/io_buffer.h"
#include "net/base/net_errors.h"
#include "net/http/http_response_headers.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_error_job.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webkit/appcache/appcache_response.h"
#include "webkit/appcache/appcache_url_request_job.h"
#include "webkit/appcache/mock_appcache_service.h"
using net::IOBuffer;
using net::WrappedIOBuffer;
namespace appcache {
static const char kHttpBasicHeaders[] =
"HTTP/1.0 200 OK\0Content-Length: 5\0\0";
static const char kHttpBasicBody[] = "Hello";
static const int kNumBlocks = 4;
static const int kBlockSize = 1024;
class AppCacheURLRequestJobTest : public testing::Test {
public:
// Test Harness -------------------------------------------------------------
// TODO(michaeln): share this test harness with AppCacheResponseTest
class MockStorageDelegate : public AppCacheStorage::Delegate {
public:
explicit MockStorageDelegate(AppCacheURLRequestJobTest* test)
: loaded_info_id_(0), test_(test) {
}
virtual void OnResponseInfoLoaded(AppCacheResponseInfo* info,
int64 response_id) OVERRIDE {
loaded_info_ = info;
loaded_info_id_ = response_id;
test_->ScheduleNextTask();
}
scoped_refptr<AppCacheResponseInfo> loaded_info_;
int64 loaded_info_id_;
AppCacheURLRequestJobTest* test_;
};
class MockURLRequestDelegate : public net::URLRequest::Delegate {
public:
explicit MockURLRequestDelegate(AppCacheURLRequestJobTest* test)
: test_(test),
received_data_(new net::IOBuffer(kNumBlocks * kBlockSize)),
did_receive_headers_(false), amount_received_(0),
kill_after_amount_received_(0), kill_with_io_pending_(false) {
}
virtual void OnResponseStarted(net::URLRequest* request) OVERRIDE {
amount_received_ = 0;
did_receive_headers_ = false;
if (request->status().is_success()) {
EXPECT_TRUE(request->response_headers());
did_receive_headers_ = true;
received_info_ = request->response_info();
ReadSome(request);
} else {
RequestComplete();
}
}
virtual void OnReadCompleted(net::URLRequest* request,
int bytes_read) OVERRIDE {
if (bytes_read > 0) {
amount_received_ += bytes_read;
if (kill_after_amount_received_ && !kill_with_io_pending_) {
if (amount_received_ >= kill_after_amount_received_) {
request->Cancel();
return;
}
}
ReadSome(request);
if (kill_after_amount_received_ && kill_with_io_pending_) {
if (amount_received_ >= kill_after_amount_received_) {
request->Cancel();
return;
}
}
} else {
RequestComplete();
}
}
void ReadSome(net::URLRequest* request) {
DCHECK(amount_received_ + kBlockSize <= kNumBlocks * kBlockSize);
scoped_refptr<IOBuffer> wrapped_buffer(
new net::WrappedIOBuffer(received_data_->data() + amount_received_));
int bytes_read = 0;
EXPECT_FALSE(request->Read(wrapped_buffer, kBlockSize, &bytes_read));
EXPECT_EQ(0, bytes_read);
}
void RequestComplete() {
test_->ScheduleNextTask();
}
AppCacheURLRequestJobTest* test_;
net::HttpResponseInfo received_info_;
scoped_refptr<net::IOBuffer> received_data_;
bool did_receive_headers_;
int amount_received_;
int kill_after_amount_received_;
bool kill_with_io_pending_;
};
static net::URLRequestJob* MockHttpJobFactory(
net::URLRequest* request,
net::NetworkDelegate* network_delegate,
const std::string& scheme) {
if (mock_factory_job_) {
net::URLRequestJob* temp = mock_factory_job_;
mock_factory_job_ = NULL;
return temp;
} else {
return new net::URLRequestErrorJob(request,
network_delegate,
net::ERR_INTERNET_DISCONNECTED);
}
}
// Helper callback to run a test on our io_thread. The io_thread is spun up
// once and reused for all tests.
template <class Method>
void MethodWrapper(Method method) {
SetUpTest();
(this->*method)();
}
static void SetUpTestCase() {
io_thread_.reset(new base::Thread("AppCacheURLRequestJobTest Thread"));
base::Thread::Options options(base::MessageLoop::TYPE_IO, 0);
io_thread_->StartWithOptions(options);
}
static void TearDownTestCase() {
io_thread_.reset(NULL);
}
AppCacheURLRequestJobTest() {}
template <class Method>
void RunTestOnIOThread(Method method) {
test_finished_event_ .reset(new base::WaitableEvent(false, false));
io_thread_->message_loop()->PostTask(
FROM_HERE, base::Bind(&AppCacheURLRequestJobTest::MethodWrapper<Method>,
base::Unretained(this), method));
test_finished_event_->Wait();
}
void SetUpTest() {
DCHECK(base::MessageLoop::current() == io_thread_->message_loop());
DCHECK(task_stack_.empty());
orig_http_factory_ = net::URLRequest::Deprecated::RegisterProtocolFactory(
"http", MockHttpJobFactory);
url_request_delegate_.reset(new MockURLRequestDelegate(this));
storage_delegate_.reset(new MockStorageDelegate(this));
service_.reset(new MockAppCacheService());
expected_read_result_ = 0;
expected_write_result_ = 0;
written_response_id_ = 0;
reader_deletion_count_down_ = 0;
writer_deletion_count_down_ = 0;
}
void TearDownTest() {
DCHECK(base::MessageLoop::current() == io_thread_->message_loop());
net::URLRequest::Deprecated::RegisterProtocolFactory("http",
orig_http_factory_);
orig_http_factory_ = NULL;
request_.reset();
url_request_delegate_.reset();
DCHECK(!mock_factory_job_);
while (!task_stack_.empty())
task_stack_.pop();
reader_.reset();
read_buffer_ = NULL;
read_info_buffer_ = NULL;
writer_.reset();
write_buffer_ = NULL;
write_info_buffer_ = NULL;
storage_delegate_.reset();
service_.reset();
}
void TestFinished() {
// We unwind the stack prior to finishing up to let stack
// based objects get deleted.
DCHECK(base::MessageLoop::current() == io_thread_->message_loop());
base::MessageLoop::current()->PostTask(
FROM_HERE,
base::Bind(&AppCacheURLRequestJobTest::TestFinishedUnwound,
base::Unretained(this)));
}
void TestFinishedUnwound() {
TearDownTest();
test_finished_event_->Signal();
}
void PushNextTask(const base::Closure& task) {
task_stack_.push(std::pair<base::Closure, bool>(task, false));
}
void PushNextTaskAsImmediate(const base::Closure& task) {
task_stack_.push(std::pair<base::Closure, bool>(task, true));
}
void ScheduleNextTask() {
DCHECK(base::MessageLoop::current() == io_thread_->message_loop());
if (task_stack_.empty()) {
TestFinished();
return;
}
base::Closure task =task_stack_.top().first;
bool immediate = task_stack_.top().second;
task_stack_.pop();
if (immediate)
task.Run();
else
base::MessageLoop::current()->PostTask(FROM_HERE, task);
}
// Wrappers to call AppCacheResponseReader/Writer Read and Write methods
void WriteBasicResponse() {
scoped_refptr<IOBuffer> body(new WrappedIOBuffer(kHttpBasicBody));
std::string raw_headers(kHttpBasicHeaders, arraysize(kHttpBasicHeaders));
WriteResponse(MakeHttpResponseInfo(raw_headers), body,
strlen(kHttpBasicBody));
}
void WriteResponse(net::HttpResponseInfo* head,
IOBuffer* body, int body_len) {
DCHECK(body);
scoped_refptr<IOBuffer> body_ref(body);
PushNextTask(base::Bind(&AppCacheURLRequestJobTest::WriteResponseBody,
base::Unretained(this), body_ref, body_len));
WriteResponseHead(head);
}
void WriteResponseHead(net::HttpResponseInfo* head) {
EXPECT_FALSE(writer_->IsWritePending());
expected_write_result_ = GetHttpResponseInfoSize(head);
write_info_buffer_ = new HttpResponseInfoIOBuffer(head);
writer_->WriteInfo(
write_info_buffer_,
base::Bind(&AppCacheURLRequestJobTest::OnWriteInfoComplete,
base::Unretained(this)));
}
void WriteResponseBody(scoped_refptr<IOBuffer> io_buffer, int buf_len) {
EXPECT_FALSE(writer_->IsWritePending());
write_buffer_ = io_buffer;
expected_write_result_ = buf_len;
writer_->WriteData(
write_buffer_, buf_len,
base::Bind(&AppCacheURLRequestJobTest::OnWriteComplete,
base::Unretained(this)));
}
void ReadResponseBody(scoped_refptr<IOBuffer> io_buffer, int buf_len) {
EXPECT_FALSE(reader_->IsReadPending());
read_buffer_ = io_buffer;
expected_read_result_ = buf_len;
reader_->ReadData(
read_buffer_, buf_len,
base::Bind(&AppCacheURLRequestJobTest::OnReadComplete,
base::Unretained(this)));
}
// AppCacheResponseReader / Writer completion callbacks
void OnWriteInfoComplete(int result) {
EXPECT_FALSE(writer_->IsWritePending());
EXPECT_EQ(expected_write_result_, result);
ScheduleNextTask();
}
void OnWriteComplete(int result) {
EXPECT_FALSE(writer_->IsWritePending());
EXPECT_EQ(expected_write_result_, result);
ScheduleNextTask();
}
void OnReadInfoComplete(int result) {
EXPECT_FALSE(reader_->IsReadPending());
EXPECT_EQ(expected_read_result_, result);
ScheduleNextTask();
}
void OnReadComplete(int result) {
EXPECT_FALSE(reader_->IsReadPending());
EXPECT_EQ(expected_read_result_, result);
ScheduleNextTask();
}
// Helpers to work with HttpResponseInfo objects
net::HttpResponseInfo* MakeHttpResponseInfo(const std::string& raw_headers) {
net::HttpResponseInfo* info = new net::HttpResponseInfo;
info->request_time = base::Time::Now();
info->response_time = base::Time::Now();
info->was_cached = false;
info->headers = new net::HttpResponseHeaders(raw_headers);
return info;
}
int GetHttpResponseInfoSize(const net::HttpResponseInfo* info) {
Pickle pickle;
return PickleHttpResonseInfo(&pickle, info);
}
bool CompareHttpResponseInfos(const net::HttpResponseInfo* info1,
const net::HttpResponseInfo* info2) {
Pickle pickle1;
Pickle pickle2;
PickleHttpResonseInfo(&pickle1, info1);
PickleHttpResonseInfo(&pickle2, info2);
return (pickle1.size() == pickle2.size()) &&
(0 == memcmp(pickle1.data(), pickle2.data(), pickle1.size()));
}
int PickleHttpResonseInfo(Pickle* pickle, const net::HttpResponseInfo* info) {
const bool kSkipTransientHeaders = true;
const bool kTruncated = false;
info->Persist(pickle, kSkipTransientHeaders, kTruncated);
return pickle->size();
}
// Helpers to fill and verify blocks of memory with a value
void FillData(char value, char* data, int data_len) {
memset(data, value, data_len);
}
bool CheckData(char value, const char* data, int data_len) {
for (int i = 0; i < data_len; ++i, ++data) {
if (*data != value)
return false;
}
return true;
}
// Individual Tests ---------------------------------------------------------
// Some of the individual tests involve multiple async steps. Each test
// is delineated with a section header.
// Basic -------------------------------------------------------------------
void Basic() {
AppCacheStorage* storage = service_->storage();
net::URLRequest request(GURL("http://blah/"), NULL, &empty_context_);
scoped_refptr<AppCacheURLRequestJob> job;
// Create an instance and see that it looks as expected.
job = new AppCacheURLRequestJob(
&request, NULL, storage);
EXPECT_TRUE(job->is_waiting());
EXPECT_FALSE(job->is_delivering_appcache_response());
EXPECT_FALSE(job->is_delivering_network_response());
EXPECT_FALSE(job->is_delivering_error_response());
EXPECT_FALSE(job->has_been_started());
EXPECT_FALSE(job->has_been_killed());
EXPECT_EQ(GURL(), job->manifest_url());
EXPECT_EQ(kNoCacheId, job->cache_id());
EXPECT_FALSE(job->entry().has_response_id());
TestFinished();
}
// DeliveryOrders -----------------------------------------------------
void DeliveryOrders() {
AppCacheStorage* storage = service_->storage();
net::URLRequest request(GURL("http://blah/"), NULL, &empty_context_);
scoped_refptr<AppCacheURLRequestJob> job;
// Create an instance, give it a delivery order and see that
// it looks as expected.
job = new AppCacheURLRequestJob(&request, NULL, storage);
job->DeliverErrorResponse();
EXPECT_TRUE(job->is_delivering_error_response());
EXPECT_FALSE(job->has_been_started());
job = new AppCacheURLRequestJob(&request, NULL, storage);
job->DeliverNetworkResponse();
EXPECT_TRUE(job->is_delivering_network_response());
EXPECT_FALSE(job->has_been_started());
job = new AppCacheURLRequestJob(&request, NULL, storage);
const GURL kManifestUrl("http://blah/");
const int64 kCacheId(1);
const int64 kGroupId(1);
const AppCacheEntry kEntry(AppCacheEntry::EXPLICIT, 1);
job->DeliverAppCachedResponse(kManifestUrl, kCacheId, kGroupId,
kEntry, false);
EXPECT_FALSE(job->is_waiting());
EXPECT_TRUE(job->is_delivering_appcache_response());
EXPECT_FALSE(job->has_been_started());
EXPECT_EQ(kManifestUrl, job->manifest_url());
EXPECT_EQ(kCacheId, job->cache_id());
EXPECT_EQ(kGroupId, job->group_id());
EXPECT_EQ(kEntry.types(), job->entry().types());
EXPECT_EQ(kEntry.response_id(), job->entry().response_id());
TestFinished();
}
// DeliverNetworkResponse --------------------------------------------------
void DeliverNetworkResponse() {
// This test has async steps.
PushNextTask(
base::Bind(&AppCacheURLRequestJobTest::VerifyDeliverNetworkResponse,
base::Unretained(this)));
AppCacheStorage* storage = service_->storage();
request_.reset(empty_context_.CreateRequest(
GURL("http://blah/"), url_request_delegate_.get()));
// Setup to create an AppCacheURLRequestJob with orders to deliver
// a network response.
mock_factory_job_ = new AppCacheURLRequestJob(
request_.get(), NULL, storage);
mock_factory_job_->DeliverNetworkResponse();
EXPECT_TRUE(mock_factory_job_->is_delivering_network_response());
EXPECT_FALSE(mock_factory_job_->has_been_started());
// Start the request.
request_->Start();
// The job should have been picked up.
EXPECT_FALSE(mock_factory_job_);
// Completion is async.
}
void VerifyDeliverNetworkResponse() {
EXPECT_EQ(request_->status().error(),
net::ERR_INTERNET_DISCONNECTED);
TestFinished();
}
// DeliverErrorResponse --------------------------------------------------
void DeliverErrorResponse() {
// This test has async steps.
PushNextTask(
base::Bind(&AppCacheURLRequestJobTest::VerifyDeliverErrorResponse,
base::Unretained(this)));
AppCacheStorage* storage = service_->storage();
request_.reset(empty_context_.CreateRequest(GURL(
"http://blah/"), url_request_delegate_.get()));
// Setup to create an AppCacheURLRequestJob with orders to deliver
// a network response.
mock_factory_job_ = new AppCacheURLRequestJob(
request_.get(), NULL, storage);
mock_factory_job_->DeliverErrorResponse();
EXPECT_TRUE(mock_factory_job_->is_delivering_error_response());
EXPECT_FALSE(mock_factory_job_->has_been_started());
// Start the request.
request_->Start();
// The job should have been picked up.
EXPECT_FALSE(mock_factory_job_);
// Completion is async.
}
void VerifyDeliverErrorResponse() {
EXPECT_EQ(request_->status().error(), net::ERR_FAILED);
TestFinished();
}
// DeliverSmallAppCachedResponse --------------------------------------
// "Small" being small enough to read completely in a single
// request->Read call.
void DeliverSmallAppCachedResponse() {
// This test has several async steps.
// 1. Write a small response to response storage.
// 2. Use net::URLRequest to retrieve it.
// 3. Verify we received what we expected to receive.
PushNextTask(base::Bind(
&AppCacheURLRequestJobTest::VerifyDeliverSmallAppCachedResponse,
base::Unretained(this)));
PushNextTask(
base::Bind(&AppCacheURLRequestJobTest::RequestAppCachedResource,
base::Unretained(this), false));
writer_.reset(service_->storage()->CreateResponseWriter(GURL(), 0));
written_response_id_ = writer_->response_id();
WriteBasicResponse();
// Continues async
}
void RequestAppCachedResource(bool start_after_delivery_orders) {
AppCacheStorage* storage = service_->storage();
request_.reset(empty_context_.CreateRequest(
GURL("http://blah/"), url_request_delegate_.get()));
// Setup to create an AppCacheURLRequestJob with orders to deliver
// a network response.
scoped_refptr<AppCacheURLRequestJob> job(new AppCacheURLRequestJob(
request_.get(), NULL, storage));
if (start_after_delivery_orders) {
job->DeliverAppCachedResponse(
GURL(), 0, 111,
AppCacheEntry(AppCacheEntry::EXPLICIT, written_response_id_),
false);
EXPECT_TRUE(job->is_delivering_appcache_response());
}
// Start the request.
EXPECT_FALSE(job->has_been_started());
mock_factory_job_ = job;
request_->Start();
EXPECT_FALSE(mock_factory_job_);
EXPECT_TRUE(job->has_been_started());
if (!start_after_delivery_orders) {
job->DeliverAppCachedResponse(
GURL(), 0, 111,
AppCacheEntry(AppCacheEntry::EXPLICIT, written_response_id_),
false);
EXPECT_TRUE(job->is_delivering_appcache_response());
}
// Completion is async.
}
void VerifyDeliverSmallAppCachedResponse() {
EXPECT_TRUE(request_->status().is_success());
EXPECT_TRUE(CompareHttpResponseInfos(
write_info_buffer_->http_info.get(),
&url_request_delegate_->received_info_));
EXPECT_EQ(5, url_request_delegate_->amount_received_);
EXPECT_EQ(0, memcmp(kHttpBasicBody,
url_request_delegate_->received_data_->data(),
strlen(kHttpBasicBody)));
TestFinished();
}
// DeliverLargeAppCachedResponse --------------------------------------
// "Large" enough to require multiple calls to request->Read to complete.
void DeliverLargeAppCachedResponse() {
// This test has several async steps.
// 1. Write a large response to response storage.
// 2. Use net::URLRequest to retrieve it.
// 3. Verify we received what we expected to receive.
PushNextTask(base::Bind(
&AppCacheURLRequestJobTest::VerifyDeliverLargeAppCachedResponse,
base::Unretained(this)));
PushNextTask(base::Bind(
&AppCacheURLRequestJobTest::RequestAppCachedResource,
base::Unretained(this), true));
writer_.reset(service_->storage()->CreateResponseWriter(GURL(), 0));
written_response_id_ = writer_->response_id();
WriteLargeResponse();
// Continues async
}
void WriteLargeResponse() {
// 3, 1k blocks
static const char kHttpHeaders[] =
"HTTP/1.0 200 OK\0Content-Length: 3072\0\0";
scoped_refptr<IOBuffer> body(new IOBuffer(kBlockSize * 3));
char* p = body->data();
for (int i = 0; i < 3; ++i, p += kBlockSize)
FillData(i + 1, p, kBlockSize);
std::string raw_headers(kHttpHeaders, arraysize(kHttpHeaders));
WriteResponse(MakeHttpResponseInfo(raw_headers), body, kBlockSize * 3);
}
void VerifyDeliverLargeAppCachedResponse() {
EXPECT_TRUE(request_->status().is_success());
EXPECT_TRUE(CompareHttpResponseInfos(
write_info_buffer_->http_info.get(),
&url_request_delegate_->received_info_));
EXPECT_EQ(3072, url_request_delegate_->amount_received_);
char* p = url_request_delegate_->received_data_->data();
for (int i = 0; i < 3; ++i, p += kBlockSize)
EXPECT_TRUE(CheckData(i + 1, p, kBlockSize));
TestFinished();
}
// DeliverPartialResponse --------------------------------------
void DeliverPartialResponse() {
// This test has several async steps.
// 1. Write a small response to response storage.
// 2. Use net::URLRequest to retrieve it a subset using a range request
// 3. Verify we received what we expected to receive.
PushNextTask(base::Bind(
&AppCacheURLRequestJobTest::VerifyDeliverPartialResponse,
base::Unretained(this)));
PushNextTask(base::Bind(
&AppCacheURLRequestJobTest::MakeRangeRequest, base::Unretained(this)));
writer_.reset(service_->storage()->CreateResponseWriter(GURL(), 0));
written_response_id_ = writer_->response_id();
WriteBasicResponse();
// Continues async
}
void MakeRangeRequest() {
AppCacheStorage* storage = service_->storage();
request_.reset(empty_context_.CreateRequest(
GURL("http://blah/"), url_request_delegate_.get()));
// Request a range, the 3 middle chars out of 'Hello'
net::HttpRequestHeaders extra_headers;
extra_headers.SetHeader("Range", "bytes= 1-3");
request_->SetExtraRequestHeaders(extra_headers);
// Create job with orders to deliver an appcached entry.
scoped_refptr<AppCacheURLRequestJob> job(new AppCacheURLRequestJob(
request_.get(), NULL, storage));
job->DeliverAppCachedResponse(
GURL(), 0, 111,
AppCacheEntry(AppCacheEntry::EXPLICIT, written_response_id_),
false);
EXPECT_TRUE(job->is_delivering_appcache_response());
// Start the request.
EXPECT_FALSE(job->has_been_started());
mock_factory_job_ = job;
request_->Start();
EXPECT_FALSE(mock_factory_job_);
EXPECT_TRUE(job->has_been_started());
// Completion is async.
}
void VerifyDeliverPartialResponse() {
EXPECT_TRUE(request_->status().is_success());
EXPECT_EQ(3, url_request_delegate_->amount_received_);
EXPECT_EQ(0, memcmp(kHttpBasicBody + 1,
url_request_delegate_->received_data_->data(),
3));
net::HttpResponseHeaders* headers =
url_request_delegate_->received_info_.headers.get();
EXPECT_EQ(206, headers->response_code());
EXPECT_EQ(3, headers->GetContentLength());
int64 range_start, range_end, object_size;
EXPECT_TRUE(
headers->GetContentRange(&range_start, &range_end, &object_size));
EXPECT_EQ(1, range_start);
EXPECT_EQ(3, range_end);
EXPECT_EQ(5, object_size);
TestFinished();
}
// CancelRequest --------------------------------------
void CancelRequest() {
// This test has several async steps.
// 1. Write a large response to response storage.
// 2. Use net::URLRequest to retrieve it.
// 3. Cancel the request after data starts coming in.
PushNextTask(base::Bind(
&AppCacheURLRequestJobTest::VerifyCancel, base::Unretained(this)));
PushNextTask(base::Bind(
&AppCacheURLRequestJobTest::RequestAppCachedResource,
base::Unretained(this), true));
writer_.reset(service_->storage()->CreateResponseWriter(GURL(), 0));
written_response_id_ = writer_->response_id();
WriteLargeResponse();
url_request_delegate_->kill_after_amount_received_ = kBlockSize;
url_request_delegate_->kill_with_io_pending_ = false;
// Continues async
}
void VerifyCancel() {
EXPECT_EQ(net::URLRequestStatus::CANCELED,
request_->status().status());
TestFinished();
}
// CancelRequestWithIOPending --------------------------------------
void CancelRequestWithIOPending() {
// This test has several async steps.
// 1. Write a large response to response storage.
// 2. Use net::URLRequest to retrieve it.
// 3. Cancel the request after data starts coming in.
PushNextTask(base::Bind(
&AppCacheURLRequestJobTest::VerifyCancel, base::Unretained(this)));
PushNextTask(base::Bind(
&AppCacheURLRequestJobTest::RequestAppCachedResource,
base::Unretained(this), true));
writer_.reset(service_->storage()->CreateResponseWriter(GURL(), 0));
written_response_id_ = writer_->response_id();
WriteLargeResponse();
url_request_delegate_->kill_after_amount_received_ = kBlockSize;
url_request_delegate_->kill_with_io_pending_ = true;
// Continues async
}
// Data members --------------------------------------------------------
scoped_ptr<base::WaitableEvent> test_finished_event_;
scoped_ptr<MockStorageDelegate> storage_delegate_;
scoped_ptr<MockAppCacheService> service_;
std::stack<std::pair<base::Closure, bool> > task_stack_;
scoped_ptr<AppCacheResponseReader> reader_;
scoped_refptr<HttpResponseInfoIOBuffer> read_info_buffer_;
scoped_refptr<IOBuffer> read_buffer_;
int expected_read_result_;
int reader_deletion_count_down_;
int64 written_response_id_;
scoped_ptr<AppCacheResponseWriter> writer_;
scoped_refptr<HttpResponseInfoIOBuffer> write_info_buffer_;
scoped_refptr<IOBuffer> write_buffer_;
int expected_write_result_;
int writer_deletion_count_down_;
net::URLRequest::ProtocolFactory* orig_http_factory_;
net::URLRequestContext empty_context_;
scoped_ptr<net::URLRequest> request_;
scoped_ptr<MockURLRequestDelegate> url_request_delegate_;
static scoped_ptr<base::Thread> io_thread_;
static AppCacheURLRequestJob* mock_factory_job_;
};
// static
scoped_ptr<base::Thread> AppCacheURLRequestJobTest::io_thread_;
AppCacheURLRequestJob* AppCacheURLRequestJobTest::mock_factory_job_ = NULL;
TEST_F(AppCacheURLRequestJobTest, Basic) {
RunTestOnIOThread(&AppCacheURLRequestJobTest::Basic);
}
TEST_F(AppCacheURLRequestJobTest, DeliveryOrders) {
RunTestOnIOThread(&AppCacheURLRequestJobTest::DeliveryOrders);
}
TEST_F(AppCacheURLRequestJobTest, DeliverNetworkResponse) {
RunTestOnIOThread(&AppCacheURLRequestJobTest::DeliverNetworkResponse);
}
TEST_F(AppCacheURLRequestJobTest, DeliverErrorResponse) {
RunTestOnIOThread(&AppCacheURLRequestJobTest::DeliverErrorResponse);
}
TEST_F(AppCacheURLRequestJobTest, DeliverSmallAppCachedResponse) {
RunTestOnIOThread(&AppCacheURLRequestJobTest::DeliverSmallAppCachedResponse);
}
TEST_F(AppCacheURLRequestJobTest, DeliverLargeAppCachedResponse) {
RunTestOnIOThread(&AppCacheURLRequestJobTest::DeliverLargeAppCachedResponse);
}
TEST_F(AppCacheURLRequestJobTest, DeliverPartialResponse) {
RunTestOnIOThread(&AppCacheURLRequestJobTest::DeliverPartialResponse);
}
TEST_F(AppCacheURLRequestJobTest, CancelRequest) {
RunTestOnIOThread(&AppCacheURLRequestJobTest::CancelRequest);
}
TEST_F(AppCacheURLRequestJobTest, CancelRequestWithIOPending) {
RunTestOnIOThread(&AppCacheURLRequestJobTest::CancelRequestWithIOPending);
}
} // namespace appcache
| bsd-3-clause |
devbharat/gtsam | doc/html/a00494.js | 523 | var a00494 =
[
[ "calculate_nnz", "a00494.html#aca63ccfbd14352eade58fd2a2ec6b5e4", null ],
[ "nnz_internal", "a00494.html#a710993cf2d56652448517817943ad10f", null ],
[ "optimizeWildfire", "a00494.html#adc947c65dcf861c33a24399614c0791a", null ],
[ "optimizeWildfire", "a00494.html#a33509e7a55b46fe677e682d01f8fbd87", null ],
[ "optimizeWildfireNode", "a00494.html#aadd9b9f920ceaa21f31cb0695fc3c12d", null ],
[ "optimizeWildfireNonRecursive", "a00494.html#ad11ffb44abea89e42c6de7a9f2f97221", null ]
]; | bsd-3-clause |
erhs-53-hackers/Robo2012 | src/edu/wpi/first/wpilibj/templates/ImageProcessing.java | 7992 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.wpi.first.wpilibj.templates;
import edu.wpi.first.wpilibj.camera.AxisCamera;
import edu.wpi.first.wpilibj.image.BinaryImage;
import edu.wpi.first.wpilibj.image.ColorImage;
import edu.wpi.first.wpilibj.image.CriteriaCollection;
import edu.wpi.first.wpilibj.image.NIVision.MeasurementType;
import edu.wpi.first.wpilibj.image.ParticleAnalysisReport;
/**
*
* @author Rajath, Michael
*/
public class ImageProcessing {
ParticleAnalysisReport particles[] = null;
CriteriaCollection criteriaCollection = new CriteriaCollection();
ParticleAnalysisReport bottomTarget, topTarget, middleTargetLeft,
middleTargetRight;
Messager msg = new Messager();
static final double FOV = 34.42900061182182;//camera field of view in degrees
static final double camResWidth = 640;
static final double camResHeight = 480;
static final double targetHeight = 18.125;
static final double cameraTilt = 13.4;
static final double cameraHeight = 61;
static final double maxDisparity = .5;
static final double lambda = camResHeight / FOV;
static final double topTargetHeight = 109;//inches to middle
static final double middleTargetHeight = 72;//inches to middle
static final double bottomTargetHeight = 39;//inches to middle
static final double T_topTargetHeight = 118;//inches to top of tape
static final double T_middleTargetHeight = 81;//inches to top of tape
static final double T_bottomTargetHeight = 48;//inches to top of tape
static final double B_topTargetHeight = 100;//inches to bottom of tape
static final double B_middleTargetHeight = 63;//inches to bottom of tape
static final double B_bottomTargetHeight = 30;//inches to bottom of tape
public ImageProcessing() {
criteriaCollection.addCriteria(
MeasurementType.IMAQ_MT_BOUNDING_RECT_WIDTH, 30, 400, false);
criteriaCollection.addCriteria(
MeasurementType.IMAQ_MT_BOUNDING_RECT_HEIGHT, 40, 400, false);
}
public static double getHorizontalAngle(ParticleAnalysisReport particle) {
double p = (camResWidth / 2) - particle.center_mass_x;
double angle = p / lambda;
return angle;
}
public static ParticleAnalysisReport getTopMost(ParticleAnalysisReport[] particles) {
ParticleAnalysisReport greatest = particles[0];
for (int i = 0; i < particles.length; i++) {
ParticleAnalysisReport particle = particles[i];
if (particle.center_mass_y > greatest.center_mass_y) {
greatest = particle;
}
}
return greatest;
}
public static ParticleAnalysisReport getBottomMost(ParticleAnalysisReport[] particles) {
ParticleAnalysisReport lowest = particles[0];
for (int i = 0; i < particles.length; i++) {
ParticleAnalysisReport particle = particles[i];
if (particle.center_mass_y < lowest.center_mass_y) {
lowest = particle;
}
}
return lowest;
}
public static ParticleAnalysisReport getRightMost(ParticleAnalysisReport[] particles) {
ParticleAnalysisReport rightistTarget = particles[0];
for (int i = 0; i < particles.length; i++) {
ParticleAnalysisReport particle = particles[i];
if (particle.center_mass_x > rightistTarget.center_mass_x) {
rightistTarget = particle;
}
}
return rightistTarget;
}
public static ParticleAnalysisReport getLeftMost(ParticleAnalysisReport[] particles) {
ParticleAnalysisReport leftistTarget = particles[0];
for (int i = 0; i < particles.length; i++) {
ParticleAnalysisReport particle = particles[i];
if (particle.center_mass_x < leftistTarget.center_mass_x) {
leftistTarget = particle;
}
}
return leftistTarget;
}
/**
* Fills the array (particles) with all found particle analysis reports
*
* @param camera the camera to get the particle analysis report from
* @throws Exception
*/
public void getTheParticles(AxisCamera camera) throws Exception {
int erosionCount = 2;
// true means use connectivity 8, false means connectivity 4
boolean useConnectivity8 = false;
ColorImage colorImage;
BinaryImage binaryImage;
BinaryImage cleanImage;
BinaryImage convexHullImage;
BinaryImage filteredImage;
colorImage = camera.getImage();
//seperate the light and dark image
binaryImage = colorImage.thresholdRGB(0, 42, 71, 255, 0, 255);
cleanImage = binaryImage.removeSmallObjects(
useConnectivity8, erosionCount);
//fill the rectangles that were created
convexHullImage = cleanImage.convexHull(useConnectivity8);
filteredImage = convexHullImage.particleFilter(criteriaCollection);
particles = filteredImage.getOrderedParticleAnalysisReports();
colorImage.free();
binaryImage.free();
cleanImage.free();
convexHullImage.free();
filteredImage.free();
}
public double getCameraTilt() {
double level = particles[0].center_mass_y - particles[0].boundingRectHeight / 2;
level *= FOV;
level /= camResHeight;
return level - FOV / 2;
}
/**
* Get the horizontal distance to the target
*
* @param part the particle analysis report to get the report from
* @param height the height of the target to get the report from
* @return distance to target, in inches
*/
public double getDistance(ParticleAnalysisReport part, double height) {
double ph = part.boundingRectHeight;
double delta = height - cameraHeight;
double R = targetHeight / MathX.tan(ph / lambda);
double D = 0;
for (int i = 0; i < 4; i++) {
double theta = MathX.asin(delta / R);
double new_ph = ph / MathX.cos(theta);
R = targetHeight / MathX.tan(new_ph / lambda);
D = MathX.sqrt(R * R - delta * delta);
}
return D;
}
private double max(double d1, double d2) {
if (d1 > d2) {
return d1;
}
return d2;
}
private double min(double d1, double d2) {
if (d1 < d2) {
return d1;
}
return d2;
}
public double isTopTarget(ParticleAnalysisReport part) {
double D1 = getDistance(part, T_topTargetHeight);
double D2 = getDistance(part, B_topTargetHeight);
double disparity = max(D1, D2) - min(D1, D2);
System.out.println("Top1:" + D1);
System.out.println("Top2:" + D2);
System.out.println("----------------------");
/*
* if (disparity < maxDisparity) { return true; } else { return false; }
*
*/
return disparity;
}
public double isBottomTarget(ParticleAnalysisReport part) {
double D1 = getDistance(part, T_bottomTargetHeight);
double D2 = getDistance(part, B_bottomTargetHeight);
double disparity = max(D1, D2) - min(D1, D2);
System.out.println("Bottom1:" + D1);
System.out.println("Bottom2:" + D2);
System.out.println("----------------------");
/*
*
* if (disparity < maxDisparity) { return true; } else { return false; }
*
*/
return disparity;
}
public boolean isMiddleTarget(ParticleAnalysisReport part) {
double D1 = getDistance(part, T_middleTargetHeight);
double D2 = getDistance(part, B_middleTargetHeight);
double disparity = max(D1, D2) / min(D1, D2);
if (disparity < maxDisparity) {
return true;
} else {
return false;
}
}
}
| bsd-3-clause |
shnfu/shnfucarver | library/ShnfuCarver/Kernel/Service/ServiceRepository.php | 1772 | <?php
/**
* Service repository class file
*
* @package ShnfuCarver
* @subpackage Kernel\Service
* @copyright 2012 Shnfu
* @author Zhao Xianghu <[email protected]>
* @license http://carver.shnfu.com/license.txt New BSD License
*/
namespace ShnfuCarver\Kernel\Service;
/**
* Service repository class
*
* @package ShnfuCarver
* @subpackage Kernel\Service
* @copyright 2012 Shnfu
* @author Zhao Xianghu <[email protected]>
* @license http://carver.shnfu.com/license.txt New BSD License
*/
class ServiceRepository
{
/**
* Service repository
*
* @var array
*/
protected $_repository = array();
/**
* Register a service
*
* @param \ShnfuCarver\Kernel\Service\Service $service
* @return \ShnfuCarver\Kernel\Service\Service
*/
public function register($service)
{
if (!$service instanceof ServiceInterface)
{
throw new \InvalidArgumentException('Not an instance of ServiceInterface!');
}
$name = $service->getName();
if (!$this->exist($name))
{
$this->_repository[$name] = $service;
}
return $this->get($name);
}
/**
* Check whether a service exists
*
* @param string $name
* @return bool
*/
public function exist($name)
{
return isset($this->_repository[$name]);
}
/**
* Get a service
*
* @param string $name
* @return object
*/
public function get($name)
{
if (!isset($this->_repository[$name]))
{
throw new \InvalidArgumentException("The service $name does not exist!");
}
return $this->_repository[$name]->get();
}
}
?>
| bsd-3-clause |
drmateo/pcl | gpu/kinfu/include/pcl/gpu/kinfu/kinfu.h | 11857 | /*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2011, Willow Garage, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. 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.
*
*/
#pragma once
#include <pcl/pcl_macros.h>
#include <pcl/gpu/containers/device_array.h>
#include <pcl/gpu/kinfu/pixel_rgb.h>
#include <pcl/gpu/kinfu/tsdf_volume.h>
#include <pcl/gpu/kinfu/color_volume.h>
#include <pcl/gpu/kinfu/raycaster.h>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <Eigen/Core>
#include <vector>
// Focal lengths of RGB camera
#define KINFU_DEFAULT_RGB_FOCAL_X 525.f
#define KINFU_DEFAULT_RGB_FOCAL_Y 525.f
// Focal lengths of depth (i.e. NIR) camera
#define KINFU_DEFAULT_DEPTH_FOCAL_X 585.f
#define KINFU_DEFAULT_DEPTH_FOCAL_Y 585.f
namespace pcl
{
namespace gpu
{
/** \brief KinfuTracker class encapsulates implementation of Microsoft Kinect Fusion algorithm
* \author Anatoly Baskeheev, Itseez Ltd, ([email protected])
*/
class PCL_EXPORTS KinfuTracker
{
public:
/** \brief Pixel type for rendered image. */
using PixelRGB = pcl::gpu::PixelRGB;
using View = DeviceArray2D<PixelRGB>;
using DepthMap = DeviceArray2D<unsigned short>;
using PointType = pcl::PointXYZ;
using NormalType = pcl::Normal;
/** \brief Constructor
* \param[in] rows height of depth image
* \param[in] cols width of depth image
*/
KinfuTracker (int rows = 480, int cols = 640);
/** \brief Sets Depth camera intrinsics
* \param[in] fx focal length x
* \param[in] fy focal length y
* \param[in] cx principal point x
* \param[in] cy principal point y
*/
void
setDepthIntrinsics (float fx, float fy, float cx = -1, float cy = -1);
/** \brief Get Depth camera intrinsics
* \param[out] fx focal length x
* \param[out] fy focal length y
* \param[out] cx principal point x
* \param[out] cy principal point y
*/
void
getDepthIntrinsics (float& fx, float& fy, float& cx, float& cy);
/** \brief Sets initial camera pose relative to volume coordinate space
* \param[in] pose Initial camera pose
*/
void
setInitalCameraPose (const Eigen::Affine3f& pose);
/** \brief Sets truncation threshold for depth image for ICP step only! This helps
* to filter measurements that are outside tsdf volume. Pass zero to disable the truncation.
* \param[in] max_icp_distance Maximal distance, higher values are reset to zero (means no measurement).
*/
void
setDepthTruncationForICP (float max_icp_distance = 0.f);
/** \brief Sets ICP filtering parameters.
* \param[in] distThreshold distance.
* \param[in] sineOfAngle sine of angle between normals.
*/
void
setIcpCorespFilteringParams (float distThreshold, float sineOfAngle);
/** \brief Sets integration threshold. TSDF volume is integrated iff a camera movement metric exceedes the threshold value.
* The metric represents the following: M = (rodrigues(Rotation).norm() + alpha*translation.norm())/2, where alpha = 1.f (hardcoded constant)
* \param[in] threshold a value to compare with the metric. Suitable values are ~0.001
*/
void
setCameraMovementThreshold(float threshold = 0.001f);
/** \brief Performs initialization for color integration. Must be called before calling color integration.
* \param[in] max_weight max weighe for color integration. -1 means default weight.
*/
void
initColorIntegration(int max_weight = -1);
/** \brief Returns cols passed to ctor */
int
cols ();
/** \brief Returns rows passed to ctor */
int
rows ();
/** \brief Processes next frame.
* \param[in] depth next frame with values in millimeters
* \param hint
* \return true if can render 3D view.
*/
bool operator() (const DepthMap& depth, Eigen::Affine3f* hint=nullptr);
/** \brief Processes next frame (both depth and color integration). Please call initColorIntegration before invpoking this.
* \param[in] depth next depth frame with values in millimeters
* \param[in] colors next RGB frame
* \return true if can render 3D view.
*/
bool operator() (const DepthMap& depth, const View& colors);
/** \brief Returns camera pose at given time, default the last pose
* \param[in] time Index of frame for which camera pose is returned.
* \return camera pose
*/
Eigen::Affine3f
getCameraPose (int time = -1) const;
/** \brief Returns number of poses including initial */
size_t
getNumberOfPoses () const;
/** \brief Returns TSDF volume storage */
const TsdfVolume& volume() const;
/** \brief Returns TSDF volume storage */
TsdfVolume& volume();
/** \brief Returns color volume storage */
const ColorVolume& colorVolume() const;
/** \brief Returns color volume storage */
ColorVolume& colorVolume();
/** \brief Renders 3D scene to display to human
* \param[out] view output array with image
*/
void
getImage (View& view) const;
/** \brief Returns point cloud abserved from last camera pose
* \param[out] cloud output array for points
*/
void
getLastFrameCloud (DeviceArray2D<PointType>& cloud) const;
/** \brief Returns point cloud abserved from last camera pose
* \param[out] normals output array for normals
*/
void
getLastFrameNormals (DeviceArray2D<NormalType>& normals) const;
/** \brief Disables ICP forever */
void disableIcp();
private:
/** \brief Number of pyramid levels */
enum { LEVELS = 3 };
/** \brief ICP Correspondences map type */
using CorespMap = DeviceArray2D<int>;
/** \brief Vertex or Normal Map type */
using MapArr = DeviceArray2D<float>;
using Matrix3frm = Eigen::Matrix<float, 3, 3, Eigen::RowMajor>;
using Vector3f = Eigen::Vector3f;
/** \brief Height of input depth image. */
int rows_;
/** \brief Width of input depth image. */
int cols_;
/** \brief Frame counter */
int global_time_;
/** \brief Truncation threshold for depth image for ICP step */
float max_icp_distance_;
/** \brief Intrinsic parameters of depth camera. */
float fx_, fy_, cx_, cy_;
/** \brief Tsdf volume container. */
TsdfVolume::Ptr tsdf_volume_;
ColorVolume::Ptr color_volume_;
/** \brief Initial camera rotation in volume coo space. */
Matrix3frm init_Rcam_;
/** \brief Initial camera position in volume coo space. */
Vector3f init_tcam_;
/** \brief array with IPC iteration numbers for each pyramid level */
int icp_iterations_[LEVELS];
/** \brief distance threshold in correspondences filtering */
float distThres_;
/** \brief angle threshold in correspondences filtering. Represents max sine of angle between normals. */
float angleThres_;
/** \brief Depth pyramid. */
std::vector<DepthMap> depths_curr_;
/** \brief Vertex maps pyramid for current frame in global coordinate space. */
std::vector<MapArr> vmaps_g_curr_;
/** \brief Normal maps pyramid for current frame in global coordinate space. */
std::vector<MapArr> nmaps_g_curr_;
/** \brief Vertex maps pyramid for previous frame in global coordinate space. */
std::vector<MapArr> vmaps_g_prev_;
/** \brief Normal maps pyramid for previous frame in global coordinate space. */
std::vector<MapArr> nmaps_g_prev_;
/** \brief Vertex maps pyramid for current frame in current coordinate space. */
std::vector<MapArr> vmaps_curr_;
/** \brief Normal maps pyramid for current frame in current coordinate space. */
std::vector<MapArr> nmaps_curr_;
/** \brief Array of buffers with ICP correspondences for each pyramid level. */
std::vector<CorespMap> coresps_;
/** \brief Buffer for storing scaled depth image */
DeviceArray2D<float> depthRawScaled_;
/** \brief Temporary buffer for ICP */
DeviceArray2D<double> gbuf_;
/** \brief Buffer to store MLS matrix. */
DeviceArray<double> sumbuf_;
/** \brief Array of camera rotation matrices for each moment of time. */
std::vector<Matrix3frm> rmats_;
/** \brief Array of camera translations for each moment of time. */
std::vector<Vector3f> tvecs_;
/** \brief Camera movement threshold. TSDF is integrated iff a camera movement metric exceedes some value. */
float integration_metric_threshold_;
/** \brief ICP step is completely disabled. Only integration now. */
bool disable_icp_;
/** \brief Allocates all GPU internal buffers.
* \param[in] rows_arg
* \param[in] cols_arg
*/
void
allocateBufffers (int rows_arg, int cols_arg);
/** \brief Performs the tracker reset to initial state. It's used if case of camera tracking fail.
*/
void
reset ();
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};
}
};
namespace pcl
{
namespace gpu
{
PCL_EXPORTS void
paint3DView(const KinfuTracker::View& rgb24, KinfuTracker::View& view, float colors_weight);
PCL_EXPORTS void
mergePointNormal(const DeviceArray<PointXYZ>& cloud, const DeviceArray<Normal>& normals, DeviceArray<PointNormal>& output);
Eigen::Vector3f rodrigues2(const Eigen::Matrix3f& matrix);
}
}
#endif /* PCL_KINFU_KINFUTRACKER_HPP_ */
| bsd-3-clause |
evenator/mapviz | mapviz_plugins/src/laserscan_plugin.cpp | 20064 | // *****************************************************************************
//
// Copyright (c) 2015, Southwest Research Institute® (SwRI®)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of Southwest Research Institute® (SwRI®) nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// *****************************************************************************
#include <mapviz_plugins/laserscan_plugin.h>
// C++ standard libraries
#include <cmath>
#include <cstdio>
#include <algorithm>
#include <vector>
// Boost libraries
#include <boost/algorithm/string.hpp>
// QT libraries
#include <QColorDialog>
#include <QDialog>
#include <QGLWidget>
// OpenGL
#include <GL/glew.h>
// QT Autogenerated
#include "ui_topic_select.h"
// ROS libraries
#include <ros/master.h>
#include <swri_transform_util/transform.h>
#include <swri_yaml_util/yaml_util.h>
#include <mapviz/select_topic_dialog.h>
// Declare plugin
#include <pluginlib/class_list_macros.h>
PLUGINLIB_DECLARE_CLASS(
mapviz_plugins,
laserscan,
mapviz_plugins::LaserScanPlugin,
mapviz::MapvizPlugin)
namespace mapviz_plugins
{
LaserScanPlugin::LaserScanPlugin() :
config_widget_(new QWidget()),
topic_(""),
alpha_(1.0),
min_value_(0.0),
max_value_(100.0),
point_size_(3)
{
ui_.setupUi(config_widget_);
// Set background white
QPalette p(config_widget_->palette());
p.setColor(QPalette::Background, Qt::white);
config_widget_->setPalette(p);
// Set status text red
QPalette p3(ui_.status->palette());
p3.setColor(QPalette::Text, Qt::red);
ui_.status->setPalette(p3);
// Initialize color selector colors
ui_.min_color->setColor(Qt::white);
ui_.max_color->setColor(Qt::black);
// Set color transformer choices
ui_.color_transformer->addItem(QString("Flat Color"), QVariant(0));
ui_.color_transformer->addItem(QString("Intensity"), QVariant(1));
ui_.color_transformer->addItem(QString("Range"), QVariant(2));
ui_.color_transformer->addItem(QString("X Axis"), QVariant(3));
ui_.color_transformer->addItem(QString("Y Axis"), QVariant(4));
ui_.color_transformer->addItem(QString("Z Axis"), QVariant(5));
QObject::connect(ui_.selecttopic,
SIGNAL(clicked()),
this,
SLOT(SelectTopic()));
QObject::connect(ui_.topic,
SIGNAL(editingFinished()),
this,
SLOT(TopicEdited()));
QObject::connect(ui_.alpha,
SIGNAL(editingFinished()),
this,
SLOT(AlphaEdited()));
QObject::connect(ui_.color_transformer,
SIGNAL(currentIndexChanged(int)),
this,
SLOT(ColorTransformerChanged(int)));
QObject::connect(ui_.max_color,
SIGNAL(colorEdited(const QColor &)),
this,
SLOT(UpdateColors()));
QObject::connect(ui_.min_color,
SIGNAL(colorEdited(const QColor &)),
this,
SLOT(UpdateColors()));
QObject::connect(ui_.minValue,
SIGNAL(valueChanged(double)),
this,
SLOT(MinValueChanged(double)));
QObject::connect(ui_.maxValue,
SIGNAL(valueChanged(double)),
this,
SLOT(MaxValueChanged(double)));
QObject::connect(ui_.bufferSize,
SIGNAL(valueChanged(int)),
this,
SLOT(BufferSizeChanged(int)));
QObject::connect(ui_.pointSize,
SIGNAL(valueChanged(int)),
this,
SLOT(PointSizeChanged(int)));
QObject::connect(ui_.use_rainbow,
SIGNAL(stateChanged(int)),
this,
SLOT(UseRainbowChanged(int)));
QObject::connect(ui_.max_color,
SIGNAL(colorEdited(const QColor &)),
this,
SLOT(DrawIcon()));
QObject::connect(ui_.min_color,
SIGNAL(colorEdited(const QColor &)),
this,
SLOT(DrawIcon()));
PrintInfo("Constructed LaserScanPlugin");
}
LaserScanPlugin::~LaserScanPlugin()
{
}
void LaserScanPlugin::DrawIcon()
{
if (icon_)
{
QPixmap icon(16, 16);
icon.fill(Qt::transparent);
QPainter painter(&icon);
painter.setRenderHint(QPainter::Antialiasing, true);
QPen pen;
pen.setWidth(4);
pen.setCapStyle(Qt::RoundCap);
pen.setColor(ui_.min_color->color());
painter.setPen(pen);
painter.drawPoint(2, 13);
pen.setColor(ui_.min_color->color());
painter.setPen(pen);
painter.drawPoint(4, 6);
pen.setColor(ui_.max_color->color());
painter.setPen(pen);
painter.drawPoint(12, 9);
pen.setColor(ui_.max_color->color());
painter.setPen(pen);
painter.drawPoint(13, 2);
icon_->SetPixmap(icon);
}
}
QColor LaserScanPlugin::CalculateColor(const StampedPoint& point,
bool has_intensity)
{
double val;
unsigned int color_transformer = ui_.color_transformer->currentIndex();
if (color_transformer == COLOR_RANGE)
{
val = point.range;
}
else if (color_transformer == COLOR_INTENSITY && has_intensity)
{
val = point.intensity;
}
else if (color_transformer == COLOR_X)
{
val = point.point.x();
}
else if (color_transformer == COLOR_Y)
{
val = point.point.y();
}
else if (color_transformer == COLOR_Z)
{
val = point.transformed_point.z();
}
else // No intensity or (color_transformer == COLOR_FLAT)
{
return ui_.min_color->color();
}
if (max_value_ > min_value_)
val = (val - min_value_) / (max_value_ - min_value_);
val = std::max(0.0, std::min(val, 1.0));
if (ui_.use_rainbow->isChecked())
{
// Hue Interpolation
int hue = val * 255;
return QColor::fromHsl(hue, 255, 127, 255);
}
else
{
const QColor min_color = ui_.min_color->color();
const QColor max_color = ui_.max_color->color();
// RGB Interpolation
int red, green, blue;
red = val * max_color.red() + ((1.0 - val) * min_color.red());
green = val * max_color.green() + ((1.0 - val) * min_color.green());
blue = val * max_color.blue() + ((1.0 - val) * min_color.blue());
return QColor(red, green, blue, 255);
}
}
void LaserScanPlugin::UpdateColors()
{
std::deque<Scan>::iterator scan_it = scans_.begin();
for (; scan_it != scans_.end(); ++scan_it)
{
std::vector<StampedPoint>::iterator point_it = scan_it->points.begin();
for (; point_it != scan_it->points.end(); point_it++)
{
point_it->color = CalculateColor(*point_it, scan_it->has_intensity);
}
}
}
void LaserScanPlugin::SelectTopic()
{
ros::master::TopicInfo topic = mapviz::SelectTopicDialog::selectTopic(
"sensor_msgs/LaserScan");
if (!topic.name.empty())
{
ui_.topic->setText(QString::fromStdString(topic.name));
TopicEdited();
}
}
void LaserScanPlugin::TopicEdited()
{
std::string topic = ui_.topic->text().trimmed().toStdString();
if (topic != topic_)
{
initialized_ = false;
scans_.clear();
has_message_ = false;
PrintWarning("No messages received.");
laserscan_sub_.shutdown();
topic_ = topic;
if (!topic.empty())
{
laserscan_sub_ = node_.subscribe(topic_,
100,
&LaserScanPlugin::laserScanCallback,
this);
ROS_INFO("Subscribing to %s", topic_.c_str());
}
}
}
void LaserScanPlugin::MinValueChanged(double value)
{
min_value_ = value;
UpdateColors();
}
void LaserScanPlugin::MaxValueChanged(double value)
{
max_value_ = value;
UpdateColors();
}
void LaserScanPlugin::BufferSizeChanged(int value)
{
buffer_size_ = value;
if (buffer_size_ > 0)
{
while (scans_.size() > buffer_size_)
{
scans_.pop_front();
}
}
}
void LaserScanPlugin::PointSizeChanged(int value)
{
point_size_ = value;
}
void LaserScanPlugin::laserScanCallback(const sensor_msgs::LaserScanConstPtr& msg)
{
if (!has_message_)
{
initialized_ = true;
has_message_ = true;
}
// Note that unlike some plugins, this one does not store nor rely on the
// source_frame_ member variable. This one can potentially store many
// messages with different source frames, so we need to store and transform
// them individually.
Scan scan;
scan.stamp = msg->header.stamp;
scan.color = QColor::fromRgbF(1.0f, 0.0f, 0.0f, 1.0f);
scan.source_frame_ = msg->header.frame_id;
scan.transformed = true;
scan.has_intensity = !msg->intensities.empty();
scan.points.clear();
swri_transform_util::Transform transform;
if (!GetTransform(scan.source_frame_, msg->header.stamp, transform))
{
scan.transformed = false;
PrintError("No transform between " + source_frame_ + " and " + target_frame_);
}
double angle, x, y;
for (size_t i = 0; i < msg->ranges.size(); i++)
{
// Discard the point if it's out of range
if (msg->ranges[i] > msg->range_max || msg->ranges[i] < msg->range_min)
{
continue;
}
StampedPoint point;
angle = msg->angle_min + msg->angle_increment * i;
x = cos(angle) * msg->ranges[i];
y = sin(angle) * msg->ranges[i];
point.point = tf::Point(x, y, 0.0f);
point.range = msg->ranges[i];
if (i < msg->intensities.size())
point.intensity = msg->intensities[i];
if (scan.transformed)
{
point.transformed_point = transform * point.point;
}
point.color = CalculateColor(point, scan.has_intensity);
scan.points.push_back(point);
}
scans_.push_back(scan);
// If there are more items in the scan buffer than buffer_size_, remove them
if (buffer_size_ > 0)
{
while (scans_.size() > buffer_size_)
{
scans_.pop_front();
}
}
}
void LaserScanPlugin::PrintError(const std::string& message)
{
if (message == ui_.status->text().toStdString())
return;
ROS_ERROR("Error: %s", message.c_str());
QPalette p(ui_.status->palette());
p.setColor(QPalette::Text, Qt::red);
ui_.status->setPalette(p);
ui_.status->setText(message.c_str());
}
void LaserScanPlugin::PrintInfo(const std::string& message)
{
if (message == ui_.status->text().toStdString())
return;
ROS_INFO("%s", message.c_str());
QPalette p(ui_.status->palette());
p.setColor(QPalette::Text, Qt::green);
ui_.status->setPalette(p);
ui_.status->setText(message.c_str());
}
void LaserScanPlugin::PrintWarning(const std::string& message)
{
if (message == ui_.status->text().toStdString())
return;
ROS_WARN("%s", message.c_str());
QPalette p(ui_.status->palette());
p.setColor(QPalette::Text, Qt::darkYellow);
ui_.status->setPalette(p);
ui_.status->setText(message.c_str());
}
QWidget* LaserScanPlugin::GetConfigWidget(QWidget* parent)
{
config_widget_->setParent(parent);
return config_widget_;
}
bool LaserScanPlugin::Initialize(QGLWidget* canvas)
{
canvas_ = canvas;
DrawIcon();
return true;
}
void LaserScanPlugin::Draw(double x, double y, double scale)
{
ros::Time now = ros::Time::now();
glPointSize(point_size_);
glBegin(GL_POINTS);
std::deque<Scan>::const_iterator scan_it = scans_.begin();
while (scan_it != scans_.end())
{
if (scan_it->transformed)
{
std::vector<StampedPoint>::const_iterator point_it = scan_it->points.begin();
for (; point_it != scan_it->points.end(); ++point_it)
{
glColor4f(
point_it->color.redF(),
point_it->color.greenF(),
point_it->color.blueF(),
alpha_);
glVertex2f(
point_it->transformed_point.getX(),
point_it->transformed_point.getY());
}
}
++scan_it;
}
glEnd();
PrintInfo("OK");
}
void LaserScanPlugin::UseRainbowChanged(int check_state)
{
if (check_state == Qt::Checked)
{
ui_.max_color->setVisible(false);
ui_.min_color->setVisible(false);
ui_.maxColorLabel->setVisible(false);
ui_.minColorLabel->setVisible(false);
}
else
{
ui_.max_color->setVisible(true);
ui_.min_color->setVisible(true);
ui_.maxColorLabel->setVisible(true);
ui_.minColorLabel->setVisible(true);
}
UpdateColors();
}
void LaserScanPlugin::Transform()
{
std::deque<Scan>::iterator scan_it = scans_.begin();
for (; scan_it != scans_.end(); ++scan_it)
{
Scan& scan = *scan_it;
swri_transform_util::Transform transform;
bool was_using_latest_transforms = this->use_latest_transforms_;
this->use_latest_transforms_ = false;
if (GetTransform(scan.source_frame_, scan.stamp, transform))
{
scan.transformed = true;
std::vector<StampedPoint>::iterator point_it = scan.points.begin();
for (; point_it != scan.points.end(); ++point_it)
{
point_it->transformed_point = transform * point_it->point;
}
}
else
{
scan.transformed = false;
}
this->use_latest_transforms_ = was_using_latest_transforms;
}
// Z color is based on transformed color, so it is dependent on the
// transform
if (ui_.color_transformer->currentIndex() == COLOR_Z)
{
UpdateColors();
}
}
void LaserScanPlugin::LoadConfig(const YAML::Node& node,
const std::string& path)
{
if (node["topic"])
{
std::string topic;
node["topic"] >> topic;
ui_.topic->setText(boost::trim_copy(topic).c_str());
TopicEdited();
}
if (node["size"])
{
node["size"] >> point_size_;
ui_.pointSize->setValue(point_size_);
}
if (node["buffer_size"])
{
node["buffer_size"] >> buffer_size_;
ui_.bufferSize->setValue(buffer_size_);
}
if (node["color_transformer"])
{
std::string color_transformer;
node["color_transformer"] >> color_transformer;
if (color_transformer == "Intensity")
ui_.color_transformer->setCurrentIndex(COLOR_INTENSITY);
else if (color_transformer == "Range")
ui_.color_transformer->setCurrentIndex(COLOR_RANGE);
else if (color_transformer == "X Axis")
ui_.color_transformer->setCurrentIndex(COLOR_X);
else if (color_transformer == "Y Axis")
ui_.color_transformer->setCurrentIndex(COLOR_Y);
else if (color_transformer == "Z Axis")
ui_.color_transformer->setCurrentIndex(COLOR_Z);
else
ui_.color_transformer->setCurrentIndex(COLOR_FLAT);
}
if (node["min_color"])
{
std::string min_color_str;
node["min_color"] >> min_color_str;
ui_.min_color->setColor(QColor(min_color_str.c_str()));
}
if (node["max_color"])
{
std::string max_color_str;
node["max_color"] >> max_color_str;
ui_.max_color->setColor(QColor(max_color_str.c_str()));
}
if (node["value_min"])
{
node["value_min"] >> min_value_;
ui_.minValue->setValue(min_value_);
}
if (node["max_value"])
{
node["value_max"] >> max_value_;
ui_.maxValue->setValue(max_value_);
}
if (node["alpha"])
{
node["alpha"] >> alpha_;
ui_.alpha->setValue(alpha_);
AlphaEdited();
}
if (node["use_rainbow"])
{
bool use_rainbow;
node["use_rainbow"] >> use_rainbow;
ui_.use_rainbow->setChecked(use_rainbow);
}
// UseRainbowChanged must be called *before* ColorTransformerChanged
UseRainbowChanged(ui_.use_rainbow->checkState());
// ColorTransformerChanged will also update colors of all points
ColorTransformerChanged(ui_.color_transformer->currentIndex());
}
void LaserScanPlugin::ColorTransformerChanged(int index)
{
ROS_DEBUG("Color transformer changed to %d", index);
switch (index)
{
case COLOR_FLAT:
ui_.min_color->setVisible(true);
ui_.max_color->setVisible(false);
ui_.maxColorLabel->setVisible(false);
ui_.minColorLabel->setVisible(false);
ui_.minValueLabel->setVisible(false);
ui_.maxValueLabel->setVisible(false);
ui_.minValue->setVisible(false);
ui_.maxValue->setVisible(false);
ui_.use_rainbow->setVisible(false);
break;
case COLOR_INTENSITY: // Intensity
case COLOR_RANGE: // Range
case COLOR_X: // X Axis
case COLOR_Y: // Y Axis
case COLOR_Z: // Z axis
default:
ui_.min_color->setVisible(!ui_.use_rainbow->isChecked());
ui_.max_color->setVisible(!ui_.use_rainbow->isChecked());
ui_.maxColorLabel->setVisible(!ui_.use_rainbow->isChecked());
ui_.minColorLabel->setVisible(!ui_.use_rainbow->isChecked());
ui_.minValueLabel->setVisible(true);
ui_.maxValueLabel->setVisible(true);
ui_.minValue->setVisible(true);
ui_.maxValue->setVisible(true);
ui_.use_rainbow->setVisible(true);
break;
}
UpdateColors();
}
/**
* Coerces alpha to [0.0, 1.0] and stores it in alpha_
*/
void LaserScanPlugin::AlphaEdited()
{
alpha_ = std::max(0.0f, std::min(ui_.alpha->text().toFloat(), 1.0f));
ui_.alpha->setValue(alpha_);
}
void LaserScanPlugin::SaveConfig(YAML::Emitter& emitter,
const std::string& path)
{
emitter << YAML::Key << "topic" <<
YAML::Value << boost::trim_copy(ui_.topic->text().toStdString());
emitter << YAML::Key << "size" <<
YAML::Value << ui_.pointSize->value();
emitter << YAML::Key << "buffer_size" <<
YAML::Value << ui_.bufferSize->value();
emitter << YAML::Key << "alpha" <<
YAML::Value << alpha_;
emitter << YAML::Key << "color_transformer" <<
YAML::Value << ui_.color_transformer->currentText().toStdString();
emitter << YAML::Key << "min_color" <<
YAML::Value << ui_.min_color->color().name().toStdString();
emitter << YAML::Key << "max_color" <<
YAML::Value << ui_.max_color->color().name().toStdString();
emitter << YAML::Key << "value_min" <<
YAML::Value << ui_.minValue->text().toDouble();
emitter << YAML::Key << "value_max" <<
YAML::Value << ui_.maxValue->text().toDouble();
emitter << YAML::Key << "use_rainbow" <<
YAML::Value << ui_.use_rainbow->isChecked();
}
}
| bsd-3-clause |
raisedadead/FreeCodeCamp | curriculum/challenges/chinese-traditional/02-javascript-algorithms-and-data-structures/functional-programming/apply-functional-programming-to-convert-strings-to-url-slugs.md | 2469 | ---
id: 587d7dab367417b2b2512b6d
title: 應用函數式編程將字符串轉換爲URL片段
challengeType: 1
forumTopicId: 301227
dashedName: apply-functional-programming-to-convert-strings-to-url-slugs
---
# --description--
最後幾個挑戰中涵蓋了許多符合函數式編程原則並在處理數組和字符串中非常有用的方法。 我們還學習了強大的、可以將問題簡化爲更簡單形式的 `reduce` 方法。 從計算平均值到排序,任何數組操作都可以用它來實現。 回想一下,`map` 和 `filter` 方法都是 `reduce` 的特殊實現。
讓我們把學到的知識結合起來解決一個實際問題。
許多內容管理站點(CMS)爲了讓添加書籤更簡單,會將帖子的標題添加到 URL 上。 舉個例子,如果你寫了一篇標題爲 `Stop Using Reduce` 的帖子,URL很可能會包含標題字符串的某種形式 (如:`.../stop-using-reduce`)。 你可能已經在 freeCodeCamp 網站上注意到了這一點。
# --instructions--
填寫 `urlSlug` 函數,將字符串 `title` 轉換成帶有連字符號的 URL。 您可以使用本節中介紹的任何方法,但不要用 `replace` 方法。 以下是本次挑戰的要求:
輸入包含空格和標題大小寫單詞的字符串
輸出字符串,單詞之間的空格用連字符 (`-`) 替換
輸出應該是小寫字母
輸出不應有任何空格
# --hints--
不能使用 `replace` 方法。
```js
assert(!code.match(/\.?[\s\S]*?replace/g));
```
`urlSlug("Winter Is Coming")` 應返回 `winter-is-coming`。
```js
assert(urlSlug('Winter Is Coming') === 'winter-is-coming');
```
`urlSlug(" Winter Is Coming")` 應返回 `winter-is-coming`。
```js
assert(urlSlug(' Winter Is Coming') === 'winter-is-coming');
```
`urlSlug("A Mind Needs Books Like A Sword Needs A Whetstone")` 應返回 `a-mind-needs-books-like-a-sword-needs-a-whetstone`。
```js
assert(
urlSlug('A Mind Needs Books Like A Sword Needs A Whetstone') ===
'a-mind-needs-books-like-a-sword-needs-a-whetstone'
);
```
`urlSlug("Hold The Door")` 應返回 `hold-the-door`。
```js
assert(urlSlug('Hold The Door') === 'hold-the-door');
```
# --seed--
## --seed-contents--
```js
// Only change code below this line
function urlSlug(title) {
}
// Only change code above this line
```
# --solutions--
```js
// Only change code below this line
function urlSlug(title) {
return title.trim().split(/\s+/).join("-").toLowerCase();
}
```
| bsd-3-clause |
bxlab/HiFive_Paper | Scripts/Timing/hiclib_heatmap.py | 813 | #!/usr/bin/env python
import sys
from hiclib import mapping, fragmentHiC
from mirnylib import h5dict, genome
import h5py
basedir = sys.argv[1]
genome_db = genome.Genome('%s/Data/Genome/mm9_fasta' % basedir, readChrms=['1'], chrmFileTemplate="%s.fa")
temp = h5py.File('%s/Data/Timing/hiclib_data_norm.hdf5' % basedir, 'r')
weights = temp['weights'][...]
temp.close()
fragments = fragmentHiC.HiCdataset(
filename='temp',
genome=genome_db,
maximumMoleculeLength=500,
mode='a',
enzymeName="NcoI",
inMemory=True)
fragments.load('%s/Data/Timing/hiclib_data_norm.hdf5' % basedir)
fragments.weights = weights
fragments.fragmentWeights = weights
fragments.vectors['weights'] = 'float32'
fragments.saveHeatmap('%s/Data/Timing/hiclib_heatmap.hdf5' % basedir, resolution=10000, useWeights=True) | bsd-3-clause |
raonyguimaraes/mendelmd | filter_analysis/templates/tabs/main_familyanalysis.html | 3095 | <style type="text/css">
#s2id_id_groups, #s2id_id_individuals, #s2id_id_exclude_individuals, #s2id_id_exclude_groups, #s2id_id_genelists, #s2id_id_exclude_genelists, #s2id_id_father, #s2id_id_mother, #s2id_id_children{
width:240px;
/*height: 50px;*/
}
#id_individuals, #id_exclude_individuals, #id_groups, #id_exclude_groups, #id_genelists, #id_exclude_genelists{
display:none;
}
</style>
<script>
$(document).ready(function() {
$("#id_father").select2({
width: 'off',
placeholder: "SELECT FATHER",
allowClear: true,
});
$("#id_mother").select2({
width: 'off',
placeholder: "SELECT MOTHER",
allowClear: true,
});
$("#id_children").select2({
width: 'off',
placeholder: "SELECT CHILDREN",
allowClear: true,
});
$("#id_individuals").select2(
{
width: 'off',
placeholder: "SELECT YOUR CASES",
allowClear: true,
}
); });
$(document).ready(function() { $("#id_exclude_individuals").select2(
{ width: 'off',
placeholder: "SELECT YOUR CONTROLS", }
); });
$(document).ready(function() { $("#id_groups").select2(
{ width: 'off',
placeholder: "SELECT YOUR GROUPS", }
); });
$(document).ready(function() { $("#id_exclude_groups").select2(
{ width: 'off',
placeholder: "SELECT YOUR GROUPS", }
); });
$(document).ready(function() { $("#id_genelists").select2(
{ width: 'off',
placeholder: "SELECT YOUR GENELISTS", }
); });
$(document).ready(function() { $("#id_exclude_genelists").select2(
{ width: 'off',
placeholder: "SELECT YOUR GENELISTS", }
); });
</script>
<div class="span10">
<table class="table table-nonfluid table-striped table-bordered table-condensed">
<tr>
<th >FATHER</th>
<th >MOTHER</th>
<th >INHERITANCE</th>
</tr>
<tr>
<td>{{ form.father }}</td>
<td>{{ form.mother }}</td>
<td>{{ form.inheritance_option }}</td>
</tr>
<tr>
<th colspan="2">SELECT VARIANTS FROM</th>
<th colspan="2">EXCLUDE VARIANTS FROM</th>
</tr>
<tr>
<td> {{ form.individuals.errors }}{{ form.individuals.label }}:
<br>
{#{ form.individuals }#}
{{ form.children }}
<br>
{{ form.snp_list.errors }}
{{ form.snp_list.label }}:<br>
{{ form.snp_list }}
</td>
<td>
{{ form.groups.label }}:
<br>
{{ form.groups }}
<br>
{{ form.genelists.errors }}
{{ form.genelists.label }}:
<br>
{{ form.genelists }}
<br>
{{ form.gene_list.errors }}
{{ form.gene_list.label }}:
<br>
{{ form.gene_list }}
</td>
<td> {{ form.exclude_individuals.errors }}
{{ form.exclude_individuals.label }}:
<br>
{{ form.exclude_individuals }}
<br>{{ form.exclude_snp_list.label }}:<br>
{{ form.exclude_snp_list }}
</td>
<td>
{{ form.exclude_groups.label }}:
<br>
{{ form.exclude_groups }}
<br>
{{ form.exclude_genelists.errors }}
{{ form.exclude_genelists.label }}:
<br>
{{ form.exclude_genelists }}
<br>
{{ form.exclude_gene_list.errors }}
{{ form.exclude_gene_list.label }}:
<br>
{{ form.exclude_gene_list }}
</td>
</tr>
</table>
</div>
| bsd-3-clause |
brahmajiayatas/getweiss | protected/views/profile/online.php | 1760 | <div class="member_section">
<div class="login_home"> <a href="<?php echo Yii::app()->getHomeUrl(true); ?>"><img src="<?php echo Yii::app()->theme->baseUrl; ?>/images/login_home_img.png" alt="" /></a> </div>
<div class="login_arrow"> <a href="javascript:history.back()"><img src="<?php echo Yii::app()->theme->baseUrl; ?>/images/login_representation_img.png" alt="" /></a> </div>
<div class="clear"></div>
<div class="mid_blocks" id="mid_blocks">
<?php
if(!empty($models)){
foreach($models as $model){
$time1 = date("Y-m-d H:i:s");
$time2 = $model->LastLoginDate;
$timeDiff = Profile::model()->getDateTimeDiff($time1,$time2);
if($timeDiff < 1){
?>
<div class="view"> <img src="<?php echo Yii::app()->theme->baseUrl; ?>/images/img1.png" alt="">
<div class="mask">
<div class="test_section"><span><?php echo CHtml::link($model->UserName,array('profile/'.$model->UserId)); ?></span></div>
<div class="age_section"> <img src="<?php echo Yii::app()->theme->baseUrl; ?>/images/inner_man.png" alt="" /> <span><?php echo ($model->Gender) ? "Female" : "Male"; ?>, <?php if($model->DateOfBirth != '0000-00-00') echo Profile::model()->getAge(($model->DateOfBirth)); ?></span> </div>
<div class="age_section"> <img src="<?php echo Yii::app()->theme->baseUrl; ?>/images/map_icon.png" alt="" /> <span><?php echo $model->CityOrPostal; ?></span> </div>
<div class="hover_navigation">
<ul>
<li><a href="#">Mail </a></li>
<li><a href="#">Chat </a></li>
<li><a href="#">Wink</a></li>
</ul>
</div>
</div>
</div>
<?php } }
}else{
echo '<div class="notFound">Not Found!</div>';
}
?>
<div class="clear"></div>
</div>
</div> | bsd-3-clause |
webino/WebinoDev | tests/WebinoDev/ModuleTest.php | 1226 | <?php
/**
* Webino (http://webino.sk/)
*
* @link https://github.com/webino/WebinoDev/ for the canonical source repository
* @copyright Copyright (c) 2014-2017 Webino, s. r. o. (http://webino.sk/)
* @license BSD-3-Clause
*/
namespace WebinoDev;
/**
* WebinDev module tests
*/
class ModuleTest extends \PHPUnit_Framework_TestCase
{
/**
* @var Module
*/
protected $object;
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*/
protected function setUp()
{
$this->object = new Module;
}
/**
* Module initialization
*/
public function testInit()
{
$this->assertTrue(function_exists('d'));
$this->assertTrue(function_exists('dd'));
$this->assertTrue(function_exists('p'));
$this->assertTrue(function_exists('pd'));
$this->assertTrue(function_exists('pr'));
$this->assertTrue(function_exists('e'));
}
/**
* Module getConfig()
*
* @covers WebinoDev\Module::getConfig
*/
public function testGetConfig()
{
$this->assertTrue(is_array($this->object->getConfig()));
}
}
| bsd-3-clause |
Midnighter/MfinderWrapper | mfinderwrapper/mfinder/mat.c | 6759 | /************************************************************************
*
* File name: mat.c
*
* Description: matrix operations functions
*
* Copyright � 2002-2004 Weizmann Institute of Science,
* 76100 Rehovot Israel, All rights reserved
*
*************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "mat.h"
/*************************** Global variables ****************************/
/******************************* Externs *********************************/
extern int DEBUG_LEVEL;
/******************************* Functions *******************************/
Matrix*
init_matrix(int size) {
Matrix *mat;
mat = (Matrix*) calloc(1, sizeof (Matrix));
//if (DEBUG_LEVEL >=9)
//fprintf(GNRL_ST.log_fp,"function:init_matrix : mat allocated at %x\n",mat);
mat->size = size;
mat->m = (char*) calloc((size + 1)*(size + 1), sizeof (char));
//if (DEBUG_LEVEL >=9)
//fprintf(GNRL_ST.log_fp,"function:init_matrix : mat->m allocated at %x\n",mat->m);
return mat;
}
SparseMatrix*
init_spr_matrix(int size) {
SparseMatrix *mat;
mat = (SparseMatrix*) calloc(1, sizeof (SparseMatrix));
mat->size = size;
mat->m = (Edges_lists*) calloc((unsigned int) size + 1, sizeof (Edges_lists));
return mat;
}
void
clear_matrix(Matrix *M) {
int i;
int mat_cells_num = M->size * M->size;
for (i = 0; i < mat_cells_num; i++)
M->m[i] = 0;
}
void
free_matrix(Matrix *M) {
if (M != NULL) {
free(M->m);
//free((void*)M);
}
}
void
free_spr_matrix(SparseMatrix *M) {
int i;
if (M != NULL) {
for (i = 0; i <= M->size; i++) {
if (M->m[i].to != NULL)
list_free_mem(M->m[i].to);
if (M->m[i].from != NULL)
list_free_mem(M->m[i].from);
}
free(M->m);
}
}
void
dump_matrix(FILE *fp, Matrix *M, char *name) {
int i, j;
if (strcmp(name, ""))
fprintf(fp, "name :%s\n", name);
for (i = 1; i <= M->size; i++) {
fprintf(fp, "\n");
for (j = 1; j <= M->size; j++)
fprintf(fp, "%d ", MTRX(M, i, j));
}
fprintf(fp, "\n");
}
void
dump_spr_matrix(FILE *fp, Mat *M, char *name) {
int i, j;
if (strcmp(name, ""))
fprintf(fp, "name :%s\n", name);
for (i = 1; i <= M->spr->size; i++) {
fprintf(fp, "\n");
for (j = 1; j <= M->spr->size; j++)
fprintf(fp, "%d ", MatGet(M, i, j));
}
fprintf(fp, "\n");
}
//General matrices functions - full or sparse
//returns value of mat[i,j]
int
MatGet(Mat *mat, int i, int j) {
list_item *e_l;
switch (mat->type) {
case FULL:
return MTRX(mat->full, i, j);
break;
case SPARSE:
if (i < 0 || j < 0)
printf("Error in matget\n");
if (i == j) {
return (mat->spr->m[i].self_edge);
}
if ((e_l = list_get(mat->spr->m[i].to, j)) != NULL)
//edge exist
return *(int*) e_l->p;
else
//edge doest not exist return zero
return 0;
break;
default:
return -1;
break;
}
}
//asign values val to mat[i,j]
void
MatAsgn(Mat *mat, int i, int j, int val) {
list_item *e_l;
int *val_p;
switch (mat->type) {
case FULL:
MTRX(mat->full, i, j) = (char) val;
break;
case SPARSE:
if (i == j) {
mat->spr->m[i].self_edge = 1; //self edge
break;
}
//update the "to" lists
if (mat->spr->m[i].to == NULL) {
//no edges from this vertex
list_init(&mat->spr->m[i].to);
val_p = (int*) calloc(1, sizeof (int));
*val_p = val;
list_insert(mat->spr->m[i].to, j, val_p);
} else if ((e_l = list_get(mat->spr->m[i].to, j)) == NULL) {
//edges from this vertex exist but not this one
val_p = (int*) calloc(1, sizeof (int));
*val_p = val;
list_insert(mat->spr->m[i].to, j, val_p);
} else {
//edge exist but need to assign val
if (val == 0)
//need to delete this edge from list
list_delete(mat->spr->m[i].to, j);
else
//different value to be assigned
*(int*) e_l->p = val;
}
//update the "from" lists
if (mat->spr->m[j].from == NULL) {
//no edges from this vertex
list_init(&mat->spr->m[j].from);
val_p = (int*) calloc(1, sizeof (int));
*val_p = val;
list_insert(mat->spr->m[j].from, i, val_p);
} else if ((e_l = list_get(mat->spr->m[j].from, i)) == NULL) {
//edges from this vertex exist but not this one
val_p = (int*) calloc(1, sizeof (int));
*val_p = val;
list_insert(mat->spr->m[j].from, i, val_p);
} else {
//edge exist but need to assign val
if (val == 0)
//need to delete this edge from list
list_delete(mat->spr->m[j].from, i);
else
//different value to be assigned
*(int*) e_l->p = val;
}
break;
default:
break;
}
}
//arguments:
//type = FULL/SPARSE
int
MatInit(Mat **mat_p, int size, int type) {
Mat *mat;
mat = (Mat*) calloc(1, sizeof (Mat));
//if (DEBUG_LEVEL >=9)
//fprintf(GNRL_ST.log_fp,"function MatInit: mat allocated at %x\n",mat);
//if number of vertices not bigger then MAT_MAX_SIZE
//then use full matrix data structure
//else use sparse matrix data structure
//if(size <= MAT_MAX_SIZE)
//mat->type=FULL;
//else
//mat->type=SPARSE;
mat->type = type;
switch (mat->type) {
case FULL:
mat->full = init_matrix(size);
break;
case SPARSE:
mat->spr = init_spr_matrix(size);
break;
default:
return -1;
break;
}
*mat_p = mat;
return 0;
}
void
MatFree(Mat *mat) {
switch (mat->type) {
case FULL:
free_matrix(mat->full);
free((void*) mat->full);
break;
case SPARSE:
free_spr_matrix(mat->spr);
free((void*) mat->spr);
break;
default:
break;
}
}
| bsd-3-clause |
UsuarioCristian/basic2015 | api/assets/js/controllers/controllers.js | 450 | 'use strict';
angular.module('app.controllers', [])
.controller('HomeController', ['$scope','CountryFactory', function($scope, CountryFactory){
$scope.paisSeleccionado = [];
CountryFactory.getAllCountries();
$scope.mostrarPaises = function(){
CountryFactory.getAllCountries();
var countries = CountryFactory.getCountries();
$scope.paisSeleccionado = countries[0];
}
$scope.crearPais = function(){
CountryFactory.crearPais();
}
}]) | bsd-3-clause |
primiano/blink-gitcs | Source/web/WebRuntimeFeatures.cpp | 8907 | /*
* Copyright (C) 2013 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. 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.
*/
#include "config.h"
#include "public/web/WebRuntimeFeatures.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "web/WebMediaPlayerClientImpl.h"
namespace blink {
void WebRuntimeFeatures::enableExperimentalFeatures(bool enable)
{
RuntimeEnabledFeatures::setExperimentalFeaturesEnabled(enable);
}
void WebRuntimeFeatures::enableBleedingEdgeFastPaths(bool enable)
{
ASSERT(enable);
RuntimeEnabledFeatures::setBleedingEdgeFastPathsEnabled(enable);
RuntimeEnabledFeatures::setWebAnimationsAPIEnabled(enable);
}
void WebRuntimeFeatures::enableBlinkScheduler(bool enable)
{
RuntimeEnabledFeatures::setBlinkSchedulerEnabled(enable);
}
void WebRuntimeFeatures::enableTestOnlyFeatures(bool enable)
{
RuntimeEnabledFeatures::setTestFeaturesEnabled(enable);
}
void WebRuntimeFeatures::enableApplicationCache(bool enable)
{
RuntimeEnabledFeatures::setApplicationCacheEnabled(enable);
}
void WebRuntimeFeatures::enableCompositedSelectionUpdate(bool enable)
{
RuntimeEnabledFeatures::setCompositedSelectionUpdateEnabled(enable);
}
bool WebRuntimeFeatures::isCompositedSelectionUpdateEnabled()
{
return RuntimeEnabledFeatures::compositedSelectionUpdateEnabled();
}
void WebRuntimeFeatures::enableDatabase(bool enable)
{
RuntimeEnabledFeatures::setDatabaseEnabled(enable);
}
void WebRuntimeFeatures::enableDecodeToYUV(bool enable)
{
RuntimeEnabledFeatures::setDecodeToYUVEnabled(enable);
}
void WebRuntimeFeatures::forceDisplayList2dCanvas(bool enable)
{
RuntimeEnabledFeatures::setForceDisplayList2dCanvasEnabled(enable);
}
void WebRuntimeFeatures::enableDisplayList2dCanvas(bool enable)
{
RuntimeEnabledFeatures::setDisplayList2dCanvasEnabled(enable);
}
void WebRuntimeFeatures::enableEncryptedMedia(bool enable)
{
RuntimeEnabledFeatures::setEncryptedMediaEnabled(enable);
}
bool WebRuntimeFeatures::isEncryptedMediaEnabled()
{
return RuntimeEnabledFeatures::encryptedMediaEnabled();
}
void WebRuntimeFeatures::enablePrefixedEncryptedMedia(bool enable)
{
RuntimeEnabledFeatures::setPrefixedEncryptedMediaEnabled(enable);
}
bool WebRuntimeFeatures::isPrefixedEncryptedMediaEnabled()
{
return RuntimeEnabledFeatures::prefixedEncryptedMediaEnabled();
}
void WebRuntimeFeatures::enableExperimentalCanvasFeatures(bool enable)
{
RuntimeEnabledFeatures::setExperimentalCanvasFeaturesEnabled(enable);
}
void WebRuntimeFeatures::enableFastMobileScrolling(bool enable)
{
RuntimeEnabledFeatures::setFastMobileScrollingEnabled(enable);
}
void WebRuntimeFeatures::enableFileSystem(bool enable)
{
RuntimeEnabledFeatures::setFileSystemEnabled(enable);
}
void WebRuntimeFeatures::enableImageColorProfiles(bool enable)
{
RuntimeEnabledFeatures::setImageColorProfilesEnabled(enable);
}
void WebRuntimeFeatures::enableLocalStorage(bool enable)
{
RuntimeEnabledFeatures::setLocalStorageEnabled(enable);
}
void WebRuntimeFeatures::enableMediaPlayer(bool enable)
{
RuntimeEnabledFeatures::setMediaEnabled(enable);
}
void WebRuntimeFeatures::enableMediaCapture(bool enable)
{
RuntimeEnabledFeatures::setMediaCaptureEnabled(enable);
}
void WebRuntimeFeatures::enableMediaSource(bool enable)
{
RuntimeEnabledFeatures::setMediaSourceEnabled(enable);
}
void WebRuntimeFeatures::enableNotifications(bool enable)
{
RuntimeEnabledFeatures::setNotificationsEnabled(enable);
}
void WebRuntimeFeatures::enableNavigatorContentUtils(bool enable)
{
RuntimeEnabledFeatures::setNavigatorContentUtilsEnabled(enable);
}
void WebRuntimeFeatures::enableNavigationTransitions(bool enable)
{
RuntimeEnabledFeatures::setNavigationTransitionsEnabled(enable);
}
void WebRuntimeFeatures::enableNetworkInformation(bool enable)
{
RuntimeEnabledFeatures::setNetworkInformationEnabled(enable);
}
void WebRuntimeFeatures::enableOrientationEvent(bool enable)
{
RuntimeEnabledFeatures::setOrientationEventEnabled(enable);
}
void WebRuntimeFeatures::enablePagePopup(bool enable)
{
RuntimeEnabledFeatures::setPagePopupEnabled(enable);
}
void WebRuntimeFeatures::enablePeerConnection(bool enable)
{
RuntimeEnabledFeatures::setPeerConnectionEnabled(enable);
}
void WebRuntimeFeatures::enableRequestAutocomplete(bool enable)
{
RuntimeEnabledFeatures::setRequestAutocompleteEnabled(enable);
}
void WebRuntimeFeatures::enableScreenOrientation(bool enable)
{
RuntimeEnabledFeatures::setScreenOrientationEnabled(enable);
}
void WebRuntimeFeatures::enableScriptedSpeech(bool enable)
{
RuntimeEnabledFeatures::setScriptedSpeechEnabled(enable);
}
void WebRuntimeFeatures::enableServiceWorker(bool enable)
{
RuntimeEnabledFeatures::setServiceWorkerEnabled(enable);
}
void WebRuntimeFeatures::enableSessionStorage(bool enable)
{
RuntimeEnabledFeatures::setSessionStorageEnabled(enable);
}
void WebRuntimeFeatures::enableSlimmingPaint(bool enable)
{
RuntimeEnabledFeatures::setSlimmingPaintEnabled(enable);
}
void WebRuntimeFeatures::enableTouch(bool enable)
{
RuntimeEnabledFeatures::setTouchEnabled(enable);
}
void WebRuntimeFeatures::enableTouchIconLoading(bool enable)
{
RuntimeEnabledFeatures::setTouchIconLoadingEnabled(enable);
}
void WebRuntimeFeatures::enableWebAudio(bool enable)
{
RuntimeEnabledFeatures::setWebAudioEnabled(enable);
}
void WebRuntimeFeatures::enableWebGLDraftExtensions(bool enable)
{
RuntimeEnabledFeatures::setWebGLDraftExtensionsEnabled(enable);
}
void WebRuntimeFeatures::enableWebGLImageChromium(bool enable)
{
RuntimeEnabledFeatures::setWebGLImageChromiumEnabled(enable);
}
void WebRuntimeFeatures::enableWebMIDI(bool enable)
{
return RuntimeEnabledFeatures::setWebMIDIEnabled(enable);
}
void WebRuntimeFeatures::enableXSLT(bool enable)
{
RuntimeEnabledFeatures::setXSLTEnabled(enable);
}
void WebRuntimeFeatures::enableOverlayScrollbars(bool enable)
{
RuntimeEnabledFeatures::setOverlayScrollbarsEnabled(enable);
}
void WebRuntimeFeatures::enableOverlayFullscreenVideo(bool enable)
{
RuntimeEnabledFeatures::setOverlayFullscreenVideoEnabled(enable);
}
void WebRuntimeFeatures::enableSharedWorker(bool enable)
{
RuntimeEnabledFeatures::setSharedWorkerEnabled(enable);
}
void WebRuntimeFeatures::enablePreciseMemoryInfo(bool enable)
{
RuntimeEnabledFeatures::setPreciseMemoryInfoEnabled(enable);
}
void WebRuntimeFeatures::enableShowModalDialog(bool enable)
{
RuntimeEnabledFeatures::setShowModalDialogEnabled(enable);
}
void WebRuntimeFeatures::enableLaxMixedContentChecking(bool enable)
{
RuntimeEnabledFeatures::setLaxMixedContentCheckingEnabled(enable);
}
void WebRuntimeFeatures::enableCredentialManagerAPI(bool enable)
{
RuntimeEnabledFeatures::setCredentialManagerEnabled(enable);
}
void WebRuntimeFeatures::enableTextBlobs(bool enable)
{
RuntimeEnabledFeatures::setTextBlobEnabled(enable);
}
void WebRuntimeFeatures::enableCSSViewport(bool enable)
{
RuntimeEnabledFeatures::setCSSViewportEnabled(enable);
}
void WebRuntimeFeatures::enableV8IdleTasks(bool enable)
{
RuntimeEnabledFeatures::setV8IdleTasksEnabled(enable);
}
void WebRuntimeFeatures::enableSVG1DOM(bool enable)
{
RuntimeEnabledFeatures::setSVG1DOMEnabled(enable);
}
void WebRuntimeFeatures::enableReducedReferrerGranularity(bool enable)
{
RuntimeEnabledFeatures::setReducedReferrerGranularityEnabled(enable);
}
} // namespace blink
| bsd-3-clause |
ChromiumWebApps/chromium | ash/wm/window_manager_unittest.cc | 31970 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/shell.h"
#include "ash/shell_window_ids.h"
#include "ash/test/ash_test_base.h"
#include "ash/test/shell_test_api.h"
#include "ash/test/test_activation_delegate.h"
#include "ash/wm/window_util.h"
#include "ui/aura/client/activation_client.h"
#include "ui/aura/client/activation_delegate.h"
#include "ui/aura/client/cursor_client_observer.h"
#include "ui/aura/client/focus_client.h"
#include "ui/aura/env.h"
#include "ui/aura/root_window.h"
#include "ui/aura/test/aura_test_base.h"
#include "ui/aura/test/event_generator.h"
#include "ui/aura/test/test_event_handler.h"
#include "ui/aura/test/test_window_delegate.h"
#include "ui/aura/test/test_windows.h"
#include "ui/base/cursor/cursor.h"
#include "ui/base/hit_test.h"
#include "ui/events/event.h"
#include "ui/events/event_utils.h"
#include "ui/gfx/screen.h"
#include "ui/views/corewm/compound_event_filter.h"
#include "ui/views/corewm/corewm_switches.h"
#include "ui/views/corewm/input_method_event_filter.h"
namespace {
class TestingCursorClientObserver : public aura::client::CursorClientObserver {
public:
TestingCursorClientObserver()
: cursor_visibility_(false),
did_visibility_change_(false) {}
void reset() { cursor_visibility_ = did_visibility_change_ = false; }
bool is_cursor_visible() const { return cursor_visibility_; }
bool did_visibility_change() const { return did_visibility_change_; }
// Overridden from aura::client::CursorClientObserver:
virtual void OnCursorVisibilityChanged(bool is_visible) OVERRIDE {
cursor_visibility_ = is_visible;
did_visibility_change_ = true;
}
private:
bool cursor_visibility_;
bool did_visibility_change_;
DISALLOW_COPY_AND_ASSIGN(TestingCursorClientObserver);
};
base::TimeDelta getTime() {
return ui::EventTimeForNow();
}
// A slightly changed TestEventHandler which can be configured to return a
// specified value for key/mouse event handling.
class CustomEventHandler : public aura::test::TestEventHandler {
public:
CustomEventHandler()
: key_result_(ui::ER_UNHANDLED),
mouse_result_(ui::ER_UNHANDLED) {
}
virtual ~CustomEventHandler() {}
void set_key_event_handling_result(ui::EventResult result) {
key_result_ = result;
}
void set_mouse_event_handling_result(ui::EventResult result) {
mouse_result_ = result;
}
// Overridden from ui::EventHandler:
virtual void OnKeyEvent(ui::KeyEvent* event) OVERRIDE {
aura::test::TestEventHandler::OnKeyEvent(event);
if (key_result_ & ui::ER_HANDLED)
event->SetHandled();
if (key_result_ & ui::ER_CONSUMED)
event->StopPropagation();
}
virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE {
aura::test::TestEventHandler::OnMouseEvent(event);
if (mouse_result_ & ui::ER_HANDLED)
event->SetHandled();
if (mouse_result_ & ui::ER_CONSUMED)
event->StopPropagation();
}
private:
ui::EventResult key_result_;
ui::EventResult mouse_result_;
DISALLOW_COPY_AND_ASSIGN(CustomEventHandler);
};
} // namespace
namespace ash {
typedef test::AshTestBase WindowManagerTest;
class NonFocusableDelegate : public aura::test::TestWindowDelegate {
public:
NonFocusableDelegate() {}
private:
virtual bool CanFocus() OVERRIDE {
return false;
}
DISALLOW_COPY_AND_ASSIGN(NonFocusableDelegate);
};
class HitTestWindowDelegate : public aura::test::TestWindowDelegate {
public:
HitTestWindowDelegate()
: hittest_code_(HTNOWHERE) {
}
virtual ~HitTestWindowDelegate() {}
void set_hittest_code(int hittest_code) { hittest_code_ = hittest_code; }
private:
// Overridden from TestWindowDelegate:
virtual int GetNonClientComponent(const gfx::Point& point) const OVERRIDE {
return hittest_code_;
}
int hittest_code_;
DISALLOW_COPY_AND_ASSIGN(HitTestWindowDelegate);
};
TEST_F(WindowManagerTest, Focus) {
// The IME event filter interferes with the basic key event propagation we
// attempt to do here, so we remove it.
test::ShellTestApi shell_test(Shell::GetInstance());
Shell::GetInstance()->RemovePreTargetHandler(
shell_test.input_method_event_filter());
aura::Window* root_window = Shell::GetPrimaryRootWindow();
root_window->SetBounds(gfx::Rect(0, 0, 510, 510));
// Supplied ids are negative so as not to collide with shell ids.
// TODO(beng): maybe introduce a MAKE_SHELL_ID() macro that generates a safe
// id beyond shell id max?
scoped_ptr<aura::Window> w1(CreateTestWindowInShell(
SK_ColorWHITE, -1, gfx::Rect(10, 10, 500, 500)));
scoped_ptr<aura::Window> w11(aura::test::CreateTestWindow(
SK_ColorGREEN, -11, gfx::Rect(5, 5, 100, 100), w1.get()));
scoped_ptr<aura::Window> w111(aura::test::CreateTestWindow(
SK_ColorCYAN, -111, gfx::Rect(5, 5, 75, 75), w11.get()));
scoped_ptr<aura::Window> w1111(aura::test::CreateTestWindow(
SK_ColorRED, -1111, gfx::Rect(5, 5, 50, 50), w111.get()));
scoped_ptr<aura::Window> w12(aura::test::CreateTestWindow(
SK_ColorMAGENTA, -12, gfx::Rect(10, 420, 25, 25), w1.get()));
aura::test::ColorTestWindowDelegate* w121delegate =
new aura::test::ColorTestWindowDelegate(SK_ColorYELLOW);
scoped_ptr<aura::Window> w121(aura::test::CreateTestWindowWithDelegate(
w121delegate, -121, gfx::Rect(5, 5, 5, 5), w12.get()));
aura::test::ColorTestWindowDelegate* w122delegate =
new aura::test::ColorTestWindowDelegate(SK_ColorRED);
scoped_ptr<aura::Window> w122(aura::test::CreateTestWindowWithDelegate(
w122delegate, -122, gfx::Rect(10, 5, 5, 5), w12.get()));
aura::test::ColorTestWindowDelegate* w123delegate =
new aura::test::ColorTestWindowDelegate(SK_ColorRED);
scoped_ptr<aura::Window> w123(aura::test::CreateTestWindowWithDelegate(
w123delegate, -123, gfx::Rect(15, 5, 5, 5), w12.get()));
scoped_ptr<aura::Window> w13(aura::test::CreateTestWindow(
SK_ColorGRAY, -13, gfx::Rect(5, 470, 50, 50), w1.get()));
// Click on a sub-window (w121) to focus it.
aura::test::EventGenerator generator(Shell::GetPrimaryRootWindow(),
w121.get());
generator.ClickLeftButton();
aura::client::FocusClient* focus_client =
aura::client::GetFocusClient(w121.get());
EXPECT_EQ(w121.get(), focus_client->GetFocusedWindow());
aura::WindowEventDispatcher* dispatcher = root_window->GetDispatcher();
// The key press should be sent to the focused sub-window.
ui::KeyEvent keyev(ui::ET_KEY_PRESSED, ui::VKEY_E, 0, false);
ui::EventDispatchDetails details = dispatcher->OnEventFromSource(&keyev);
ASSERT_FALSE(details.dispatcher_destroyed);
EXPECT_EQ(ui::VKEY_E, w121delegate->last_key_code());
// Touch on a sub-window (w122) to focus it.
gfx::Point click_point = w122->bounds().CenterPoint();
aura::Window::ConvertPointToTarget(w122->parent(), root_window, &click_point);
ui::TouchEvent touchev(ui::ET_TOUCH_PRESSED, click_point, 0, getTime());
details = dispatcher->OnEventFromSource(&touchev);
ASSERT_FALSE(details.dispatcher_destroyed);
focus_client = aura::client::GetFocusClient(w122.get());
EXPECT_EQ(w122.get(), focus_client->GetFocusedWindow());
// The key press should be sent to the focused sub-window.
details = dispatcher->OnEventFromSource(&keyev);
ASSERT_FALSE(details.dispatcher_destroyed);
EXPECT_EQ(ui::VKEY_E, w122delegate->last_key_code());
// Hiding the focused window will set the focus to its parent if
// it's focusable.
w122->Hide();
EXPECT_EQ(aura::client::GetFocusClient(w12.get()),
aura::client::GetFocusClient(w122.get()));
EXPECT_EQ(w12.get(),
aura::client::GetFocusClient(w12.get())->GetFocusedWindow());
// Sets the focus back to w122.
w122->Show();
w122->Focus();
EXPECT_EQ(w122.get(),
aura::client::GetFocusClient(w12.get())->GetFocusedWindow());
// Removing the focused window from parent should set the focus to
// its parent if it's focusable.
w12->RemoveChild(w122.get());
EXPECT_EQ(NULL, aura::client::GetFocusClient(w122.get()));
EXPECT_EQ(w12.get(),
aura::client::GetFocusClient(w12.get())->GetFocusedWindow());
// Set the focus to w123, but make the w1 not activatable.
test::TestActivationDelegate activation_delegate(false);
w123->Focus();
EXPECT_EQ(w123.get(),
aura::client::GetFocusClient(w12.get())->GetFocusedWindow());
aura::client::SetActivationDelegate(w1.get(), &activation_delegate);
// Hiding the focused window will set the focus to NULL because
// parent window is not focusable.
w123->Hide();
EXPECT_EQ(aura::client::GetFocusClient(w12.get()),
aura::client::GetFocusClient(w123.get()));
EXPECT_EQ(NULL, aura::client::GetFocusClient(w12.get())->GetFocusedWindow());
details = dispatcher->OnEventFromSource(&keyev);
EXPECT_FALSE(keyev.handled() || details.dispatcher_destroyed);
// Set the focus back to w123
aura::client::SetActivationDelegate(w1.get(), NULL);
w123->Show();
w123->Focus();
EXPECT_EQ(w123.get(),
aura::client::GetFocusClient(w12.get())->GetFocusedWindow());
aura::client::SetActivationDelegate(w1.get(), &activation_delegate);
// Removing the focused window will set the focus to NULL because
// parent window is not focusable.
w12->RemoveChild(w123.get());
EXPECT_EQ(NULL, aura::client::GetFocusClient(w123.get()));
details = dispatcher->OnEventFromSource(&keyev);
EXPECT_FALSE(keyev.handled() || details.dispatcher_destroyed);
}
// Various assertion testing for activating windows.
TEST_F(WindowManagerTest, ActivateOnMouse) {
aura::Window* root_window = Shell::GetPrimaryRootWindow();
test::TestActivationDelegate d1;
aura::test::TestWindowDelegate wd;
scoped_ptr<aura::Window> w1(CreateTestWindowInShellWithDelegate(
&wd, -1, gfx::Rect(10, 10, 50, 50)));
d1.SetWindow(w1.get());
test::TestActivationDelegate d2;
scoped_ptr<aura::Window> w2(CreateTestWindowInShellWithDelegate(
&wd, -2, gfx::Rect(70, 70, 50, 50)));
d2.SetWindow(w2.get());
aura::client::FocusClient* focus_client =
aura::client::GetFocusClient(w1.get());
d1.Clear();
d2.Clear();
// Activate window1.
wm::ActivateWindow(w1.get());
EXPECT_TRUE(wm::IsActiveWindow(w1.get()));
EXPECT_EQ(w1.get(), focus_client->GetFocusedWindow());
EXPECT_EQ(1, d1.activated_count());
EXPECT_EQ(0, d1.lost_active_count());
d1.Clear();
{
// Click on window2.
aura::test::EventGenerator generator(Shell::GetPrimaryRootWindow(),
w2.get());
generator.ClickLeftButton();
// Window2 should have become active.
EXPECT_TRUE(wm::IsActiveWindow(w2.get()));
EXPECT_EQ(w2.get(), focus_client->GetFocusedWindow());
EXPECT_EQ(0, d1.activated_count());
EXPECT_EQ(1, d1.lost_active_count());
EXPECT_EQ(1, d2.activated_count());
EXPECT_EQ(0, d2.lost_active_count());
d1.Clear();
d2.Clear();
}
{
// Click back on window1, but set it up so w1 doesn't activate on click.
aura::test::EventGenerator generator(Shell::GetPrimaryRootWindow(),
w1.get());
d1.set_activate(false);
generator.ClickLeftButton();
// Window2 should still be active and focused.
EXPECT_TRUE(wm::IsActiveWindow(w2.get()));
EXPECT_EQ(w2.get(), focus_client->GetFocusedWindow());
EXPECT_EQ(0, d1.activated_count());
EXPECT_EQ(0, d1.lost_active_count());
EXPECT_EQ(0, d2.activated_count());
EXPECT_EQ(0, d2.lost_active_count());
d1.Clear();
d2.Clear();
}
// Destroy window2, this should make window1 active.
d1.set_activate(true);
w2.reset();
EXPECT_EQ(0, d2.activated_count());
EXPECT_EQ(1, d2.lost_active_count());
EXPECT_TRUE(wm::IsActiveWindow(w1.get()));
EXPECT_EQ(w1.get(), focus_client->GetFocusedWindow());
EXPECT_EQ(1, d1.activated_count());
EXPECT_EQ(0, d1.lost_active_count());
// Clicking an active window with a child shouldn't steal the
// focus from the child.
{
scoped_ptr<aura::Window> w11(CreateTestWindowWithDelegate(
&wd, -11, gfx::Rect(10, 10, 10, 10), w1.get()));
aura::test::EventGenerator generator(Shell::GetPrimaryRootWindow(),
w11.get());
// First set the focus to the child |w11|.
generator.ClickLeftButton();
EXPECT_EQ(w11.get(), focus_client->GetFocusedWindow());
EXPECT_EQ(w1.get(), wm::GetActiveWindow());
// Then click the parent active window. The focus shouldn't move.
gfx::Point left_top = w1->bounds().origin();
aura::Window::ConvertPointToTarget(w1->parent(), root_window, &left_top);
left_top.Offset(1, 1);
generator.MoveMouseTo(left_top);
generator.ClickLeftButton();
EXPECT_EQ(w11.get(), focus_client->GetFocusedWindow());
EXPECT_EQ(w1.get(), wm::GetActiveWindow());
}
// Clicking on a non-focusable window inside a background window should still
// give focus to the background window.
{
NonFocusableDelegate nfd;
scoped_ptr<aura::Window> w11(CreateTestWindowWithDelegate(
&nfd, -1, gfx::Rect(10, 10, 10, 10), w1.get()));
// Move focus to |w2| first.
scoped_ptr<aura::Window> w2(CreateTestWindowInShellWithDelegate(
&wd, -1, gfx::Rect(70, 70, 50, 50)));
aura::test::EventGenerator generator(Shell::GetPrimaryRootWindow(),
w2.get());
generator.ClickLeftButton();
EXPECT_EQ(w2.get(), focus_client->GetFocusedWindow());
EXPECT_FALSE(w11->CanFocus());
// Click on |w11|. This should focus w1.
generator.MoveMouseToCenterOf(w11.get());
generator.ClickLeftButton();
EXPECT_EQ(w1.get(), focus_client->GetFocusedWindow());
}
}
TEST_F(WindowManagerTest, PanelActivation) {
aura::test::TestWindowDelegate wd;
scoped_ptr<aura::Window> w1(CreateTestWindowInShellWithDelegate(
&wd, -1, gfx::Rect(10, 10, 50, 50)));
aura::test::TestWindowDelegate pd;
scoped_ptr<aura::Window> p1(CreateTestWindowInShellWithDelegateAndType(
&pd, ui::wm::WINDOW_TYPE_PANEL, -1, gfx::Rect(10, 10, 50, 50)));
aura::client::FocusClient* focus_client =
aura::client::GetFocusClient(w1.get());
// Activate w1.
wm::ActivateWindow(w1.get());
EXPECT_TRUE(wm::IsActiveWindow(w1.get()));
// Activate p1.
wm::ActivateWindow(p1.get());
EXPECT_TRUE(wm::IsActiveWindow(p1.get()));
EXPECT_EQ(p1.get(), focus_client->GetFocusedWindow());
// Activate w1.
wm::ActivateWindow(w1.get());
EXPECT_TRUE(wm::IsActiveWindow(w1.get()));
EXPECT_EQ(w1.get(), focus_client->GetFocusedWindow());
// Clicking on a non-activatable window should not change the active window.
{
NonFocusableDelegate nfd;
scoped_ptr<aura::Window> w3(CreateTestWindowInShellWithDelegate(
&nfd, -1, gfx::Rect(70, 70, 50, 50)));
aura::test::EventGenerator generator3(Shell::GetPrimaryRootWindow(),
w3.get());
wm::ActivateWindow(p1.get());
EXPECT_TRUE(wm::IsActiveWindow(p1.get()));
generator3.ClickLeftButton();
EXPECT_TRUE(wm::IsActiveWindow(p1.get()));
}
}
// Essentially the same as ActivateOnMouse, but for touch events.
TEST_F(WindowManagerTest, ActivateOnTouch) {
aura::Window* root_window = Shell::GetPrimaryRootWindow();
test::TestActivationDelegate d1;
aura::test::TestWindowDelegate wd;
scoped_ptr<aura::Window> w1(CreateTestWindowInShellWithDelegate(
&wd, -1, gfx::Rect(10, 10, 50, 50)));
d1.SetWindow(w1.get());
test::TestActivationDelegate d2;
scoped_ptr<aura::Window> w2(CreateTestWindowInShellWithDelegate(
&wd, -2, gfx::Rect(70, 70, 50, 50)));
d2.SetWindow(w2.get());
aura::client::FocusClient* focus_client =
aura::client::GetFocusClient(w1.get());
d1.Clear();
d2.Clear();
// Activate window1.
wm::ActivateWindow(w1.get());
EXPECT_TRUE(wm::IsActiveWindow(w1.get()));
EXPECT_EQ(w1.get(), focus_client->GetFocusedWindow());
EXPECT_EQ(1, d1.activated_count());
EXPECT_EQ(0, d1.lost_active_count());
d1.Clear();
// Touch window2.
gfx::Point press_point = w2->bounds().CenterPoint();
aura::Window::ConvertPointToTarget(w2->parent(), root_window, &press_point);
ui::TouchEvent touchev1(ui::ET_TOUCH_PRESSED, press_point, 0, getTime());
aura::WindowEventDispatcher* dispatcher = root_window->GetDispatcher();
ui::EventDispatchDetails details = dispatcher->OnEventFromSource(&touchev1);
ASSERT_FALSE(details.dispatcher_destroyed);
// Window2 should have become active.
EXPECT_TRUE(wm::IsActiveWindow(w2.get()));
EXPECT_EQ(w2.get(), focus_client->GetFocusedWindow());
EXPECT_EQ(0, d1.activated_count());
EXPECT_EQ(1, d1.lost_active_count());
EXPECT_EQ(1, d2.activated_count());
EXPECT_EQ(0, d2.lost_active_count());
d1.Clear();
d2.Clear();
// Touch window1, but set it up so w1 doesn't activate on touch.
press_point = w1->bounds().CenterPoint();
aura::Window::ConvertPointToTarget(w1->parent(), root_window, &press_point);
d1.set_activate(false);
ui::TouchEvent touchev2(ui::ET_TOUCH_PRESSED, press_point, 1, getTime());
details = dispatcher->OnEventFromSource(&touchev2);
ASSERT_FALSE(details.dispatcher_destroyed);
// Window2 should still be active and focused.
EXPECT_TRUE(wm::IsActiveWindow(w2.get()));
EXPECT_EQ(w2.get(), focus_client->GetFocusedWindow());
EXPECT_EQ(0, d1.activated_count());
EXPECT_EQ(0, d1.lost_active_count());
EXPECT_EQ(0, d2.activated_count());
EXPECT_EQ(0, d2.lost_active_count());
d1.Clear();
d2.Clear();
// Destroy window2, this should make window1 active.
d1.set_activate(true);
w2.reset();
EXPECT_EQ(0, d2.activated_count());
EXPECT_EQ(1, d2.lost_active_count());
EXPECT_TRUE(wm::IsActiveWindow(w1.get()));
EXPECT_EQ(w1.get(), focus_client->GetFocusedWindow());
EXPECT_EQ(1, d1.activated_count());
EXPECT_EQ(0, d1.lost_active_count());
}
TEST_F(WindowManagerTest, MouseEventCursors) {
aura::Window* root_window = Shell::GetPrimaryRootWindow();
// Create a window.
const int kWindowLeft = 123;
const int kWindowTop = 45;
HitTestWindowDelegate window_delegate;
scoped_ptr<aura::Window> window(CreateTestWindowInShellWithDelegate(
&window_delegate,
-1,
gfx::Rect(kWindowLeft, kWindowTop, 640, 480)));
// Create two mouse movement events we can switch between.
gfx::Point point1(kWindowLeft, kWindowTop);
aura::Window::ConvertPointToTarget(window->parent(), root_window, &point1);
gfx::Point point2(kWindowLeft + 1, kWindowTop + 1);
aura::Window::ConvertPointToTarget(window->parent(), root_window, &point2);
aura::WindowEventDispatcher* dispatcher = root_window->GetDispatcher();
// Cursor starts as a pointer (set during Shell::Init()).
EXPECT_EQ(ui::kCursorPointer,
dispatcher->host()->last_cursor().native_type());
{
// Resize edges and corners show proper cursors.
window_delegate.set_hittest_code(HTBOTTOM);
ui::MouseEvent move1(ui::ET_MOUSE_MOVED, point1, point1, 0, 0);
ui::EventDispatchDetails details = dispatcher->OnEventFromSource(&move1);
ASSERT_FALSE(details.dispatcher_destroyed);
EXPECT_EQ(ui::kCursorSouthResize,
dispatcher->host()->last_cursor().native_type());
}
{
window_delegate.set_hittest_code(HTBOTTOMLEFT);
ui::MouseEvent move2(ui::ET_MOUSE_MOVED, point2, point2, 0, 0);
ui::EventDispatchDetails details = dispatcher->OnEventFromSource(&move2);
ASSERT_FALSE(details.dispatcher_destroyed);
EXPECT_EQ(ui::kCursorSouthWestResize,
dispatcher->host()->last_cursor().native_type());
}
{
window_delegate.set_hittest_code(HTBOTTOMRIGHT);
ui::MouseEvent move1(ui::ET_MOUSE_MOVED, point1, point1, 0, 0);
ui::EventDispatchDetails details = dispatcher->OnEventFromSource(&move1);
ASSERT_FALSE(details.dispatcher_destroyed);
EXPECT_EQ(ui::kCursorSouthEastResize,
dispatcher->host()->last_cursor().native_type());
}
{
window_delegate.set_hittest_code(HTLEFT);
ui::MouseEvent move2(ui::ET_MOUSE_MOVED, point2, point2, 0, 0);
ui::EventDispatchDetails details = dispatcher->OnEventFromSource(&move2);
ASSERT_FALSE(details.dispatcher_destroyed);
EXPECT_EQ(ui::kCursorWestResize,
dispatcher->host()->last_cursor().native_type());
}
{
window_delegate.set_hittest_code(HTRIGHT);
ui::MouseEvent move1(ui::ET_MOUSE_MOVED, point1, point1, 0, 0);
ui::EventDispatchDetails details = dispatcher->OnEventFromSource(&move1);
ASSERT_FALSE(details.dispatcher_destroyed);
EXPECT_EQ(ui::kCursorEastResize,
dispatcher->host()->last_cursor().native_type());
}
{
window_delegate.set_hittest_code(HTTOP);
ui::MouseEvent move2(ui::ET_MOUSE_MOVED, point2, point2, 0, 0);
ui::EventDispatchDetails details = dispatcher->OnEventFromSource(&move2);
ASSERT_FALSE(details.dispatcher_destroyed);
EXPECT_EQ(ui::kCursorNorthResize,
dispatcher->host()->last_cursor().native_type());
}
{
window_delegate.set_hittest_code(HTTOPLEFT);
ui::MouseEvent move1(ui::ET_MOUSE_MOVED, point1, point1, 0, 0);
ui::EventDispatchDetails details = dispatcher->OnEventFromSource(&move1);
ASSERT_FALSE(details.dispatcher_destroyed);
EXPECT_EQ(ui::kCursorNorthWestResize,
dispatcher->host()->last_cursor().native_type());
}
{
window_delegate.set_hittest_code(HTTOPRIGHT);
ui::MouseEvent move2(ui::ET_MOUSE_MOVED, point2, point2, 0, 0);
ui::EventDispatchDetails details = dispatcher->OnEventFromSource(&move2);
ASSERT_FALSE(details.dispatcher_destroyed);
EXPECT_EQ(ui::kCursorNorthEastResize,
dispatcher->host()->last_cursor().native_type());
}
{
// Client area uses null cursor.
window_delegate.set_hittest_code(HTCLIENT);
ui::MouseEvent move1(ui::ET_MOUSE_MOVED, point1, point1, 0, 0);
ui::EventDispatchDetails details = dispatcher->OnEventFromSource(&move1);
ASSERT_FALSE(details.dispatcher_destroyed);
EXPECT_EQ(ui::kCursorNull, dispatcher->host()->last_cursor().native_type());
}
}
#if defined(OS_WIN)
#define MAYBE_TransformActivate DISABLED_TransformActivate
#else
#define MAYBE_TransformActivate TransformActivate
#endif
TEST_F(WindowManagerTest, MAYBE_TransformActivate) {
aura::Window* root_window = Shell::GetPrimaryRootWindow();
gfx::Size size = root_window->bounds().size();
EXPECT_EQ(gfx::Rect(size).ToString(),
Shell::GetScreen()->GetDisplayNearestPoint(
gfx::Point()).bounds().ToString());
// Rotate it clock-wise 90 degrees.
gfx::Transform transform;
transform.Translate(size.width(), 0);
transform.Rotate(90.0f);
root_window->GetDispatcher()->host()->SetTransform(transform);
test::TestActivationDelegate d1;
aura::test::TestWindowDelegate wd;
scoped_ptr<aura::Window> w1(
CreateTestWindowInShellWithDelegate(&wd, 1, gfx::Rect(0, 15, 50, 50)));
d1.SetWindow(w1.get());
w1->Show();
gfx::Point miss_point(5, 5);
transform.TransformPoint(&miss_point);
ui::MouseEvent mouseev1(ui::ET_MOUSE_PRESSED,
miss_point,
miss_point,
ui::EF_LEFT_MOUSE_BUTTON,
ui::EF_LEFT_MOUSE_BUTTON);
aura::WindowEventDispatcher* dispatcher = root_window->GetDispatcher();
ui::EventDispatchDetails details = dispatcher->OnEventFromSource(&mouseev1);
ASSERT_FALSE(details.dispatcher_destroyed);
EXPECT_EQ(NULL, aura::client::GetFocusClient(w1.get())->GetFocusedWindow());
ui::MouseEvent mouseup(ui::ET_MOUSE_RELEASED,
miss_point,
miss_point,
ui::EF_LEFT_MOUSE_BUTTON,
ui::EF_LEFT_MOUSE_BUTTON);
details = dispatcher->OnEventFromSource(&mouseup);
ASSERT_FALSE(details.dispatcher_destroyed);
gfx::Point hit_point(5, 15);
transform.TransformPoint(&hit_point);
ui::MouseEvent mouseev2(ui::ET_MOUSE_PRESSED,
hit_point,
hit_point,
ui::EF_LEFT_MOUSE_BUTTON,
ui::EF_LEFT_MOUSE_BUTTON);
details = dispatcher->OnEventFromSource(&mouseev2);
ASSERT_FALSE(details.dispatcher_destroyed);
EXPECT_TRUE(wm::IsActiveWindow(w1.get()));
EXPECT_EQ(w1.get(),
aura::client::GetFocusClient(w1.get())->GetFocusedWindow());
}
TEST_F(WindowManagerTest, AdditionalFilters) {
// The IME event filter interferes with the basic key event propagation we
// attempt to do here, so we remove it.
test::ShellTestApi shell_test(Shell::GetInstance());
Shell::GetInstance()->RemovePreTargetHandler(
shell_test.input_method_event_filter());
aura::Window* root_window = Shell::GetPrimaryRootWindow();
// Creates a window and make it active
scoped_ptr<aura::Window> w1(CreateTestWindowInShell(
SK_ColorWHITE, -1, gfx::Rect(0, 0, 100, 100)));
wm::ActivateWindow(w1.get());
// Creates two addition filters
scoped_ptr<CustomEventHandler> f1(new CustomEventHandler);
scoped_ptr<CustomEventHandler> f2(new CustomEventHandler);
// Adds them to root window event filter.
views::corewm::CompoundEventFilter* env_filter =
Shell::GetInstance()->env_filter();
env_filter->AddHandler(f1.get());
env_filter->AddHandler(f2.get());
// Dispatches mouse and keyboard events.
ui::KeyEvent key_event(ui::ET_KEY_PRESSED, ui::VKEY_A, 0, false);
aura::WindowEventDispatcher* dispatcher = root_window->GetDispatcher();
ui::EventDispatchDetails details = dispatcher->OnEventFromSource(&key_event);
ASSERT_FALSE(details.dispatcher_destroyed);
ui::MouseEvent mouse_pressed(
ui::ET_MOUSE_PRESSED, gfx::Point(0, 0), gfx::Point(0, 0), 0, 0);
details = dispatcher->OnEventFromSource(&mouse_pressed);
ASSERT_FALSE(details.dispatcher_destroyed);
// Both filters should get the events.
EXPECT_EQ(1, f1->num_key_events());
EXPECT_EQ(1, f1->num_mouse_events());
EXPECT_EQ(1, f2->num_key_events());
EXPECT_EQ(1, f2->num_mouse_events());
f1->Reset();
f2->Reset();
// Makes f1 consume events.
f1->set_key_event_handling_result(ui::ER_CONSUMED);
f1->set_mouse_event_handling_result(ui::ER_CONSUMED);
// Dispatches events.
details = dispatcher->OnEventFromSource(&key_event);
ASSERT_FALSE(details.dispatcher_destroyed);
ui::MouseEvent mouse_released(
ui::ET_MOUSE_RELEASED, gfx::Point(0, 0), gfx::Point(0, 0), 0, 0);
details = dispatcher->OnEventFromSource(&mouse_released);
ASSERT_FALSE(details.dispatcher_destroyed);
// f1 should still get the events but f2 no longer gets them.
EXPECT_EQ(1, f1->num_key_events());
EXPECT_EQ(1, f1->num_mouse_events());
EXPECT_EQ(0, f2->num_key_events());
EXPECT_EQ(0, f2->num_mouse_events());
f1->Reset();
f2->Reset();
// Remove f1 from additonal filters list.
env_filter->RemoveHandler(f1.get());
// Dispatches events.
details = dispatcher->OnEventFromSource(&key_event);
ASSERT_FALSE(details.dispatcher_destroyed);
details = dispatcher->OnEventFromSource(&mouse_pressed);
ASSERT_FALSE(details.dispatcher_destroyed);
// f1 should get no events since it's out and f2 should get them.
EXPECT_EQ(0, f1->num_key_events());
EXPECT_EQ(0, f1->num_mouse_events());
EXPECT_EQ(1, f2->num_key_events());
EXPECT_EQ(1, f2->num_mouse_events());
env_filter->RemoveHandler(f2.get());
}
#if defined(OS_CHROMEOS)
// Touch visually hides the cursor on ChromeOS and Windows, but we only update
// our internal tracking of the cursor state on ChromeOS (crbug.com/333952).
TEST_F(WindowManagerTest, UpdateCursorVisibility) {
aura::test::EventGenerator& generator = GetEventGenerator();
views::corewm::CursorManager* cursor_manager =
ash::Shell::GetInstance()->cursor_manager();
generator.MoveMouseTo(gfx::Point(0, 0));
EXPECT_TRUE(cursor_manager->IsCursorVisible());
EXPECT_TRUE(cursor_manager->IsMouseEventsEnabled());
generator.PressTouch();
EXPECT_FALSE(cursor_manager->IsCursorVisible());
EXPECT_FALSE(cursor_manager->IsMouseEventsEnabled());
generator.MoveMouseTo(gfx::Point(0, 0));
EXPECT_TRUE(cursor_manager->IsCursorVisible());
EXPECT_TRUE(cursor_manager->IsMouseEventsEnabled());
generator.ReleaseTouch();
EXPECT_TRUE(cursor_manager->IsCursorVisible());
EXPECT_TRUE(cursor_manager->IsMouseEventsEnabled());
}
// ChromeOS is the only platform for which the cursor is hidden on keypress
// (crbug.com/304296).
TEST_F(WindowManagerTest, UpdateCursorVisibilityOnKeyEvent) {
aura::test::EventGenerator& generator = GetEventGenerator();
views::corewm::CursorManager* cursor_manager =
ash::Shell::GetInstance()->cursor_manager();
// Pressing a key hides the cursor but does not disable mouse events.
generator.PressKey(ui::VKEY_A, ui::EF_NONE);
EXPECT_FALSE(cursor_manager->IsCursorVisible());
EXPECT_TRUE(cursor_manager->IsMouseEventsEnabled());
// Moving mouse shows the cursor.
generator.MoveMouseTo(gfx::Point(0, 0));
EXPECT_TRUE(cursor_manager->IsCursorVisible());
EXPECT_TRUE(cursor_manager->IsMouseEventsEnabled());
// Releasing a key also hides the cursor but does not disable mouse events.
generator.ReleaseKey(ui::VKEY_A, ui::EF_NONE);
EXPECT_FALSE(cursor_manager->IsCursorVisible());
EXPECT_TRUE(cursor_manager->IsMouseEventsEnabled());
// Moving mouse shows the cursor again.
generator.MoveMouseTo(gfx::Point(0, 0));
EXPECT_TRUE(cursor_manager->IsCursorVisible());
EXPECT_TRUE(cursor_manager->IsMouseEventsEnabled());
}
TEST_F(WindowManagerTest, TestCursorClientObserver) {
aura::test::EventGenerator& generator = GetEventGenerator();
views::corewm::CursorManager* cursor_manager =
ash::Shell::GetInstance()->cursor_manager();
scoped_ptr<aura::Window> w1(CreateTestWindowInShell(
SK_ColorWHITE, -1, gfx::Rect(0, 0, 100, 100)));
wm::ActivateWindow(w1.get());
// Add two observers. Both should have OnCursorVisibilityChanged()
// invoked when an event changes the visibility of the cursor.
TestingCursorClientObserver observer_a;
TestingCursorClientObserver observer_b;
cursor_manager->AddObserver(&observer_a);
cursor_manager->AddObserver(&observer_b);
// Initial state before any events have been sent.
observer_a.reset();
observer_b.reset();
EXPECT_FALSE(observer_a.did_visibility_change());
EXPECT_FALSE(observer_b.did_visibility_change());
EXPECT_FALSE(observer_a.is_cursor_visible());
EXPECT_FALSE(observer_b.is_cursor_visible());
// Keypress should hide the cursor.
generator.PressKey(ui::VKEY_A, ui::EF_NONE);
EXPECT_TRUE(observer_a.did_visibility_change());
EXPECT_TRUE(observer_b.did_visibility_change());
EXPECT_FALSE(observer_a.is_cursor_visible());
EXPECT_FALSE(observer_b.is_cursor_visible());
// Mouse move should show the cursor.
observer_a.reset();
observer_b.reset();
generator.MoveMouseTo(50, 50);
EXPECT_TRUE(observer_a.did_visibility_change());
EXPECT_TRUE(observer_b.did_visibility_change());
EXPECT_TRUE(observer_a.is_cursor_visible());
EXPECT_TRUE(observer_b.is_cursor_visible());
// Remove observer_b. Its OnCursorVisibilityChanged() should
// not be invoked past this point.
cursor_manager->RemoveObserver(&observer_b);
// Gesture tap should hide the cursor.
observer_a.reset();
observer_b.reset();
generator.GestureTapAt(gfx::Point(25, 25));
EXPECT_TRUE(observer_a.did_visibility_change());
EXPECT_FALSE(observer_b.did_visibility_change());
EXPECT_FALSE(observer_a.is_cursor_visible());
// Mouse move should show the cursor.
observer_a.reset();
observer_b.reset();
generator.MoveMouseTo(50, 50);
EXPECT_TRUE(observer_a.did_visibility_change());
EXPECT_FALSE(observer_b.did_visibility_change());
EXPECT_TRUE(observer_a.is_cursor_visible());
}
#endif // defined(OS_CHROMEOS)
} // namespace ash
| bsd-3-clause |
fahmihdyt/propensi | views/Issue/update.php | 550 | <?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model app\models\issue */
$this->title = 'Update Issue: ' . ' ' . $model->id;
$this->params['breadcrumbs'][] = ['label' => 'Issues', 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => $model->id, 'url' => ['view', 'id' => $model->id]];
$this->params['breadcrumbs'][] = 'Update';
?>
<div class="issue-update">
<h1 style='margin-top:0px; padding-top:15px'>Update Issue</h1>
<hr>
<?= $this->render('_form', [
'model' => $model,
]) ?>
</div>
| bsd-3-clause |
cboy868/lion | modules/grave/views/admin/tomb/option.php | 10602 | <?php
use app\core\helpers\Url;
\app\assets\BootBoxAsset::register($this);
?>
<style type="text/css">
#option-box { font-size:12px;}
#option-box table tr{ margin-bottom:1em; border-bottom:1px dotted #e1e1e1; }
#option-box table td { vertical-align:middle; padding:2px 0px 3px 3px; }
#option-box table td span { background-color:#ccd8ed; border-radius:3px; padding:2px 5px; color:#666;}
#option-box table td div { width:100px; float:left; line-height:30px; }
</style>
<div class="row">
<div class="col-xs-3">
<img class="img-circle" width="64" src="<?=$tomb->getThumb('200x100', '/static/images/default.png')?>">
</div>
<div class="col-xs-9">
墓位号:<code><?=$tomb->tomb_no?></code> 价格:<code>¥<?=$tomb->price?></code> 穴数:<code><?=$tomb->hole?></code>
</div>
<div id="option-box" class="col-xs-12">
<hr />
<table>
<?php foreach($options as $key=>$opt):?>
<tr>
<td width="80px;" valign="top" style="padding-top:4px;">
<?php
switch ($key) {
case 'common':
echo '<span class="option-title">普通操作</span>';
break;
case 'operate':
echo '<span class="option-title">业务操作</span>';
break;
case 'other':
echo '<span class="option-title">其他操作</span>';
break;
case 'tombwithdraw':
echo '<span class="option-title">退墓操作</span>';
break;
case 'careful':
echo '<span class="option-title">改墓操作</span>';
break;
// ..... 其他的
}
?>
</td>
<td>
<?php foreach($opt as $item): ?>
<div>
<a class="<?php echo $item[2];?>" href="<?php echo $item[1];?>" target="_blank"><?php echo $item[0];?></a>
</div>
<?php endforeach;?>
</td>
</tr>
<?php endforeach;?>
</table>
</div>
</div>
<div id='ylw-tpl' style="display:none;">
<div id="recommand-form" class="recommand-box">
<form action="" method="post">
<textarea placeholder="操作理由" rows="5" class="form-control" name="recommand_intro"></textarea>
</div>
<div id="retain-form" class="retain-box">
<form action="" method="post">
<textarea placeholder="操作理由" rows="5" class="form-control" name="retain_intro"></textarea>
</form>
</div>
</div>
<script type="text/javascript" charset="utf-8">
$(function(){
// 操作项 - 墓位预订-------------------------------------------------
$('body').on('click', 'a.tomb-preorder', function(e){
e.preventDefault();
var url = $(this).attr('href');
$.get(url, function(xhr){
if (xhr.status) {
window.location = "<?php echo Url::toRoute(['/grave/admin/process/index', 'step'=>1, 'tomb_id'=>$tomb->id]) ?>"
} else {
//alert(xhr.info);
}
}, 'json');
return false;
});
// 操作项 - 取消预订-------------------------------------------------
$('body').on('click', 'a.tomb-unpreorder', function(e){
e.preventDefault();
var url = $(this).attr('href');
$.get(url, function(json){
if (json.status == 0) {
bootbox.dialog({
title: "错误信息",
message: json.info
})
} else {
window.location.reload();
}
}, 'json');
});
// 保留墓位操作
$('body').on('click', 'a.tomb-retain', function(e){
e.preventDefault();
var $this = $(this);
var url = $(this).attr('href');
var retainForm = $('#ylw-tpl').find('#retain-form')
.clone().removeAttr('id');
retainForm.find('textarea').attr('rel','retain-box');
retainArt = bootbox.dialog({
title: "保留该墓位",
message: retainForm.html(),
buttons:
{
"success" :
{
"label" : "<i class='icon-ok'></i> 保留",
"className" : "btn-sm btn-success",
"callback": function() {
var content = $('textarea[rel=retain-box]').val();
var datas = {
'retain_intro' : content,
'sale_status' : -1
};
$.get(url, datas, function(rs){
if (rs.status) {
$this.text('');
bootbox.dialog({
title: "保留墓位成功",
message: '<p style="font-size:1.5em" class="alert alert-success"><i class="icon-comment-alt"></i> 保留墓位成功</p>',
buttons:
{
"success" :
{
"label" : "<i class='icon-ok'></i> 结束",
"className" : "btn-sm btn-success",
"callback": function() {location.reload()}
},
}
})
}
},'json');
}
},
"button" :
{
"label" : "返回",
"className" : "btn-sm",
"callback": function() {
}
}
}
})
});
// 保留墓位操作
$('body').on('click', 'a.tomb-retain-del', function(e){
e.preventDefault();
var $this = $(this);
var url = $(this).attr('href');
var retainForm = $('#ylw-tpl').find('#retain-form')
.clone().removeAttr('id')
retainForm.find('textarea').attr('rel','retain-box');
retainArt = bootbox.dialog({
title: "取消保留",
message: retainForm.html(),
buttons:
{
"success" :
{
"label" : "<i class='icon-ok'></i> 取消保留",
"className" : "btn-sm btn-success",
"callback": function() {
var content = $('textarea[rel=retain-box]').val();
var datas = {
'retain_intro' : content,
'sale_status' : 1
};
$.get(url, datas, function(rs){
if (rs.status) {
$this.text('');
bootbox.dialog({
title: "取消保留墓位成功",
message: '<p style="font-size:1.5em" class="alert alert-success"><i class="icon-comment-alt"></i> 取消保留成功</p>',
buttons:
{
"success" :
{
"label" : "<i class='icon-ok'></i> 结束",
"className" : "btn-sm btn-success",
"callback": function() {location.reload()}
},
}
})
}
},'json');
}
},
"button" :
{
"label" : "返回",
"className" : "btn-sm",
"callback": function() {
}
}
}
})
});
// 推荐墓位操作
$('body').on('click', 'a.tomb-recommand', function(e){
e.preventDefault();
var $this = $(this);
var url = $(this).attr('href');
var recommandForm = $('#ylw-tpl').find('#recommand-form')
.clone().removeAttr('id')
recommandForm.find('textarea').attr('rel','recommand-box');
recommandArt = bootbox.dialog({
title: "推荐该墓位",
message: recommandForm.html(),
buttons:
{
"success" :
{
"label" : "<i class='icon-ok'></i> 推荐",
"className" : "btn-sm btn-success",
"callback": function() {
var content = $('textarea[rel=recommand-box]').val();
var datas = {
'recommand_intro' : content
};
$.post(url, datas, function(rs){
if (rs.info == 'ok') {
$this.attr('href', rs.data.url);
$this.attr('class', 'tomb-unrecommand');
$this.text('取消推荐');
}
},'json');
}
},
"button" :
{
"label" : "返回",
"className" : "btn-sm",
"callback": function() {
}
}
}
})
});
// 取消推荐
$('body').on('click', 'a.tomb-unrecommand', function(e){
e.preventDefault();
var $this = $(this);
var url = $this.attr('href');
$.get(url, function(rs) {
if (rs.info == 'ok') {
$this.attr('class', 'tomb-recommand');
$this.attr('href', rs.data.url);
$this.text('推荐该墓位');
}
},'json');
});
});
</script>
| bsd-3-clause |
stan-dev/math | lib/sundials_6.0.0/src/nvector/hip/VectorKernels.hip.hpp | 7402 | /*
* -----------------------------------------------------------------
* Programmer(s): Slaven Peles, Cody J. Balos @ LLNL
* -----------------------------------------------------------------
* SUNDIALS Copyright Start
* Copyright (c) 2002-2021, Lawrence Livermore National Security
* and Southern Methodist University.
* All rights reserved.
*
* See the top-level LICENSE and NOTICE files for details.
*
* SPDX-License-Identifier: BSD-3-Clause
* SUNDIALS Copyright End
* -----------------------------------------------------------------
*/
#ifndef _NVECTOR_HIP_KERNELS_HIP_HPP_
#define _NVECTOR_HIP_KERNELS_HIP_HPP_
#include <limits>
#include <hip/hip_runtime.h>
#include "sundials_hip_kernels.hip.hpp"
using namespace sundials::hip;
namespace sundials
{
namespace nvector_hip
{
/* -----------------------------------------------------------------
* The namespace for HIP kernels
*
* Reduction HIP kernels in nvector are based in part on "reduction"
* example in NVIDIA Corporation CUDA Samples, and parallel reduction
* examples in textbook by J. Cheng at al. "CUDA C Programming".
* -----------------------------------------------------------------
*/
/*
* Sets all elements of the vector X to constant value a.
*
*/
template <typename T, typename I>
__global__ void
setConstKernel(T a, T *X, I n)
{
GRID_STRIDE_XLOOP(I, i, n)
{
X[i] = a;
}
}
/*
* Computes linear sum (combination) of two vectors.
*
*/
template <typename T, typename I>
__global__ void
linearSumKernel(T a, const T *X, T b, const T *Y, T *Z, I n)
{
GRID_STRIDE_XLOOP(I, i, n)
{
Z[i] = a*X[i] + b*Y[i];
}
}
/*
* Elementwise product of two vectors.
*
*/
template <typename T, typename I>
__global__ void
prodKernel(const T *X, const T *Y, T *Z, I n)
{
GRID_STRIDE_XLOOP(I, i, n)
{
Z[i] = X[i]*Y[i];
}
}
/*
* Elementwise division of two vectors.
*
*/
template <typename T, typename I>
__global__ void
divKernel(const T *X, const T *Y, T *Z, I n)
{
GRID_STRIDE_XLOOP(I, i, n)
{
Z[i] = X[i]/Y[i];
}
}
/*
* Scale vector with scalar value 'a'.
*
*/
template <typename T, typename I>
__global__ void
scaleKernel(T a, const T *X, T *Z, I n)
{
GRID_STRIDE_XLOOP(I, i, n)
{
Z[i] = a*X[i];
}
}
/*
* Stores absolute values of vector X elements into vector Z.
*
*/
template <typename T, typename I>
__global__ void
absKernel(const T *X, T *Z, I n)
{
GRID_STRIDE_XLOOP(I, i, n)
{
Z[i] = abs(X[i]);
}
}
/*
* Elementwise inversion.
*
*/
template <typename T, typename I>
__global__ void
invKernel(const T *X, T *Z, I n)
{
GRID_STRIDE_XLOOP(I, i, n)
{
Z[i] = 1.0/(X[i]);
}
}
/*
* Add constant 'c' to each vector element.
*
*/
template <typename T, typename I>
__global__ void
addConstKernel(T a, const T *X, T *Z, I n)
{
GRID_STRIDE_XLOOP(I, i, n)
{
Z[i] = a + X[i];
}
}
/*
* Compare absolute values of vector 'X' with constant 'c'.
*
*/
template <typename T, typename I>
__global__ void
compareKernel(T c, const T *X, T *Z, I n)
{
GRID_STRIDE_XLOOP(I, i, n)
{
Z[i] = (abs(X[i]) >= c) ? 1.0 : 0.0;
}
}
/*
* Dot product of two vectors.
*
*/
template <typename T, typename I>
__global__ void
dotProdKernel(const T *x, const T *y, T *out, I n)
{
T sum = 0.0;
GRID_STRIDE_XLOOP(I, i, n)
{
sum += x[i] * y[i];
}
sum = blockReduce<T, RSUM>(sum, 0.0);
// Copy reduction result for each block to global memory
if (threadIdx.x == 0) atomicAdd(out, sum);
}
/*
* Finds max norm the vector.
*
*/
template <typename T, typename I>
__global__ void
maxNormKernel(const T *x, T *out, I n)
{
T maximum = 0.0;
GRID_STRIDE_XLOOP(I, i, n)
{
maximum = max(abs(x[i]), maximum);
}
maximum = blockReduce<T, RMAX>(maximum, 0.0);
// Maximum of reduction result for each block
if (threadIdx.x == 0) AtomicMax(out, maximum);
}
/*
* Weighted L2 norm squared.
*
*/
template <typename T, typename I>
__global__ void
wL2NormSquareKernel(const T *x, const T *w, T *out, I n)
{
T sum = 0.0;
GRID_STRIDE_XLOOP(I, i, n)
{
sum += x[i] * w[i] * x[i] * w[i];
}
sum = blockReduce<T, RSUM>(sum, 0.0);
// Copy reduction result for each block to global memory
if (threadIdx.x == 0) atomicAdd(out, sum);
}
/*
* Weighted L2 norm squared with mask. Vector id specifies the mask.
*
*/
template <typename T, typename I>
__global__ void
wL2NormSquareMaskKernel(const T *x, const T *w, const T *id, T *out, I n)
{
T sum = 0.0;
GRID_STRIDE_XLOOP(I, i, n)
{
if(id[i] > 0.0) sum += x[i] * w[i] * x[i] * w[i];
}
sum = blockReduce<T, RSUM>(sum, 0.0);
// Copy reduction result for each block to global memory
if (threadIdx.x == 0) atomicAdd(out, sum);
}
/*
* Finds min value in the vector.
*
*/
template <typename T, typename I>
__global__ void
findMinKernel(T MAX_VAL, const T *x, T *out, I n)
{
T minimum = MAX_VAL;
GRID_STRIDE_XLOOP(I, i, n)
{
minimum = min(x[i], minimum);
}
minimum = blockReduce<T, RMIN>(minimum, MAX_VAL);
// minimum of reduction result for each block
if (threadIdx.x == 0) AtomicMin(out, minimum);
}
/*
* Computes L1 norm of vector
*
*/
template <typename T, typename I>
__global__ void
L1NormKernel(const T *x, T *out, I n)
{
T sum = 0.0;
GRID_STRIDE_XLOOP(I, i, n)
{
sum += abs(x[i]);
}
sum = blockReduce<T, RSUM>(sum, 0.0);
// Copy reduction result for each block to global memory
if (threadIdx.x == 0) atomicAdd(out, sum);
}
/*
* Vector inverse z[i] = 1/x[i] with check for zeros. Reduction is performed
* to flag the result if any x[i] = 0.
*
*/
template <typename T, typename I>
__global__ void
invTestKernel(const T *x, T *z, T *out, I n)
{
T flag = 0.0;
GRID_STRIDE_XLOOP(I, i, n)
{
if (x[i] == static_cast<T>(0.0))
flag += 1.0;
else
z[i] = 1.0/x[i];
}
flag = blockReduce<T, RSUM>(flag, 0.0);
// Copy reduction result for each block to global memory
if (threadIdx.x == 0) atomicAdd(out, flag);
}
/*
* Checks if inequality constraints are satisfied. Constraint check
* results are stored in vector 'm'. A sum reduction over all elements
* of 'm' is performed to find if any of the constraints is violated.
* If all constraints are satisfied sum == 0.
*
*/
template <typename T, typename I>
__global__ void
constrMaskKernel(const T *c, const T *x, T *m, T *out, I n)
{
T sum = 0.0;
GRID_STRIDE_XLOOP(I, i, n)
{
// test = true if constraints violated
bool test = (std::abs(c[i]) > 1.5 && c[i]*x[i] <= 0.0) ||
(std::abs(c[i]) > 0.5 && c[i]*x[i] < 0.0);
m[i] = test ? 1.0 : 0.0;
sum = m[i];
}
sum = blockReduce<T, RSUM>(sum, 0.0);
// Copy reduction result for each block to global memory
if (threadIdx.x == 0) atomicAdd(out, sum);
}
/*
* Finds minimum component-wise quotient.
*
*/
template <typename T, typename I>
__global__ void
minQuotientKernel(const T MAX_VAL, const T *num, const T *den, T *min_quotient, I n)
{
T minimum = MAX_VAL;
T quotient = 0.0;
GRID_STRIDE_XLOOP(I, i, n)
{
quotient = (den[i] == static_cast<T>(0.0)) ? MAX_VAL : num[i]/den[i];
minimum = min(quotient, minimum);
}
minimum = blockReduce<T, RMIN>(minimum, MAX_VAL);
// minimum of reduction result for each block
if (threadIdx.x == 0) AtomicMin(min_quotient, minimum);
}
} // namespace nvector_hip
} // namespace sundials
#endif // _NVECTOR_HIP_KERNELS_HIP_HPP_
| bsd-3-clause |
PaulWoow/HTML5JUEGOGRAFICACION | Mini Valle PaJou/libs/easeljs/display/DisplayObject.js | 21794 | /*
* DisplayObject by Grant Skinner. Dec 5, 2010
* Visit http://easeljs.com/ for documentation, updates and examples.
*
*
* Copyright (c) 2010 Grant Skinner
*
* 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.
*/
/**
* The Easel Javascript library provides a retained graphics mode for canvas
* including a full, hierarchical display list, a core interaction model, and
* helper classes to make working with Canvas much easier.
* @module EaselJS
**/
(function(window) {
/**
* DisplayObject is an abstract class that should not be constructed directly. Instead construct subclasses such as
* Sprite, Bitmap, and Shape. DisplayObject is the base class for all display classes in the CanvasDisplay library.
* It defines the core properties and methods that are shared between all display objects.
* @class DisplayObject
* @constructor
**/
DisplayObject = function() {
this.initialize();
}
var p = DisplayObject.prototype;
/**
* Suppresses errors generated when using features like hitTest, onPress/onClick, and getObjectsUnderPoint with cross
* domain content
* @property suppressCrossDomainErrors
* @static
* @type Boolean
* @default false
**/
DisplayObject.suppressCrossDomainErrors = false;
/**
* @property _hitTestCanvas
* @type HTMLCanvasElement
* @static
* @protected
**/
DisplayObject._hitTestCanvas = document.createElement("canvas");
DisplayObject._hitTestCanvas.width = DisplayObject._hitTestCanvas.height = 1;
/**
* @property _hitTestContext
* @type CanvasRenderingContext2D
* @static
* @protected
**/
DisplayObject._hitTestContext = DisplayObject._hitTestCanvas.getContext("2d");
/**
* @property _workingMatrix
* @type Matrix2D
* @static
* @protected
**/
DisplayObject._workingMatrix = new Matrix2D();
/**
* The alpha (transparency) for this display object. 0 is fully transparent, 1 is fully opaque.
* @property alpha
* @type Number
* @default 1
**/
p.alpha = 1;
/**
* If a cache is active, this returns the canvas that holds the cached version of this display object. See cache()
* for more information. READ-ONLY.
* @property cacheCanvas
* @type HTMLCanvasElement
* @default null
**/
p.cacheCanvas = null;
/**
* Unique ID for this display object. Makes display objects easier for some uses.
* @property id
* @type Number
* @default -1
**/
p.id = -1;
/**
* Indicates whether to include this object when running Stage.getObjectsUnderPoint(). Setting this to true for
* Sprites will cause the Sprite to be returned (not its children) regardless of whether it's mouseChildren property
* is true.
* @property mouseEnabled
* @type Boolean
* @default true
**/
p.mouseEnabled = true;
/**
* An optional name for this display object. Included in toString(). Useful for debugging.
* @property name
* @type String
* @default null
**/
p.name = null;
/**
* A reference to the Sprite or Stage object that contains this display object, or null if it has not been added to
* one. READ-ONLY.
* @property parent
* @final
* @type DisplayObject
* @default null
**/
p.parent = null;
/**
* The x offset for this display object's registration point. For example, to make a 100x100px Bitmap rotate around
* it's center, you would set regX and regY to 50.
* @property regX
* @type Number
* @default 0
**/
p.regX = 0;
/**
* The y offset for this display object's registration point. For example, to make a 100x100px Bitmap rotate around
* it's center, you would set regX and regY to 50.
* @property regY
* @type Number
* @default 0
**/
p.regY = 0;
/**
* The rotation in degrees for this display object.
* @property rotation
* @type Number
* @default 0
**/
p.rotation = 0;
/**
* The factor to stretch this display object horizontally. For example, setting scaleX to 2 will stretch the display
* object to twice it's nominal width.
* @property scaleX
* @type Number
* @default 1
**/
p.scaleX = 1;
/**
* The factor to stretch this display object vertically. For example, setting scaleY to 0.5 will stretch the display
* object to half it's nominal height.
* @property scaleY
* @type Number
* @default 1
**/
p.scaleY = 1;
/**
* The factor to skew this display object horizontally.
* @property skewX
* @type Number
* @default 0
**/
p.skewX = 0;
/**
* The factor to skew this display object vertically.
* @property skewY
* @type Number
* @default 0
**/
p.skewY = 0;
/**
* A shadow object that defines the shadow to render on this display object. Set to null to remove a shadow. If
* null, this property is inherited from the parent container.
* @property shadow
* @type Shadow
* @default null
**/
p.shadow = null;
/**
* Indicates whether this display object should be rendered to the canvas and included when running
* Stage.getObjectsUnderPoint().
* @property visible
* @type Boolean
* @default true
**/
p.visible = true;
/**
* The x (horizontal) position of the display object, relative to its parent.
* @property x
* @type Number
* @default 0
**/
p.x = 0;
/** The y (vertical) position of the display object, relative to its parent.
* @property y
* @type Number
* @default 0
**/
p.y = 0;
/**
* The composite operation indicates how the pixels of this display object will be composited with the elements
* behind it. If null, this property is inherited from the parent container. For more information, read the
* <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#compositing">
* whatwg spec on compositing</a>.
* @property compositeOperation
* @type String
* @default null
**/
p.compositeOperation = null;
/**
* Indicates whether the display object should have it's x & y position rounded prior to drawing it to stage.
* This only applies if the enclosing stage has snapPixelsEnabled set to true, and the display object's composite
* transform does not include any scaling, rotation, or skewing. The snapToPixel property is true by default for
* Bitmap and BitmapSequence instances, and false for all other display objects.
* @property snapToPixel
* @type Boolean
* @default false
**/
p.snapToPixel = false;
/**
* The onPress callback is called when the user presses down on their mouse over this display object. The handler
* is passed a single param containing the corresponding MouseEvent instance. You can subscribe to the onMouseMove
* and onMouseUp callbacks of the event object to receive these events until the user releases the mouse button.
* If an onPress handler is set on a container, it will receive the event if any of its children are clicked.
* @event onPress
* @param {MouseEvent} event MouseEvent with information about the event.
**/
p.onPress = null;
/**
* The onClick callback is called when the user presses down on and then releases the mouse button over this
* display object. The handler is passed a single param containing the corresponding MouseEvent instance. If an
* onClick handler is set on a container, it will receive the event if any of its children are clicked.
* @event onClick
* @param {MouseEvent} event MouseEvent with information about the event.
**/
p.onClick = null;
/**
* The onMouseOver callback is called when the user rolls over the display object. You must enable this event using
* stage.enableMouseOver(). The handler is passed a single param containing the corresponding MouseEvent instance.
* @event onMouseOver
* @param {MouseEvent} event MouseEvent with information about the event.
**/
p.onMouseOver = null;
/**
* The onMouseOut callback is called when the user rolls off of the display object. You must enable this event using
* stage.enableMouseOver(). The handler is passed a single param containing the corresponding MouseEvent instance.
* @event onMouseOut
* @param {MouseEvent} event MouseEvent with information about the event.
**/
p.onMouseOut = null;
// private properties:
/**
* @property _cacheOffsetX
* @protected
* @type Number
* @default 0
**/
p._cacheOffsetX = 0;
/**
* @property _cacheOffsetY
* @protected
* @type Number
* @default 0
**/
p._cacheOffsetY = 0;
/**
* @property _cacheDraw
* @protected
* @type Boolean
* @default false
**/
p._cacheDraw = false;
/**
* @property _activeContext
* @protected
* @type CanvasRenderingContext2D
* @default null
**/
p._activeContext = null;
/**
* @property _restoreContext
* @protected
* @type Boolean
* @default false
**/
p._restoreContext = false;
/**
* @property _revertShadow
* @protected
* @type Boolean
* @default false
**/
p._revertShadow = false;
/**
* @property _revertX
* @protected
* @type Number
* @default 0
**/
p._revertX = 0;
/**
* @property _revertY
* @protected
* @type Number
* @default 0
**/
p._revertY = 0;
/**
* @property _revertAlpha
* @protected
* @type Number
* @default 1
**/
p._revertAlpha = 1;
// constructor:
// separated so it can be easily addressed in subclasses:
/**
* Initialization method.
* @method initialize
* @protected
*/
p.initialize = function() {
this.id = UID.get();
this.children = [];
}
// public methods:
/**
* Returns true or false indicating whether the display object would be visible if drawn to a canvas.
* This does not account for whether it would be visible within the boundaries of the stage.
* NOTE: This method is mainly for internal use, though it may be useful for advanced uses.
* @method isVisible
* @return {Boolean} Boolean indicating whether the display object would be visible if drawn to a canvas
**/
p.isVisible = function() {
return this.visible && this.alpha > 0 && this.scaleX != 0 && this.scaleY != 0;
}
/**
* Draws the display object into the specified context ignoring it's visible, alpha, shadow, and transform.
* Returns true if the draw was handled (useful for overriding functionality).
* NOTE: This method is mainly for internal use, though it may be useful for advanced uses.
* @method draw
* @param {CanvasRenderingContext2D} ctx The canvas 2D context object to draw into.
* @param {Boolean} ignoreCache Indicates whether the draw operation should ignore any current cache.
* For example, used for drawing the cache (to prevent it from simply drawing an existing cache back
* into itself).
**/
p.draw = function(ctx, ignoreCache) {
if (ignoreCache || !this.cacheCanvas) { return false; }
ctx.translate(this._cacheOffsetX, this._cacheOffsetY);
ctx.drawImage(this.cacheCanvas, 0, 0);
ctx.translate(-this._cacheOffsetX, -this._cacheOffsetY);
return true;
}
/**
* Draws the display object into a new canvas, which is then used for subsequent draws. For complex content
* that does not change frequently (ex. a Sprite with many children that do not move, or a complex vector Shape),
* this can provide for much faster rendering because the content does not need to be re-rendered each tick. The
* cached display object can be moved, rotated, faded, etc freely, however if it's content changes, you must manually
* update the cache by calling updateCache() or cache() again. You must specify the cache area via the x, y, w,
* and h parameters. This defines the rectangle that will be rendered and cached using this display object's
* coordinates. For example if you defined a Shape that drew a circle at 0, 0 with a radius of 25, you could call
* myShape.cache(-25, -25, 50, 50) to cache the full shape.
* @method cache
* @param {Number} x The x coordinate origin for the cache region.
* @param {Number} y The y coordinate origin for the cache region.
* @param {Number} width The width of the cache region.
* @param {Number} height The height of the cache region.
**/
p.cache = function(x, y, width, height) {
// draw to canvas.
var ctx;
if (this.cacheCanvas == null) { this.cacheCanvas = document.createElement("canvas"); }
ctx = this.cacheCanvas.getContext("2d");
this.cacheCanvas.width = width;
this.cacheCanvas.height = height;
ctx.setTransform(1, 0, 0, 1, -x, -y);
ctx.clearRect(0, 0, width+1, height+1); // because some browsers don't correctly clear if the width/height
//remain the same.
this.draw(ctx, true);
this._cacheOffsetX = x;
this._cacheOffsetY = y;
}
/**
* Redraws the display object to its cache. Calling updateCache without an active cache will throw an error.
* If compositeOperation is null the current cache will be cleared prior to drawing. Otherwise the display object
* will be drawn over the existing cache using the specified compositeOperation.
* @method updateCache
* @param {String} compositeOperation The compositeOperation to use, or null to clear the cache and redraw it.
* <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#compositing">
* whatwg spec on compositing</a>.
**/
p.updateCache = function(compositeOperation) {
if (this.cacheCanvas == null) { throw "cache() must be called before updateCache()"; }
var ctx = this.cacheCanvas.getContext("2d");
ctx.setTransform(1, 0, 0, 1, -this._cacheOffsetX, -this._cacheOffsetY);
if (!compositeOperation) { ctx.clearRect(0, 0, this.cacheCanvas.width+1, this.cacheCanvas.height+1); }
else { ctx.globalCompositeOperation = compositeOperation; }
this.draw(ctx, true);
if (compositeOperation) { ctx.globalCompositeOperation = "source-over"; }
}
/**
* Clears the current cache. See cache() for more information.
* @method uncache
**/
p.uncache = function() {
this.cacheCanvas = null;
this.cacheOffsetX = this.cacheOffsetY = 0;
}
/**
* Returns the stage that this display object will be rendered on, or null if it has not been added to one.
* @method getStage
* @return {Stage} The Stage instance that the display object is a descendent of. null if the DisplayObject has not
* been added to a Stage.
**/
p.getStage = function() {
var o = this;
while (o.parent) {
o = o.parent;
}
if (o instanceof Stage) { return o; }
return null;
}
/**
* Transforms the specified x and y position from the coordinate space of the display object
* to the global (stage) coordinate space. For example, this could be used to position an HTML label
* over a specific point on a nested display object. Returns a Point instance with x and y properties
* correlating to the transformed coordinates on the stage.
* @method localToGlobal
* @param {Number} x The x position in the source display object to transform.
* @param {Number} y The y position in the source display object to transform.
* @return {Point} A Point instance with x and y properties correlating to the transformed coordinates
* on the stage.
**/
p.localToGlobal = function(x, y) {
var mtx = this.getConcatenatedMatrix();
if (mtx == null) { return null; }
mtx.append(1, 0, 0, 1, x, y);
return new Point(mtx.tx, mtx.ty);
}
/**
* Transforms the specified x and y position from the global (stage) coordinate space to the
* coordinate space of the display object. For example, this could be used to determine
* the current mouse position within the display object. Returns a Point instance with x and y properties
* correlating to the transformed position in the display object's coordinate space.
* @method globalToLocal
* @param {Number} x The x position on the stage to transform.
* @param {Number} y The y position on the stage to transform.
* @return {Point} A Point instance with x and y properties correlating to the transformed position in the
* display object's coordinate space.
**/
p.globalToLocal = function(x, y) {
var mtx = this.getConcatenatedMatrix();
if (mtx == null) { return null; }
mtx.invert();
mtx.append(1, 0, 0, 1, x, y);
return new Point(mtx.tx, mtx.ty);
}
/**
* Transforms the specified x and y position from the coordinate space of this display object to the
* coordinate space of the target display object. Returns a Point instance with x and y properties
* correlating to the transformed position in the target's coordinate space. Effectively the same as calling
* var pt = this.localToGlobal(x, y); pt = target.globalToLocal(pt.x, pt.y);
* @method localToLocal
* @param {Number} x The x position in the source display object to transform.
* @param {Number} y The y position on the stage to transform.
* @param {DisplayObject} target The target display object to which the coordinates will be transformed.
* @return {Point} Returns a Point instance with x and y properties correlating to the transformed position
* in the target's coordinate space.
**/
p.localToLocal = function(x, y, target) {
var pt = this.localToGlobal(x, y);
return target.globalToLocal(pt.x, pt.y);
}
/**
* Generates a concatenated Matrix2D object representing the combined transform of
* the display object and all of its parent Containers up to the highest level ancestor
* (usually the stage). This can be used to transform positions between coordinate spaces,
* such as with localToGlobal and globalToLocal.
* @method getConcatenatedMatrix
* @param {Matrix2D} mtx Optional. A Matrix2D object to populate with the calculated values. If null, a new
* Matrix object is returned.
* @return {Matrix2D} a concatenated Matrix2D object representing the combined transform of
* the display object and all of its parent Containers up to the highest level ancestor (usually the stage).
**/
p.getConcatenatedMatrix = function(mtx) {
if (mtx) { mtx.identity(); }
else { mtx = new Matrix2D(); }
var target = this;
while (target != null) {
mtx.prependTransform(target.x, target.y, target.scaleX, target.scaleY, target.rotation, target.skewX,
target.skewY, target.regX, target.regY);
mtx.prependProperties(target.alpha, target.shadow, target.compositeOperation);
target = target.parent;
}
return mtx;
}
/**
* Tests whether the display object intersects the specified local point (ie. draws a pixel with alpha > 0 at
* the specified position). This ignores the alpha, shadow and compositeOperation of the display object, and all
* transform properties including regX/Y.
* @method hitTest
* @param {Number} x The x position to check in the display object's local coordinates.
* @param {Number} y The y position to check in the display object's local coordinates.
* @return {Boolean} A Boolean indicting whether a visible portion of the DisplayObject intersect the specified
* local Point.
*/
p.hitTest = function(x, y) {
var ctx = DisplayObject._hitTestContext;
var canvas = DisplayObject._hitTestCanvas;
ctx.setTransform(1, 0, 0, 1, -x, -y);
this.draw(ctx);
var hit = this._testHit(ctx);
canvas.width = 0;
canvas.width = 1;
return hit;
}
/**
* Returns a clone of this DisplayObject. Some properties that are specific to this instance's current context are
* reverted to their defaults (for example .parent).
* @method clone
@return {DisplayObject} A clone of the current DisplayObject instance.
**/
p.clone = function() {
var o = new DisplayObject();
this.cloneProps(o);
return o;
}
/**
* Returns a string representation of this object.
* @method toString
* @return {String} a string representation of the instance.
**/
p.toString = function() {
return "[DisplayObject (name="+ this.name +")]";
}
// private methods:
// separated so it can be used more easily in subclasses:
/**
* @method cloneProps
* @protected
* @param {DisplayObject} o The DisplayObject instance which will have properties from the current DisplayObject
* instance copied into.
**/
p.cloneProps = function(o) {
o.alpha = this.alpha;
o.name = this.name;
o.regX = this.regX;
o.regY = this.regY;
o.rotation = this.rotation;
o.scaleX = this.scaleX;
o.scaleY = this.scaleY;
o.shadow = this.shadow;
o.skewX = this.skewX;
o.skewY = this.skewY;
o.visible = this.visible;
o.x = this.x;
o.y = this.y;
o.mouseEnabled = this.mouseEnabled;
o.compositeOperation = this.compositeOperation;
}
/**
* @method applyShadow
* @protected
* @param {CanvasRenderingContext2D} ctx
* @param {Shadow} shadow
**/
p.applyShadow = function(ctx, shadow) {
shadow = shadow || Shadow.identity;
ctx.shadowColor = shadow.color;
ctx.shadowOffsetX = shadow.offsetX;
ctx.shadowOffsetY = shadow.offsetY;
ctx.shadowBlur = shadow.blur;
}
/**
* @method _testHit
* @protected
* @param {CanvasRenderingContext2D} ctx
* @return {Boolean}
**/
p._testHit = function(ctx) {
try {
var hit = ctx.getImageData(0, 0, 1, 1).data[3] > 1;
} catch (e) {
if (!DisplayObject.suppressCrossDomainErrors) {
throw "An error has occured. This is most likely due to security restrictions on reading canvas pixel " +
"data with local or cross-domain images.";
}
}
return hit;
}
window.DisplayObject = DisplayObject;
}(window)); | bsd-3-clause |
keithhamilton/features-commits-prs | keeping-your-features-separate.md | 35 | #keeping-your-features-separate
TBD | bsd-3-clause |
ndexbio/ndex-object-model | src/main/java/org/ndexbio/cxio/core/interfaces/INiceCXNetworkReader.java | 1040 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.ndexbio.cxio.core.interfaces;
import java.io.InputStream;
import org.ndexbio.model.cx.NiceCXNetwork;
import org.ndexbio.model.exceptions.NdexException;
/**
* Implementing interfaces support generating {@link org.ndexbio.model.cx.NiceCXNetwork}
* objects from an {@link java.io.InputStream}
* @author churas
*/
public interface INiceCXNetworkReader {
/**
* Reads {@code in} and generates {@link org.ndexbio.model.cx.NiceCXNetwork}
* object
* @param in {@link java.io.InputStream} to extract the {@link org.ndexbio.model.cx.NiceCXNetwork} from
* @return {@link org.ndexbio.model.cx.NiceCXNetwork} object representing data from {@code in}
* @throws NdexException If there was a problem parsing the input.
*/
public NiceCXNetwork readNiceCXNetwork(final InputStream in) throws NdexException;
}
| bsd-3-clause |
magdielikari/HidroLab-Manager | backend/modules/admin/views/roles/create.php | 901 | <?php
use yii\helpers\Html;
use yii\helpers\ArrayHelper;
$this->title = Yii::t('app', 'Create Role');
$this->params['breadcrumbs'][] = ['label'=>Yii::t('app', 'Admin'), 'url'=>['index']];
$this->params['breadcrumbs'][] = ['label'=>Yii::t('app', 'Roles'), 'url'=>['roles/index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<?= Html::beginForm('', 'POST') ?>
<div class="form-group">
<?= Html::label(Yii::t('app', 'Role Name'), null, ['class'=>'control-label']) ?>
<?= Html::input('text', 'role[name]', null, ['class'=>'form-control']) ?>
</div>
<div class="form-group">
<?= Html::label(Yii::t('app', 'Role Description'), null, ['class'=>'control-label']) ?>
<?= Html::input('text', 'role[description]', null, ['class'=>'form-control']) ?>
</div>
<div class="form-group">
<?= Html::submitButton(Yii::t('app', 'Create'), ['class'=>'btn btn-success']) ?>
</div>
<?= Html::endForm() ?>
| bsd-3-clause |
sabey/transmission | torrent_add.go | 2493 | package transmission
// Copyright 2015, JuanDeFu.ca. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
import (
"encoding/json"
"fmt"
"log"
"strings"
)
/*
Method name
torrent-add
*/
/*
Either "filename" OR "metainfo" MUST be included.
*/
/*
Response arguments:
On success, a "torrent-added" object contains
id, name, and hashString.
On failure due to a duplicate torrent existing,
a "torrent-duplicate" object in the same form.
*/
type Add_Argument struct {
Cookies string `json:"cookies,omitempty"`
DownloadDir string `json:"download-dir,omitempty"`
Filename string `json:"filename,omitempty"`
MetaInfo string `json:"metainfo,omitempty"`
Paused bool `json:"paused,omitempty"`
PeerLimit int `json:"peer-limit,omitempty"`
BandwidthPriority int `json:"bandwidthPriority,omitempty"`
FilesWanted []*File `json:"files-wanted,omitempty"`
FilesUnwanted []*File `json:"files-unwanted,omitempty"`
PriorityHigh []*File `json:"priority-high,omitempty"`
PriorityLow []*File `json:"priority-low,omitempty"`
PriorityNormal []*File `json:"priority-normal,omitempty"`
}
type Add_Response struct {
Torrent *Torrent `json:"torrent-added,omitempty"`
}
func (self *Client) AddTorrent(
location string,
path string,
) (
*Torrent,
error,
) {
if location == "" {
return nil, fmt.Errorf("Transmission.AddTorrent(): location empty")
}
if path == "" {
return nil, fmt.Errorf("Transmission.AddTorrent(): path empty")
}
if !strings.HasPrefix(path, "/") {
return nil, fmt.Errorf("Transmission.AddTorrent(): path doesn't start with /")
}
request := &Request{}
request.Method = "torrent-add"
access := Add_Argument{}
access.Filename = location
access.DownloadDir = path
request.Args = access
var result *Response
var err error
for i := 0; i < 5; i++ {
if result, err = self.Request(request); err == nil && result != nil {
if result.Result == "success" {
torrent := Add_Response{}
if err2 := json.Unmarshal(result.Args, &torrent); err2 != nil {
log.Printf("Transmission.AddTorrent(): failed to unmarshal %s | raw: %v\n", err2, result.Args)
} else {
return torrent.Torrent, nil
}
} else {
return nil, fmt.Errorf("Transmission.AddTorrent(): failed to add: %s", result.Result)
}
}
}
return nil, fmt.Errorf("Transmission.AddTorrent(): failed to get torrents: %s", err)
}
| bsd-3-clause |
nhibberd/search | src/main/data/core/Function.java | 79 | package main.data.core;
public interface Function<A, B> {
B apply(A a);
}
| bsd-3-clause |
SaratogaMSET/649code2014 | src/com/team649/frc2014/subsystems/ClawRollerSubsystem.java | 1047 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.team649.frc2014.subsystems;
import com.team649.frc2014.RobotMap;
import edu.wpi.first.wpilibj.SpeedController;
import edu.wpi.first.wpilibj.Victor;
import edu.wpi.first.wpilibj.command.Subsystem;
/**
*
* @author Kabi
*/
public class ClawRollerSubsystem extends Subsystem {
private final SpeedController motor;
public static final double ROLLER_SPIN_SHOOT_SPEED = 1;
public static final double ROLLER_SPIN_INTAKE_SPEED = -.4;
public static final double ROLLER_SPIN_PURGE_SPEED = .4;
public static final double ROLLER_SPIN_OFF_SPEED = 0;
public static final double ROLLER_SPIN_REALIGN_SPEED = -.2;
public ClawRollerSubsystem() {
motor = new Victor(RobotMap.CLAW_ROLLER.MOTOR);
}
protected void initDefaultCommand() {
}
public void runMotor(double speed) {
motor.set(speed);
}
}
| bsd-3-clause |
wayfinder/Wayfinder-CppCore-v2 | docs/MapLibAPI/OverlayInterface_8h-source.html | 9038 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
<title>MapLibAPI: OverlayInterface.h Source File</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">
</head><body>
<!-- Generated by Doxygen 1.4.7 -->
<div class="tabs">
<ul>
<li><a href="main.html"><span>Main Page</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li><a href="annotated.html"><span>Classes</span></a></li>
<li id="current"><a href="files.html"><span>Files</span></a></li>
</ul></div>
<h1>OverlayInterface.h</h1><div class="fragment"><pre class="fragment"><a name="l00001"></a>00001 <span class="comment">/*</span>
<a name="l00002"></a>00002 <span class="comment"> Copyright (c) 1999 - 2010, Vodafone Group Services Ltd</span>
<a name="l00003"></a>00003 <span class="comment"> All rights reserved.</span>
<a name="l00004"></a>00004 <span class="comment"></span>
<a name="l00005"></a>00005 <span class="comment"> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:</span>
<a name="l00006"></a>00006 <span class="comment"></span>
<a name="l00007"></a>00007 <span class="comment"> * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.</span>
<a name="l00008"></a>00008 <span class="comment"> * 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.</span>
<a name="l00009"></a>00009 <span class="comment"> * Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.</span>
<a name="l00010"></a>00010 <span class="comment"></span>
<a name="l00011"></a>00011 <span class="comment"> THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.</span>
<a name="l00012"></a>00012 <span class="comment">*/</span>
<a name="l00013"></a>00013
<a name="l00014"></a>00014 <span class="preprocessor">#ifndef WFAPI_OVERLAYINTERFACE_H</span>
<a name="l00015"></a>00015 <span class="preprocessor"></span><span class="preprocessor">#define WFAPI_OVERLAYINTERFACE_H </span>
<a name="l00016"></a>00016 <span class="preprocessor"></span>
<a name="l00017"></a>00017 <span class="preprocessor">#include "PALMachineTypes.h"</span>
<a name="l00018"></a>00018 <span class="preprocessor">#include "OverlayItem.h"</span>
<a name="l00019"></a>00019
<a name="l00020"></a>00020 <span class="keyword">class </span>MapLib;
<a name="l00021"></a>00021
<a name="l00022"></a>00022 <span class="keyword">namespace </span>WFAPI {
<a name="l00023"></a>00023
<a name="l00024"></a>00024 <span class="keyword">class </span>ImageSpec;
<a name="l00025"></a>00025 <span class="keyword">class </span>OverlayItemZoomSpec;
<a name="l00026"></a>00026 <span class="keyword">class </span>OverlayPos;
<a name="l00027"></a>00027
<a name="l00038"></a><a class="code" href="classWFAPI_1_1OverlayInterface.html">00038</a> <span class="keyword">class </span><a class="code" href="classWFAPI_1_1OverlayInterface.html">OverlayInterface</a> {
<a name="l00039"></a>00039 <span class="keyword">public</span>:
<a name="l00043"></a>00043 <a class="code" href="classWFAPI_1_1OverlayInterface.html#30445ed0b3dde33243010d84cdbc0592">OverlayInterface</a>();
<a name="l00044"></a>00044
<a name="l00048"></a>00048 <span class="keyword">virtual</span> <a class="code" href="classWFAPI_1_1OverlayInterface.html#9c749d44e9247450ce20fc1ae90c329c">~OverlayInterface</a>();
<a name="l00049"></a>00049
<a name="l00053"></a><a class="code" href="classWFAPI_1_1OverlayInterface.html#30284b5a73507c686b57edc55f4658ea">00053</a> <span class="keyword">typedef</span> wf_uint32 <a class="code" href="classWFAPI_1_1OverlayInterface.html#30284b5a73507c686b57edc55f4658ea">layer_id_t</a>;
<a name="l00054"></a>00054
<a name="l00067"></a>00067 <span class="keyword">virtual</span> <span class="keywordtype">bool</span> <a class="code" href="classWFAPI_1_1OverlayInterface.html#33a98f5575251f01fb049caaa717fc1d">addOverlayItem</a>(<a class="code" href="classWFAPI_1_1OverlayItem.html">OverlayItem</a>* overlayItem,
<a name="l00068"></a>00068 <a class="code" href="classWFAPI_1_1OverlayInterface.html#30284b5a73507c686b57edc55f4658ea">layer_id_t</a> layerID) = 0;
<a name="l00069"></a>00069
<a name="l00083"></a>00083 <span class="keyword">virtual</span> <span class="keywordtype">bool</span> <a class="code" href="classWFAPI_1_1OverlayInterface.html#3ba1ad8ab571a5482c7ad3d5ad545d33">addOverlayItems</a>(<span class="keyword">const</span> <a class="code" href="namespaceWFAPI.html#90d906884de7e668717d129fd1febbff">OverlayItemVector</a>& overlayItems,
<a name="l00084"></a>00084 <a class="code" href="classWFAPI_1_1OverlayInterface.html#30284b5a73507c686b57edc55f4658ea">layer_id_t</a> layerID) = 0;
<a name="l00085"></a>00085
<a name="l00094"></a>00094 <span class="keyword">virtual</span> <span class="keywordtype">bool</span> <a class="code" href="classWFAPI_1_1OverlayInterface.html#b49ab2656e17445f62774ff12962b407">removeOverlayItem</a>(<a class="code" href="classWFAPI_1_1OverlayItem.html">OverlayItem</a>* overlayItem,
<a name="l00095"></a>00095 <a class="code" href="classWFAPI_1_1OverlayInterface.html#30284b5a73507c686b57edc55f4658ea">layer_id_t</a> layerID) = 0;
<a name="l00096"></a>00096
<a name="l00102"></a>00102 <span class="keyword">virtual</span> <span class="keywordtype">void</span> <a class="code" href="classWFAPI_1_1OverlayInterface.html#e5422d4a0885ff64bfaf3a9d20fcc0e0">clearLayer</a>(<a class="code" href="classWFAPI_1_1OverlayInterface.html#30284b5a73507c686b57edc55f4658ea">layer_id_t</a> layerID) = 0;
<a name="l00103"></a>00103
<a name="l00109"></a>00109 <span class="keyword">virtual</span> <span class="keywordtype">void</span> <a class="code" href="classWFAPI_1_1OverlayInterface.html#aa551811cd3a415439144f0ff081ad4b">hideLayer</a>(<a class="code" href="classWFAPI_1_1OverlayInterface.html#30284b5a73507c686b57edc55f4658ea">layer_id_t</a> layerID) = 0;
<a name="l00110"></a>00110
<a name="l00116"></a>00116 <span class="keyword">virtual</span> <span class="keywordtype">void</span> <a class="code" href="classWFAPI_1_1OverlayInterface.html#f7a35ae570cb580cb9d383bde5bc1015">showLayer</a>(<a class="code" href="classWFAPI_1_1OverlayInterface.html#30284b5a73507c686b57edc55f4658ea">layer_id_t</a> layerID) = 0;
<a name="l00117"></a>00117
<a name="l00124"></a>00124 <span class="keyword">virtual</span> <span class="keywordtype">bool</span> <a class="code" href="classWFAPI_1_1OverlayInterface.html#523cbbf6be2c079ae322819ef830428e">getLayerVisible</a>(<a class="code" href="classWFAPI_1_1OverlayInterface.html#30284b5a73507c686b57edc55f4658ea">layer_id_t</a> layerID) <span class="keyword">const </span>= 0;
<a name="l00125"></a>00125
<a name="l00132"></a>00132 <span class="keyword">virtual</span> <span class="keyword">const</span> <a class="code" href="classWFAPI_1_1OverlayItem.html">OverlayItem</a>* <a class="code" href="classWFAPI_1_1OverlayInterface.html#aa519511c90bcf9a3548e5a731125e48">getCurrentHighlightedItem</a>() = 0;
<a name="l00133"></a>00133
<a name="l00134"></a>00134 <span class="keyword">private</span>:
<a name="l00135"></a>00135 <span class="keyword">struct </span>Impl;
<a name="l00136"></a>00136 Impl* m_impl;
<a name="l00137"></a>00137 };
<a name="l00138"></a>00138
<a name="l00139"></a>00139 } <span class="comment">// End of namespace WFAPI</span>
<a name="l00140"></a>00140
<a name="l00141"></a>00141 <span class="preprocessor">#endif // WFAPI_OVERLAY_INTERFACE_H </span>
</pre></div><hr size="1"><address style="align: right;"><small>Generated on Mon Jun 28 20:51:50 2010 for MapLibAPI by
<a href="http://www.doxygen.org/index.html">
<img src="doxygen.png" alt="doxygen" align="middle" border="0"></a> 1.4.7 </small></address>
</body>
</html>
| bsd-3-clause |
ehoch/spree_grid_faq | lib/spree_grid_faq/engine.rb | 486 | module SpreeGridFaq
class Engine < Rails::Engine
engine_name 'spree_grid_faq'
config.autoload_paths += %W(#{config.root}/lib)
# use rspec for tests
config.generators do |g|
g.test_framework :rspec
end
def self.activate
Dir.glob(File.join(File.dirname(__FILE__), '../../app/**/*_decorator*.rb')) do |c|
Rails.configuration.cache_classes ? require(c) : load(c)
end
end
config.to_prepare &method(:activate).to_proc
end
end
| bsd-3-clause |
LeonidLyalin/vova | common/humhub/protected/humhub/modules/search/messages/pt/base.php | 51 | <?php
return array (
'Search' => 'Pesquisar',
);
| bsd-3-clause |
genome-vendor/apollo | javadoc/apollo/gui/detailviewers/sequencealigner/HorizontalScrollBarAdjustmentListener.html | 10958 | <!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.5.0_18) on Tue Jul 07 10:40:59 PDT 2009 -->
<TITLE>
HorizontalScrollBarAdjustmentListener
</TITLE>
<META NAME="keywords" CONTENT="apollo.gui.detailviewers.sequencealigner.HorizontalScrollBarAdjustmentListener class">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
parent.document.title="HorizontalScrollBarAdjustmentListener";
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<!-- ========= 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> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../apollo/gui/detailviewers/sequencealigner/GoToDialog.html" title="class in apollo.gui.detailviewers.sequencealigner"><B>PREV CLASS</B></A>
<A HREF="../../../../apollo/gui/detailviewers/sequencealigner/MultiSequenceAlignerFrame.html" title="class in apollo.gui.detailviewers.sequencealigner"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?apollo/gui/detailviewers/sequencealigner/HorizontalScrollBarAdjustmentListener.html" target="_top"><B>FRAMES</B></A>
<A HREF="HorizontalScrollBarAdjustmentListener.html" target="_top"><B>NO FRAMES</B></A>
<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>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<!-- ======== START OF CLASS DATA ======== -->
<H2>
<FONT SIZE="-1">
apollo.gui.detailviewers.sequencealigner</FONT>
<BR>
Class HorizontalScrollBarAdjustmentListener</H2>
<PRE>
java.lang.Object
<IMG SRC="../../../../resources/inherit.gif" ALT="extended by "><B>apollo.gui.detailviewers.sequencealigner.HorizontalScrollBarAdjustmentListener</B>
</PRE>
<DL>
<DT><B>All Implemented Interfaces:</B> <DD>java.awt.event.AdjustmentListener, java.util.EventListener</DD>
</DL>
<HR>
<DL>
<DT><PRE>public class <B>HorizontalScrollBarAdjustmentListener</B><DT>extends java.lang.Object<DT>implements java.awt.event.AdjustmentListener</DL>
</PRE>
<P>
<HR>
<P>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<A NAME="constructor_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Constructor Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../apollo/gui/detailviewers/sequencealigner/HorizontalScrollBarAdjustmentListener.html#HorizontalScrollBarAdjustmentListener(javax.swing.JViewport)">HorizontalScrollBarAdjustmentListener</A></B>(javax.swing.JViewport viewport)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<!-- ========== METHOD SUMMARY =========== -->
<A NAME="method_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../apollo/gui/detailviewers/sequencealigner/HorizontalScrollBarAdjustmentListener.html#adjustmentValueChanged(java.awt.event.AdjustmentEvent)">adjustmentValueChanged</A></B>(java.awt.event.AdjustmentEvent e)</CODE>
<BR>
assumes that the scrollbar adjustment values have the same bounds
as the number of pixels in the component in the viewport</TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD>
</TR>
</TABLE>
<P>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<A NAME="constructor_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Constructor Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="HorizontalScrollBarAdjustmentListener(javax.swing.JViewport)"><!-- --></A><H3>
HorizontalScrollBarAdjustmentListener</H3>
<PRE>
public <B>HorizontalScrollBarAdjustmentListener</B>(javax.swing.JViewport viewport)</PRE>
<DL>
</DL>
<!-- ============ METHOD DETAIL ========== -->
<A NAME="method_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Method Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="adjustmentValueChanged(java.awt.event.AdjustmentEvent)"><!-- --></A><H3>
adjustmentValueChanged</H3>
<PRE>
public void <B>adjustmentValueChanged</B>(java.awt.event.AdjustmentEvent e)</PRE>
<DL>
<DD>assumes that the scrollbar adjustment values have the same bounds
as the number of pixels in the component in the viewport
<P>
<DD><DL>
<DT><B>Specified by:</B><DD><CODE>adjustmentValueChanged</CODE> in interface <CODE>java.awt.event.AdjustmentListener</CODE></DL>
</DD>
<DD><DL>
</DL>
</DD>
</DL>
<!-- ========= END OF CLASS DATA ========= -->
<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> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../apollo/gui/detailviewers/sequencealigner/GoToDialog.html" title="class in apollo.gui.detailviewers.sequencealigner"><B>PREV CLASS</B></A>
<A HREF="../../../../apollo/gui/detailviewers/sequencealigner/MultiSequenceAlignerFrame.html" title="class in apollo.gui.detailviewers.sequencealigner"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?apollo/gui/detailviewers/sequencealigner/HorizontalScrollBarAdjustmentListener.html" target="_top"><B>FRAMES</B></A>
<A HREF="HorizontalScrollBarAdjustmentListener.html" target="_top"><B>NO FRAMES</B></A>
<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>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
</BODY>
</HTML>
| bsd-3-clause |
ExLibrisGroup/Rosetta.dps-sdk-projects | 5.4.0/javadoc/com/exlibris/digitool/common/dnx/DNXConstants.OBJECTIDENTIFIER.html | 9262 | <!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_45) on Mon Jan 01 12:59:09 IST 2018 -->
<title>DNXConstants.OBJECTIDENTIFIER</title>
<meta name="date" content="2018-01-01">
<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="DNXConstants.OBJECTIDENTIFIER";
}
}
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="navBarCell1Rev">Class</li>
<li><a href="package-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><a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.OBJECTCHARACTERISTICSEXTENSION.html" title="interface in com.exlibris.digitool.common.dnx"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.PRESERVATIONLEVEL.html" title="interface in com.exlibris.digitool.common.dnx"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/exlibris/digitool/common/dnx/DNXConstants.OBJECTIDENTIFIER.html" target="_top">Frames</a></li>
<li><a href="DNXConstants.OBJECTIDENTIFIER.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>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field.summary">Field</a> | </li>
<li>Constr | </li>
<li>Method</li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field.detail">Field</a> | </li>
<li>Constr | </li>
<li>Method</li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">com.exlibris.digitool.common.dnx</div>
<h2 title="Interface DNXConstants.OBJECTIDENTIFIER" class="title">Interface DNXConstants.OBJECTIDENTIFIER</h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>Enclosing class:</dt>
<dd><a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.html" title="class in com.exlibris.digitool.common.dnx">DNXConstants</a></dd>
</dl>
<hr>
<br>
<pre>public static interface <span class="typeNameLabel">DNXConstants.OBJECTIDENTIFIER</span></pre>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field.summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation">
<caption><span>Fields</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.SectionKey.html" title="class in com.exlibris.digitool.common.dnx">DNXConstants.SectionKey</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.OBJECTIDENTIFIER.html#OBJECTIDENTIFIERTYPE">OBJECTIDENTIFIERTYPE</a></span></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static <a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.SectionKey.html" title="class in com.exlibris.digitool.common.dnx">DNXConstants.SectionKey</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.OBJECTIDENTIFIER.html#OBJECTIDENTIFIERVALUE">OBJECTIDENTIFIERVALUE</a></span></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.OBJECTIDENTIFIER.html#sectionId">sectionId</a></span></code> </td>
</tr>
</table>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ FIELD DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="field.detail">
<!-- -->
</a>
<h3>Field Detail</h3>
<a name="sectionId">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>sectionId</h4>
<pre>static final java.lang.String sectionId</pre>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="../../../../../constant-values.html#com.exlibris.digitool.common.dnx.DNXConstants.OBJECTIDENTIFIER.sectionId">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="OBJECTIDENTIFIERTYPE">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>OBJECTIDENTIFIERTYPE</h4>
<pre>static final <a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.SectionKey.html" title="class in com.exlibris.digitool.common.dnx">DNXConstants.SectionKey</a> OBJECTIDENTIFIERTYPE</pre>
</li>
</ul>
<a name="OBJECTIDENTIFIERVALUE">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>OBJECTIDENTIFIERVALUE</h4>
<pre>static final <a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.SectionKey.html" title="class in com.exlibris.digitool.common.dnx">DNXConstants.SectionKey</a> OBJECTIDENTIFIERVALUE</pre>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= 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="navBarCell1Rev">Class</li>
<li><a href="package-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><a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.OBJECTCHARACTERISTICSEXTENSION.html" title="interface in com.exlibris.digitool.common.dnx"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.PRESERVATIONLEVEL.html" title="interface in com.exlibris.digitool.common.dnx"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/exlibris/digitool/common/dnx/DNXConstants.OBJECTIDENTIFIER.html" target="_top">Frames</a></li>
<li><a href="DNXConstants.OBJECTIDENTIFIER.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>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field.summary">Field</a> | </li>
<li>Constr | </li>
<li>Method</li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field.detail">Field</a> | </li>
<li>Constr | </li>
<li>Method</li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| bsd-3-clause |
Ehryk/MNLicenseCheck | run.sh | 20 | node LicenseCheck.js | bsd-3-clause |
danakj/chromium | ash/common/system/ime/tray_ime_chromeos.cc | 9556 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/common/system/ime/tray_ime_chromeos.h"
#include <vector>
#include "ash/common/session/session_state_delegate.h"
#include "ash/common/system/chromeos/ime_menu/ime_list_view.h"
#include "ash/common/system/tray/hover_highlight_view.h"
#include "ash/common/system/tray/system_tray.h"
#include "ash/common/system/tray/system_tray_delegate.h"
#include "ash/common/system/tray/system_tray_notifier.h"
#include "ash/common/system/tray/tray_constants.h"
#include "ash/common/system/tray/tray_details_view.h"
#include "ash/common/system/tray/tray_item_more.h"
#include "ash/common/system/tray/tray_item_view.h"
#include "ash/common/system/tray/tray_utils.h"
#include "ash/common/system/tray_accessibility.h"
#include "ash/common/wm_shell.h"
#include "base/logging.h"
#include "base/strings/utf_string_conversions.h"
#include "grit/ash_resources.h"
#include "grit/ash_strings.h"
#include "ui/accessibility/ax_enums.h"
#include "ui/accessibility/ax_view_state.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/font.h"
#include "ui/gfx/image/image.h"
#include "ui/keyboard/keyboard_util.h"
#include "ui/views/controls/label.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/widget/widget.h"
namespace ash {
namespace tray {
// A |HoverHighlightView| that uses bold or normal font depending on whether
// it is selected. This view exposes itself as a checkbox to the accessibility
// framework.
class SelectableHoverHighlightView : public HoverHighlightView {
public:
SelectableHoverHighlightView(ViewClickListener* listener,
const base::string16& label,
bool selected)
: HoverHighlightView(listener), selected_(selected) {
AddLabel(label, gfx::ALIGN_LEFT, selected);
}
~SelectableHoverHighlightView() override {}
protected:
// Overridden from views::View.
void GetAccessibleState(ui::AXViewState* state) override {
HoverHighlightView::GetAccessibleState(state);
state->role = ui::AX_ROLE_CHECK_BOX;
if (selected_)
state->AddStateFlag(ui::AX_STATE_CHECKED);
}
private:
bool selected_;
DISALLOW_COPY_AND_ASSIGN(SelectableHoverHighlightView);
};
class IMEDefaultView : public TrayItemMore {
public:
explicit IMEDefaultView(SystemTrayItem* owner, const base::string16& label)
: TrayItemMore(owner, true) {
ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();
SetImage(bundle.GetImageNamed(IDR_AURA_UBER_TRAY_IME).ToImageSkia());
UpdateLabel(label);
}
~IMEDefaultView() override {}
void UpdateLabel(const base::string16& label) {
SetLabel(label);
SetAccessibleName(label);
}
private:
DISALLOW_COPY_AND_ASSIGN(IMEDefaultView);
};
class IMEDetailedView : public ImeListView {
public:
IMEDetailedView(SystemTrayItem* owner,
LoginStatus login,
bool show_keyboard_toggle)
: ImeListView(owner, show_keyboard_toggle, ImeListView::HIDE_SINGLE_IME),
login_(login) {
SystemTrayDelegate* delegate = WmShell::Get()->system_tray_delegate();
IMEInfoList list;
delegate->GetAvailableIMEList(&list);
IMEPropertyInfoList property_list;
delegate->GetCurrentIMEProperties(&property_list);
Update(list, property_list, show_keyboard_toggle,
ImeListView::HIDE_SINGLE_IME);
}
~IMEDetailedView() override {}
void Update(const IMEInfoList& list,
const IMEPropertyInfoList& property_list,
bool show_keyboard_toggle,
SingleImeBehavior single_ime_behavior) override {
ImeListView::Update(list, property_list, show_keyboard_toggle,
single_ime_behavior);
if (login_ != LoginStatus::NOT_LOGGED_IN && login_ != LoginStatus::LOCKED &&
!WmShell::Get()->GetSessionStateDelegate()->IsInSecondaryLoginScreen())
AppendSettings();
AppendHeaderEntry();
}
private:
// ImeListView:
void OnViewClicked(views::View* sender) override {
ImeListView::OnViewClicked(sender);
SystemTrayDelegate* delegate = WmShell::Get()->system_tray_delegate();
if (sender == footer()->content()) {
TransitionToDefaultView();
} else if (sender == settings_) {
WmShell::Get()->RecordUserMetricsAction(
UMA_STATUS_AREA_IME_SHOW_DETAILED);
delegate->ShowIMESettings();
}
}
void AppendHeaderEntry() { CreateSpecialRow(IDS_ASH_STATUS_TRAY_IME, this); }
void AppendSettings() {
HoverHighlightView* container = new HoverHighlightView(this);
container->AddLabel(
ui::ResourceBundle::GetSharedInstance().GetLocalizedString(
IDS_ASH_STATUS_TRAY_IME_SETTINGS),
gfx::ALIGN_LEFT, false /* highlight */);
AddChildView(container);
settings_ = container;
}
LoginStatus login_;
views::View* settings_;
DISALLOW_COPY_AND_ASSIGN(IMEDetailedView);
};
} // namespace tray
TrayIME::TrayIME(SystemTray* system_tray)
: SystemTrayItem(system_tray, UMA_IME),
tray_label_(NULL),
default_(NULL),
detailed_(NULL),
keyboard_suppressed_(false),
is_visible_(true) {
SystemTrayNotifier* tray_notifier = WmShell::Get()->system_tray_notifier();
tray_notifier->AddVirtualKeyboardObserver(this);
tray_notifier->AddAccessibilityObserver(this);
tray_notifier->AddIMEObserver(this);
}
TrayIME::~TrayIME() {
SystemTrayNotifier* tray_notifier = WmShell::Get()->system_tray_notifier();
tray_notifier->RemoveIMEObserver(this);
tray_notifier->RemoveAccessibilityObserver(this);
tray_notifier->RemoveVirtualKeyboardObserver(this);
}
void TrayIME::OnKeyboardSuppressionChanged(bool suppressed) {
keyboard_suppressed_ = suppressed;
Update();
}
void TrayIME::OnAccessibilityModeChanged(
AccessibilityNotificationVisibility notify) {
Update();
}
void TrayIME::Update() {
UpdateTrayLabel(current_ime_, ime_list_.size());
if (default_) {
default_->SetVisible(ShouldDefaultViewBeVisible());
default_->UpdateLabel(GetDefaultViewLabel(ime_list_.size() > 1));
}
if (detailed_)
detailed_->Update(ime_list_, property_list_, ShouldShowKeyboardToggle(),
ImeListView::HIDE_SINGLE_IME);
}
void TrayIME::UpdateTrayLabel(const IMEInfo& current, size_t count) {
if (tray_label_) {
bool visible = count > 1 && is_visible_;
tray_label_->SetVisible(visible);
// Do not change label before hiding because this change is noticeable.
if (!visible)
return;
if (current.third_party) {
tray_label_->label()->SetText(current.short_name +
base::UTF8ToUTF16("*"));
} else {
tray_label_->label()->SetText(current.short_name);
}
SetTrayLabelItemBorder(tray_label_, system_tray()->shelf_alignment());
tray_label_->Layout();
}
}
bool TrayIME::ShouldShowKeyboardToggle() {
return keyboard_suppressed_ &&
!WmShell::Get()->accessibility_delegate()->IsVirtualKeyboardEnabled();
}
base::string16 TrayIME::GetDefaultViewLabel(bool show_ime_label) {
if (show_ime_label) {
IMEInfo current;
WmShell::Get()->system_tray_delegate()->GetCurrentIME(¤t);
return current.name;
} else {
// Display virtual keyboard status instead.
int id = keyboard::IsKeyboardEnabled()
? IDS_ASH_STATUS_TRAY_KEYBOARD_ENABLED
: IDS_ASH_STATUS_TRAY_KEYBOARD_DISABLED;
return ui::ResourceBundle::GetSharedInstance().GetLocalizedString(id);
}
}
views::View* TrayIME::CreateTrayView(LoginStatus status) {
CHECK(tray_label_ == NULL);
tray_label_ = new TrayItemView(this);
tray_label_->CreateLabel();
SetupLabelForTray(tray_label_->label());
// Hide IME tray when it is created, it will be updated when it is notified
// of the IME refresh event.
tray_label_->SetVisible(false);
return tray_label_;
}
views::View* TrayIME::CreateDefaultView(LoginStatus status) {
CHECK(default_ == NULL);
default_ =
new tray::IMEDefaultView(this, GetDefaultViewLabel(ime_list_.size() > 1));
default_->SetVisible(ShouldDefaultViewBeVisible());
return default_;
}
views::View* TrayIME::CreateDetailedView(LoginStatus status) {
CHECK(detailed_ == NULL);
detailed_ =
new tray::IMEDetailedView(this, status, ShouldShowKeyboardToggle());
return detailed_;
}
void TrayIME::DestroyTrayView() {
tray_label_ = NULL;
}
void TrayIME::DestroyDefaultView() {
default_ = NULL;
}
void TrayIME::DestroyDetailedView() {
detailed_ = NULL;
}
void TrayIME::UpdateAfterLoginStatusChange(LoginStatus status) {}
void TrayIME::UpdateAfterShelfAlignmentChange(ShelfAlignment alignment) {
SetTrayLabelItemBorder(tray_label_, alignment);
tray_label_->Layout();
}
void TrayIME::OnIMERefresh() {
// Caches the current ime state.
SystemTrayDelegate* delegate = WmShell::Get()->system_tray_delegate();
ime_list_.clear();
property_list_.clear();
delegate->GetCurrentIME(¤t_ime_);
delegate->GetAvailableIMEList(&ime_list_);
delegate->GetCurrentIMEProperties(&property_list_);
Update();
}
void TrayIME::OnIMEMenuActivationChanged(bool is_active) {
is_visible_ = !is_active;
if (is_visible_)
OnIMERefresh();
else
Update();
}
bool TrayIME::ShouldDefaultViewBeVisible() {
return is_visible_ && (ime_list_.size() > 1 || property_list_.size() > 1 ||
ShouldShowKeyboardToggle());
}
} // namespace ash
| bsd-3-clause |
PolymerLabs/ristretto | src/reporter.ts | 2969 | /**
* @license
* Copyright (c) 2017 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at
* http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at
* http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at
* http://polymer.github.io/PATENTS.txt
*/
import { Suite } from './suite.js';
import { Spec } from './spec.js';
import { Test, TestResult } from './test.js';
/**
* These are the events that represent the different stages of the reporting
* lifecycle.
*/
export enum ReporterEvent {
suiteStart = 'SuiteStart',
suiteEnd = 'SuiteEnd',
specStart = 'SpecStart',
specEnd = 'SpecEnd',
testStart = 'TestStart',
testEnd = 'TestEnd',
unexpectedError = 'UnexpectedError'
};
/**
* A reporter is an object that implements some callbacks associated with
* reporting lifecycle stages of interest. The default reporter has none
* of these callbacks implemented.
*/
export abstract class Reporter {
/**
* If set to true, the reporter will not dispatch lifecycle event details
* to its associated callbacks. This is useful for disabling reporting for
* some stretch of time (for example, when a test is isolated).
*/
disabled: boolean = false;
/**
* Dispatches an event's details to the appropriate lifecycle callback.
*/
report(eventName: ReporterEvent, ...args: any[]): boolean {
const methodName = `on${eventName}` as keyof this;
if (this.disabled || this[methodName] == null) {
return false;
}
// TODO(dfreedm): make a argument mapping for each method of the reporter, someday
(this[methodName] as any)(...args);
return true;
}
/**
* Invoked just before a suite begins iterating over specs and invoking tests.
*/
onSuiteStart?(suite: Suite): void;
/**
* Invoked after a suite has finished iterating over specs and invoking all
* tests.
*/
onSuiteEnd?(suite: Suite): void;
/**
* Invoked before each spec in the suite, before ivoking tests.
*/
onSpecStart?(spec: Spec, suite: Suite): void;
/**
* Invoked for each spec in the suite, after all tests have been invoked.
*/
onSpecEnd?(spec: Spec, suite: Suite): void;
/**
* Invoked for each test, before its implementation is invoked.
*/
onTestStart?(test: Test, suite: Suite): void;
/**
* Invoked for each test, after its implementation has been invoked. Receives
* the result of the test.
*/
onTestEnd?(result: TestResult, test: Test, suite: Suite): void;
/**
* Invoked when there is an out-of-band error, such as an internal exception
* of the test runner or one of its related mixins.
*/
onUnexpectedError?(message: string, error: Error, suite: Suite): void;
};
| bsd-3-clause |
Bladefidz/ocfa_yii | vendor/yiisoft/yii2-apidoc/helpers/ApiMarkdownTrait.php | 6745 | <?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\apidoc\helpers;
use phpDocumentor\Reflection\DocBlock\Type\Collection;
use yii\apidoc\models\MethodDoc;
use yii\apidoc\models\TypeDoc;
/**
* Class ApiMarkdownTrait
*
* @property TypeDoc $renderingContext
*/
trait ApiMarkdownTrait
{
/**
* @marker [[
*/
protected function parseApiLinks($text)
{
$context = $this->renderingContext;
if (preg_match('/^\[\[([\w\d\\\\\(\):$]+)(\|[^\]]*)?\]\]/', $text, $matches)) {
$offset = strlen($matches[0]);
$object = $matches[1];
$title = (empty($matches[2]) || $matches[2] == '|') ? null : substr($matches[2], 1);
if (($pos = strpos($object, '::')) !== false) {
$typeName = substr($object, 0, $pos);
$subjectName = substr($object, $pos + 2);
if ($context !== null) {
// Collection resolves relative types
$typeName = (new Collection([$typeName], $context->phpDocContext))->__toString();
}
/** @var $type TypeDoc */
$type = static::$renderer->apiContext->getType($typeName);
if ($type === null) {
static::$renderer->apiContext->errors[] = [
'file' => ($context !== null) ? $context->sourceFile : null,
'message' => 'broken link to ' . $typeName . '::' . $subjectName . (($context !== null) ? ' in ' . $context->name : ''),
];
return [
['brokenApiLink', '<span class="broken-link">' . $typeName . '::' . $subjectName . '</span>'],
$offset
];
} else {
if (($subject = $type->findSubject($subjectName)) !== null) {
if ($title === null) {
$title = $type->name . '::' . $subject->name;
if ($subject instanceof MethodDoc) {
$title .= '()';
}
}
return [
['apiLink', static::$renderer->createSubjectLink($subject, $title)],
$offset
];
} else {
static::$renderer->apiContext->errors[] = [
'file' => ($context !== null) ? $context->sourceFile : null,
'message' => 'broken link to ' . $type->name . '::' . $subjectName . (($context !== null) ? ' in ' . $context->name : ''),
];
return [
['brokenApiLink', '<span class="broken-link">' . $type->name . '::' . $subjectName . '</span>'],
$offset
];
}
}
} elseif ($context !== null && ($subject = $context->findSubject($object)) !== null) {
return [
['apiLink', static::$renderer->createSubjectLink($subject, $title)],
$offset
];
}
if ($context !== null) {
// Collection resolves relative types
$object = (new Collection([$object], $context->phpDocContext))->__toString();
}
if (($type = static::$renderer->apiContext->getType($object)) !== null) {
return [
['apiLink', static::$renderer->createTypeLink($type, null, $title)],
$offset
];
} elseif (strpos($typeLink = static::$renderer->createTypeLink($object, null, $title), '<a href') !== false) {
return [
['apiLink', $typeLink],
$offset
];
}
static::$renderer->apiContext->errors[] = [
'file' => ($context !== null) ? $context->sourceFile : null,
'message' => 'broken link to ' . $object . (($context !== null) ? ' in ' . $context->name : ''),
];
return [
['brokenApiLink', '<span class="broken-link">' . $object . '</span>'],
$offset
];
}
return [['text', '[['], 2];
}
/**
* Renders API link
* @param array $block
* @return string
*/
protected function renderApiLink($block)
{
return $block[1];
}
/**
* Renders API link that is broken i.e. points nowhere
* @param array $block
* @return string
*/
protected function renderBrokenApiLink($block)
{
return $block[1];
}
/**
* Consume lines for a blockquote element
*/
protected function consumeQuote($lines, $current)
{
$block = parent::consumeQuote($lines, $current);
$blockTypes = [
'warning',
'note',
'info',
'tip',
];
// check whether this is a special Info, Note, Warning, Tip block
$content = $block[0]['content'];
$first = reset($content);
if (isset($first[0]) && $first[0] === 'paragraph') {
$parfirst = reset($first['content']);
if (isset($parfirst[0]) && $parfirst[0] === 'text') {
foreach ($blockTypes as $type) {
if (strncasecmp("$type: ", $parfirst[1], $len = strlen($type) + 2) === 0) {
// remove block indicator
$block[0]['content'][0]['content'][0][1] = substr($parfirst[1], $len);
// add translated block indicator as bold text
array_unshift($block[0]['content'][0]['content'], [
'strong',
[
['text', $this->translateBlockType($type)],
],
]);
$block[0]['blocktype'] = $type;
break;
}
}
}
}
return $block;
}
protected abstract function translateBlockType($type);
/**
* Renders a blockquote
*/
protected function renderQuote($block)
{
$class = '';
if (isset($block['blocktype'])) {
$class = ' class="' . $block['blocktype'] . '"';
}
return "<blockquote{$class}>" . $this->renderAbsy($block['content']) . "</blockquote>\n";
}
}
| bsd-3-clause |
ft-/arribasim-dev-extras | OpenSim/Framework/DOMap.cs | 4063 | /*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project 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 DEVELOPERS ``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 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.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
namespace OpenSim.Framework
{
/// <summary>
/// This class stores and retrieves dynamic objects.
/// </summary>
/// <remarks>
/// Experimental - DO NOT USE. Does not yet have namespace support.
/// </remarks>
public class DOMap
{
private IDictionary<string, object> m_map;
private ReaderWriterLock m_mapRwLock = new ReaderWriterLock();
public void Add(string ns, string objName, object dynObj)
{
DAMap.ValidateNamespace(ns);
m_mapRwLock.AcquireWriterLock(-1);
try
{
if (m_map == null)
m_map = new Dictionary<string, object>();
m_map.Add(objName, dynObj);
}
finally
{
m_mapRwLock.ReleaseWriterLock();
}
}
public bool ContainsKey(string key)
{
m_mapRwLock.AcquireReaderLock(-1);
try
{
return Get(key) != null;
}
finally
{
m_mapRwLock.ReleaseReaderLock();
}
}
/// <summary>
/// Get a dynamic object
/// </summary>
/// <remarks>
/// Not providing an index method so that users can't casually overwrite each other's objects.
/// </remarks>
/// <param name='key'></param>
public object Get(string key)
{
m_mapRwLock.AcquireReaderLock(-1);
try
{
if (m_map == null)
return null;
else
return m_map[key];
}
finally
{
m_mapRwLock.ReleaseReaderLock();
}
}
public bool Remove(string key)
{
m_mapRwLock.AcquireWriterLock(-1);
try
{
if (m_map == null)
return false;
else
return m_map.Remove(key);
}
finally
{
m_mapRwLock.ReleaseWriterLock();
}
}
}
} | bsd-3-clause |
SaschaMester/delicium | cc/layers/picture_layer_impl.cc | 50012 | // Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "cc/layers/picture_layer_impl.h"
#include <algorithm>
#include <cmath>
#include <limits>
#include <set>
#include "base/time/time.h"
#include "base/trace_event/trace_event_argument.h"
#include "cc/base/math_util.h"
#include "cc/debug/debug_colors.h"
#include "cc/debug/micro_benchmark_impl.h"
#include "cc/debug/traced_value.h"
#include "cc/layers/append_quads_data.h"
#include "cc/layers/solid_color_layer_impl.h"
#include "cc/output/begin_frame_args.h"
#include "cc/quads/checkerboard_draw_quad.h"
#include "cc/quads/debug_border_draw_quad.h"
#include "cc/quads/picture_draw_quad.h"
#include "cc/quads/solid_color_draw_quad.h"
#include "cc/quads/tile_draw_quad.h"
#include "cc/tiles/tile_manager.h"
#include "cc/tiles/tiling_set_raster_queue_all.h"
#include "cc/trees/layer_tree_impl.h"
#include "cc/trees/occlusion.h"
#include "ui/gfx/geometry/quad_f.h"
#include "ui/gfx/geometry/rect_conversions.h"
#include "ui/gfx/geometry/size_conversions.h"
namespace {
// This must be > 1 as we multiply or divide by this to find a new raster
// scale during pinch.
const float kMaxScaleRatioDuringPinch = 2.0f;
// When creating a new tiling during pinch, snap to an existing
// tiling's scale if the desired scale is within this ratio.
const float kSnapToExistingTilingRatio = 1.2f;
// Even for really wide viewports, at some point GPU raster should use
// less than 4 tiles to fill the viewport. This is set to 256 as a
// sane minimum for now, but we might want to tune this for low-end.
const int kMinHeightForGpuRasteredTile = 256;
// When making odd-sized tiles, round them up to increase the chances
// of using the same tile size.
const int kTileRoundUp = 64;
} // namespace
namespace cc {
PictureLayerImpl::PictureLayerImpl(
LayerTreeImpl* tree_impl,
int id,
bool is_mask,
scoped_refptr<SyncedScrollOffset> scroll_offset)
: LayerImpl(tree_impl, id, scroll_offset),
twin_layer_(nullptr),
tilings_(CreatePictureLayerTilingSet()),
ideal_page_scale_(0.f),
ideal_device_scale_(0.f),
ideal_source_scale_(0.f),
ideal_contents_scale_(0.f),
raster_page_scale_(0.f),
raster_device_scale_(0.f),
raster_source_scale_(0.f),
raster_contents_scale_(0.f),
low_res_raster_contents_scale_(0.f),
raster_source_scale_is_fixed_(false),
was_screen_space_transform_animating_(false),
only_used_low_res_last_append_quads_(false),
is_mask_(is_mask),
nearest_neighbor_(false) {
layer_tree_impl()->RegisterPictureLayerImpl(this);
}
PictureLayerImpl::~PictureLayerImpl() {
if (twin_layer_)
twin_layer_->twin_layer_ = nullptr;
layer_tree_impl()->UnregisterPictureLayerImpl(this);
}
const char* PictureLayerImpl::LayerTypeAsString() const {
return "cc::PictureLayerImpl";
}
scoped_ptr<LayerImpl> PictureLayerImpl::CreateLayerImpl(
LayerTreeImpl* tree_impl) {
return PictureLayerImpl::Create(tree_impl, id(), is_mask_,
synced_scroll_offset());
}
void PictureLayerImpl::PushPropertiesTo(LayerImpl* base_layer) {
PictureLayerImpl* layer_impl = static_cast<PictureLayerImpl*>(base_layer);
DCHECK_EQ(layer_impl->is_mask_, is_mask_);
LayerImpl::PushPropertiesTo(base_layer);
// Twin relationships should never change once established.
DCHECK_IMPLIES(twin_layer_, twin_layer_ == layer_impl);
DCHECK_IMPLIES(twin_layer_, layer_impl->twin_layer_ == this);
// The twin relationship does not need to exist before the first
// PushPropertiesTo from pending to active layer since before that the active
// layer can not have a pile or tilings, it has only been created and inserted
// into the tree at that point.
twin_layer_ = layer_impl;
layer_impl->twin_layer_ = this;
layer_impl->SetNearestNeighbor(nearest_neighbor_);
// Solid color layers have no tilings.
DCHECK_IMPLIES(raster_source_->IsSolidColor(), tilings_->num_tilings() == 0);
// The pending tree should only have a high res (and possibly low res) tiling.
DCHECK_LE(tilings_->num_tilings(),
layer_tree_impl()->create_low_res_tiling() ? 2u : 1u);
layer_impl->set_gpu_raster_max_texture_size(gpu_raster_max_texture_size_);
layer_impl->UpdateRasterSource(raster_source_, &invalidation_,
tilings_.get());
DCHECK(invalidation_.IsEmpty());
// After syncing a solid color layer, the active layer has no tilings.
DCHECK_IMPLIES(raster_source_->IsSolidColor(),
layer_impl->tilings_->num_tilings() == 0);
layer_impl->raster_page_scale_ = raster_page_scale_;
layer_impl->raster_device_scale_ = raster_device_scale_;
layer_impl->raster_source_scale_ = raster_source_scale_;
layer_impl->raster_contents_scale_ = raster_contents_scale_;
layer_impl->low_res_raster_contents_scale_ = low_res_raster_contents_scale_;
layer_impl->SanityCheckTilingState();
// We always need to push properties.
// See http://crbug.com/303943
// TODO(danakj): Stop always pushing properties since we don't swap tilings.
needs_push_properties_ = true;
}
void PictureLayerImpl::AppendQuads(RenderPass* render_pass,
AppendQuadsData* append_quads_data) {
// The bounds and the pile size may differ if the pile wasn't updated (ie.
// PictureLayer::Update didn't happen). In that case the pile will be empty.
DCHECK_IMPLIES(!raster_source_->GetSize().IsEmpty(),
bounds() == raster_source_->GetSize())
<< " bounds " << bounds().ToString() << " pile "
<< raster_source_->GetSize().ToString();
SharedQuadState* shared_quad_state =
render_pass->CreateAndAppendSharedQuadState();
if (raster_source_->IsSolidColor()) {
PopulateSharedQuadState(shared_quad_state);
AppendDebugBorderQuad(
render_pass, bounds(), shared_quad_state, append_quads_data);
SolidColorLayerImpl::AppendSolidQuads(
render_pass, draw_properties().occlusion_in_content_space,
shared_quad_state, visible_layer_rect(),
raster_source_->GetSolidColor(), append_quads_data);
return;
}
float max_contents_scale = MaximumTilingContentsScale();
PopulateScaledSharedQuadState(shared_quad_state, max_contents_scale);
Occlusion scaled_occlusion =
draw_properties()
.occlusion_in_content_space.GetOcclusionWithGivenDrawTransform(
shared_quad_state->quad_to_target_transform);
if (current_draw_mode_ == DRAW_MODE_RESOURCELESS_SOFTWARE) {
AppendDebugBorderQuad(
render_pass, shared_quad_state->quad_layer_bounds, shared_quad_state,
append_quads_data, DebugColors::DirectPictureBorderColor(),
DebugColors::DirectPictureBorderWidth(layer_tree_impl()));
gfx::Rect geometry_rect = shared_quad_state->visible_quad_layer_rect;
gfx::Rect opaque_rect = contents_opaque() ? geometry_rect : gfx::Rect();
gfx::Rect visible_geometry_rect =
scaled_occlusion.GetUnoccludedContentRect(geometry_rect);
if (visible_geometry_rect.IsEmpty())
return;
gfx::Rect quad_content_rect = shared_quad_state->visible_quad_layer_rect;
gfx::Size texture_size = quad_content_rect.size();
gfx::RectF texture_rect = gfx::RectF(texture_size);
PictureDrawQuad* quad =
render_pass->CreateAndAppendDrawQuad<PictureDrawQuad>();
quad->SetNew(shared_quad_state, geometry_rect, opaque_rect,
visible_geometry_rect, texture_rect, texture_size,
nearest_neighbor_, RGBA_8888, quad_content_rect,
max_contents_scale, raster_source_);
ValidateQuadResources(quad);
return;
}
AppendDebugBorderQuad(render_pass, shared_quad_state->quad_layer_bounds,
shared_quad_state, append_quads_data);
if (ShowDebugBorders()) {
for (PictureLayerTilingSet::CoverageIterator iter(
tilings_.get(), max_contents_scale,
shared_quad_state->visible_quad_layer_rect, ideal_contents_scale_);
iter; ++iter) {
SkColor color;
float width;
if (*iter && iter->draw_info().IsReadyToDraw()) {
TileDrawInfo::Mode mode = iter->draw_info().mode();
if (mode == TileDrawInfo::SOLID_COLOR_MODE) {
color = DebugColors::SolidColorTileBorderColor();
width = DebugColors::SolidColorTileBorderWidth(layer_tree_impl());
} else if (mode == TileDrawInfo::OOM_MODE) {
color = DebugColors::OOMTileBorderColor();
width = DebugColors::OOMTileBorderWidth(layer_tree_impl());
} else if (iter.resolution() == HIGH_RESOLUTION) {
color = DebugColors::HighResTileBorderColor();
width = DebugColors::HighResTileBorderWidth(layer_tree_impl());
} else if (iter.resolution() == LOW_RESOLUTION) {
color = DebugColors::LowResTileBorderColor();
width = DebugColors::LowResTileBorderWidth(layer_tree_impl());
} else if (iter->contents_scale() > max_contents_scale) {
color = DebugColors::ExtraHighResTileBorderColor();
width = DebugColors::ExtraHighResTileBorderWidth(layer_tree_impl());
} else {
color = DebugColors::ExtraLowResTileBorderColor();
width = DebugColors::ExtraLowResTileBorderWidth(layer_tree_impl());
}
} else {
color = DebugColors::MissingTileBorderColor();
width = DebugColors::MissingTileBorderWidth(layer_tree_impl());
}
DebugBorderDrawQuad* debug_border_quad =
render_pass->CreateAndAppendDrawQuad<DebugBorderDrawQuad>();
gfx::Rect geometry_rect = iter.geometry_rect();
gfx::Rect visible_geometry_rect = geometry_rect;
debug_border_quad->SetNew(shared_quad_state,
geometry_rect,
visible_geometry_rect,
color,
width);
}
}
// Keep track of the tilings that were used so that tilings that are
// unused can be considered for removal.
last_append_quads_tilings_.clear();
// Ignore missing tiles outside of viewport for tile priority. This is
// normally the same as draw viewport but can be independently overridden by
// embedders like Android WebView with SetExternalDrawConstraints.
gfx::Rect scaled_viewport_for_tile_priority = gfx::ScaleToEnclosingRect(
viewport_rect_for_tile_priority_in_content_space_, max_contents_scale);
size_t missing_tile_count = 0u;
size_t on_demand_missing_tile_count = 0u;
only_used_low_res_last_append_quads_ = true;
for (PictureLayerTilingSet::CoverageIterator iter(
tilings_.get(), max_contents_scale,
shared_quad_state->visible_quad_layer_rect, ideal_contents_scale_);
iter; ++iter) {
gfx::Rect geometry_rect = iter.geometry_rect();
gfx::Rect opaque_rect = contents_opaque() ? geometry_rect : gfx::Rect();
gfx::Rect visible_geometry_rect =
scaled_occlusion.GetUnoccludedContentRect(geometry_rect);
if (visible_geometry_rect.IsEmpty())
continue;
append_quads_data->visible_layer_area +=
visible_geometry_rect.width() * visible_geometry_rect.height();
bool has_draw_quad = false;
if (*iter && iter->draw_info().IsReadyToDraw()) {
const TileDrawInfo& draw_info = iter->draw_info();
switch (draw_info.mode()) {
case TileDrawInfo::RESOURCE_MODE: {
gfx::RectF texture_rect = iter.texture_rect();
// The raster_contents_scale_ is the best scale that the layer is
// trying to produce, even though it may not be ideal. Since that's
// the best the layer can promise in the future, consider those as
// complete. But if a tile is ideal scale, we don't want to consider
// it incomplete and trying to replace it with a tile at a worse
// scale.
if (iter->contents_scale() != raster_contents_scale_ &&
iter->contents_scale() != ideal_contents_scale_ &&
geometry_rect.Intersects(scaled_viewport_for_tile_priority)) {
append_quads_data->num_incomplete_tiles++;
}
TileDrawQuad* quad =
render_pass->CreateAndAppendDrawQuad<TileDrawQuad>();
quad->SetNew(shared_quad_state, geometry_rect, opaque_rect,
visible_geometry_rect, draw_info.resource_id(),
texture_rect, draw_info.resource_size(),
draw_info.contents_swizzled(), nearest_neighbor_);
ValidateQuadResources(quad);
iter->draw_info().set_was_ever_used_to_draw();
has_draw_quad = true;
break;
}
case TileDrawInfo::SOLID_COLOR_MODE: {
SolidColorDrawQuad* quad =
render_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
quad->SetNew(shared_quad_state, geometry_rect, visible_geometry_rect,
draw_info.solid_color(), false);
ValidateQuadResources(quad);
iter->draw_info().set_was_ever_used_to_draw();
has_draw_quad = true;
break;
}
case TileDrawInfo::OOM_MODE:
break; // Checkerboard.
}
}
if (!has_draw_quad) {
if (draw_checkerboard_for_missing_tiles()) {
CheckerboardDrawQuad* quad =
render_pass->CreateAndAppendDrawQuad<CheckerboardDrawQuad>();
SkColor color = DebugColors::DefaultCheckerboardColor();
quad->SetNew(shared_quad_state, geometry_rect, visible_geometry_rect,
color, ideal_device_scale_);
} else {
SkColor color = SafeOpaqueBackgroundColor();
SolidColorDrawQuad* quad =
render_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
quad->SetNew(shared_quad_state,
geometry_rect,
visible_geometry_rect,
color,
false);
ValidateQuadResources(quad);
}
if (geometry_rect.Intersects(scaled_viewport_for_tile_priority)) {
append_quads_data->num_missing_tiles++;
++missing_tile_count;
}
append_quads_data->approximated_visible_content_area +=
visible_geometry_rect.width() * visible_geometry_rect.height();
append_quads_data->checkerboarded_visible_content_area +=
visible_geometry_rect.width() * visible_geometry_rect.height();
continue;
}
if (iter.resolution() != HIGH_RESOLUTION) {
append_quads_data->approximated_visible_content_area +=
visible_geometry_rect.width() * visible_geometry_rect.height();
}
// If we have a draw quad, but it's not low resolution, then
// mark that we've used something other than low res to draw.
if (iter.resolution() != LOW_RESOLUTION)
only_used_low_res_last_append_quads_ = false;
if (last_append_quads_tilings_.empty() ||
last_append_quads_tilings_.back() != iter.CurrentTiling()) {
last_append_quads_tilings_.push_back(iter.CurrentTiling());
}
}
if (missing_tile_count) {
TRACE_EVENT_INSTANT2("cc",
"PictureLayerImpl::AppendQuads checkerboard",
TRACE_EVENT_SCOPE_THREAD,
"missing_tile_count",
missing_tile_count,
"on_demand_missing_tile_count",
on_demand_missing_tile_count);
}
// Aggressively remove any tilings that are not seen to save memory. Note
// that this is at the expense of doing cause more frequent re-painting. A
// better scheme would be to maintain a tighter visible_layer_rect for the
// finer tilings.
CleanUpTilingsOnActiveLayer(last_append_quads_tilings_);
}
bool PictureLayerImpl::UpdateTiles(bool resourceless_software_draw) {
if (!resourceless_software_draw) {
visible_rect_for_tile_priority_ = visible_layer_rect();
}
if (!CanHaveTilings()) {
ideal_page_scale_ = 0.f;
ideal_device_scale_ = 0.f;
ideal_contents_scale_ = 0.f;
ideal_source_scale_ = 0.f;
SanityCheckTilingState();
return false;
}
// Remove any non-ideal tilings that were not used last time we generated
// quads to save memory and processing time. Note that pending tree should
// only have one or two tilings (high and low res), so only clean up the
// active layer. This cleans it up here in case AppendQuads didn't run.
// If it did run, this would not remove any additional tilings.
if (layer_tree_impl()->IsActiveTree())
CleanUpTilingsOnActiveLayer(last_append_quads_tilings_);
UpdateIdealScales();
if (!raster_contents_scale_ || ShouldAdjustRasterScale()) {
RecalculateRasterScales();
AddTilingsForRasterScale();
}
DCHECK(raster_page_scale_);
DCHECK(raster_device_scale_);
DCHECK(raster_source_scale_);
DCHECK(raster_contents_scale_);
DCHECK(low_res_raster_contents_scale_);
was_screen_space_transform_animating_ =
draw_properties().screen_space_transform_is_animating;
if (draw_transform_is_animating())
raster_source_->SetShouldAttemptToUseDistanceFieldText();
double current_frame_time_in_seconds =
(layer_tree_impl()->CurrentBeginFrameArgs().frame_time -
base::TimeTicks()).InSecondsF();
UpdateViewportRectForTilePriorityInContentSpace();
// The tiling set can require tiles for activation any of the following
// conditions are true:
// - This layer produced a high-res or non-ideal-res tile last frame.
// - We're in requires high res to draw mode.
// - We're not in smoothness takes priority mode.
// To put different, the tiling set can't require tiles for activation if
// we're in smoothness mode and only used low-res or checkerboard to draw last
// frame and we don't need high res to draw.
//
// The reason for this is that we should be able to activate sooner and get a
// more up to date recording, so we don't run out of recording on the active
// tree.
bool can_require_tiles_for_activation =
!only_used_low_res_last_append_quads_ || RequiresHighResToDraw() ||
!layer_tree_impl()->SmoothnessTakesPriority();
static const Occlusion kEmptyOcclusion;
const Occlusion& occlusion_in_content_space =
layer_tree_impl()->settings().use_occlusion_for_tile_prioritization
? draw_properties().occlusion_in_content_space
: kEmptyOcclusion;
// Pass |occlusion_in_content_space| for |occlusion_in_layer_space| since
// they are the same space in picture layer, as contents scale is always 1.
bool updated = tilings_->UpdateTilePriorities(
viewport_rect_for_tile_priority_in_content_space_, ideal_contents_scale_,
current_frame_time_in_seconds, occlusion_in_content_space,
can_require_tiles_for_activation);
return updated;
}
void PictureLayerImpl::UpdateViewportRectForTilePriorityInContentSpace() {
// If visible_rect_for_tile_priority_ is empty or
// viewport_rect_for_tile_priority is set to be different from the device
// viewport, try to inverse project the viewport into layer space and use
// that. Otherwise just use visible_rect_for_tile_priority_
gfx::Rect visible_rect_in_content_space = visible_rect_for_tile_priority_;
gfx::Rect viewport_rect_for_tile_priority =
layer_tree_impl()->ViewportRectForTilePriority();
if (visible_rect_in_content_space.IsEmpty() ||
layer_tree_impl()->DeviceViewport() != viewport_rect_for_tile_priority) {
gfx::Transform view_to_layer(gfx::Transform::kSkipInitialization);
if (screen_space_transform().GetInverse(&view_to_layer)) {
// Transform from view space to content space.
visible_rect_in_content_space =
gfx::ToEnclosingRect(MathUtil::ProjectClippedRect(
view_to_layer, viewport_rect_for_tile_priority));
// We have to allow for a viewport that is outside of the layer bounds in
// order to compute tile priorities correctly for offscreen content that
// is going to make it on screen. However, we also have to limit the
// viewport since it can be very large due to screen_space_transforms. As
// a heuristic, we clip to bounds padded by skewport_extrapolation_limit *
// maximum tiling scale, since this should allow sufficient room for
// skewport calculations.
gfx::Rect padded_bounds(bounds());
int padding_amount = layer_tree_impl()
->settings()
.skewport_extrapolation_limit_in_content_pixels *
MaximumTilingContentsScale();
padded_bounds.Inset(-padding_amount, -padding_amount);
visible_rect_in_content_space.Intersect(padded_bounds);
}
}
viewport_rect_for_tile_priority_in_content_space_ =
visible_rect_in_content_space;
}
PictureLayerImpl* PictureLayerImpl::GetPendingOrActiveTwinLayer() const {
if (!twin_layer_ || !twin_layer_->IsOnActiveOrPendingTree())
return nullptr;
return twin_layer_;
}
void PictureLayerImpl::UpdateRasterSource(
scoped_refptr<RasterSource> raster_source,
Region* new_invalidation,
const PictureLayerTilingSet* pending_set) {
// The bounds and the pile size may differ if the pile wasn't updated (ie.
// PictureLayer::Update didn't happen). In that case the pile will be empty.
DCHECK_IMPLIES(!raster_source->GetSize().IsEmpty(),
bounds() == raster_source->GetSize())
<< " bounds " << bounds().ToString() << " pile "
<< raster_source->GetSize().ToString();
// The |raster_source_| is initially null, so have to check for that for the
// first frame.
bool could_have_tilings = raster_source_.get() && CanHaveTilings();
raster_source_.swap(raster_source);
// The |new_invalidation| must be cleared before updating tilings since they
// access the invalidation through the PictureLayerTilingClient interface.
invalidation_.Clear();
invalidation_.Swap(new_invalidation);
bool can_have_tilings = CanHaveTilings();
DCHECK_IMPLIES(
pending_set,
can_have_tilings == GetPendingOrActiveTwinLayer()->CanHaveTilings());
// Need to call UpdateTiles again if CanHaveTilings changed.
if (could_have_tilings != can_have_tilings)
layer_tree_impl()->set_needs_update_draw_properties();
if (!can_have_tilings) {
RemoveAllTilings();
return;
}
// We could do this after doing UpdateTiles, which would avoid doing this for
// tilings that are going to disappear on the pending tree (if scale changed).
// But that would also be more complicated, so we just do it here for now.
if (pending_set) {
tilings_->UpdateTilingsToCurrentRasterSourceForActivation(
raster_source_, pending_set, invalidation_, MinimumContentsScale(),
MaximumContentsScale());
} else {
tilings_->UpdateTilingsToCurrentRasterSourceForCommit(
raster_source_, invalidation_, MinimumContentsScale(),
MaximumContentsScale());
}
}
void PictureLayerImpl::UpdateCanUseLCDTextAfterCommit() {
// This function is only allowed to be called after commit, due to it not
// being smart about sharing tiles and because otherwise it would cause
// flashes by switching out tiles in place that may be currently on screen.
DCHECK(layer_tree_impl()->IsSyncTree());
// Don't allow the LCD text state to change once disabled.
if (!RasterSourceUsesLCDText())
return;
if (can_use_lcd_text() == RasterSourceUsesLCDText())
return;
// Raster sources are considered const, so in order to update the state
// a new one must be created and all tiles recreated.
scoped_refptr<RasterSource> new_raster_source =
raster_source_->CreateCloneWithoutLCDText();
raster_source_.swap(new_raster_source);
// Synthetically invalidate everything.
gfx::Rect bounds_rect(bounds());
invalidation_ = Region(bounds_rect);
tilings_->UpdateRasterSourceDueToLCDChange(raster_source_, invalidation_);
SetUpdateRect(bounds_rect);
DCHECK(!RasterSourceUsesLCDText());
}
bool PictureLayerImpl::RasterSourceUsesLCDText() const {
return raster_source_ ? raster_source_->CanUseLCDText()
: layer_tree_impl()->settings().can_use_lcd_text;
}
void PictureLayerImpl::NotifyTileStateChanged(const Tile* tile) {
if (layer_tree_impl()->IsActiveTree()) {
gfx::RectF layer_damage_rect =
gfx::ScaleRect(tile->content_rect(), 1.f / tile->contents_scale());
AddDamageRect(layer_damage_rect);
}
if (tile->draw_info().NeedsRaster()) {
PictureLayerTiling* tiling =
tilings_->FindTilingWithScale(tile->contents_scale());
if (tiling)
tiling->set_all_tiles_done(false);
}
}
void PictureLayerImpl::DidBeginTracing() {
raster_source_->DidBeginTracing();
}
void PictureLayerImpl::ReleaseResources() {
// Recreate tilings with new settings, since some of those might change when
// we release resources.
tilings_ = nullptr;
ResetRasterScale();
}
void PictureLayerImpl::RecreateResources() {
tilings_ = CreatePictureLayerTilingSet();
// To avoid an edge case after lost context where the tree is up to date but
// the tilings have not been managed, request an update draw properties
// to force tilings to get managed.
layer_tree_impl()->set_needs_update_draw_properties();
}
skia::RefPtr<SkPicture> PictureLayerImpl::GetPicture() {
return raster_source_->GetFlattenedPicture();
}
Region PictureLayerImpl::GetInvalidationRegion() {
// |invalidation_| gives the invalidation contained in the source frame, but
// is not cleared after drawing from the layer. However, update_rect() is
// cleared once the invalidation is drawn, which is useful for debugging
// visualizations. This method intersects the two to give a more exact
// representation of what was invalidated that is cleared after drawing.
return IntersectRegions(invalidation_, update_rect());
}
ScopedTilePtr PictureLayerImpl::CreateTile(float contents_scale,
const gfx::Rect& content_rect) {
int flags = 0;
// We don't handle solid color masks, so we shouldn't bother analyzing those.
// Otherwise, always analyze to maximize memory savings.
if (!is_mask_)
flags = Tile::USE_PICTURE_ANALYSIS;
return layer_tree_impl()->tile_manager()->CreateTile(
content_rect.size(), content_rect, contents_scale, id(),
layer_tree_impl()->source_frame_number(), flags);
}
const Region* PictureLayerImpl::GetPendingInvalidation() {
if (layer_tree_impl()->IsPendingTree())
return &invalidation_;
if (layer_tree_impl()->IsRecycleTree())
return nullptr;
DCHECK(layer_tree_impl()->IsActiveTree());
if (PictureLayerImpl* twin_layer = GetPendingOrActiveTwinLayer())
return &twin_layer->invalidation_;
return nullptr;
}
const PictureLayerTiling* PictureLayerImpl::GetPendingOrActiveTwinTiling(
const PictureLayerTiling* tiling) const {
PictureLayerImpl* twin_layer = GetPendingOrActiveTwinLayer();
if (!twin_layer)
return nullptr;
return twin_layer->tilings_->FindTilingWithScale(tiling->contents_scale());
}
bool PictureLayerImpl::RequiresHighResToDraw() const {
return layer_tree_impl()->RequiresHighResToDraw();
}
gfx::Rect PictureLayerImpl::GetEnclosingRectInTargetSpace() const {
return GetScaledEnclosingRectInTargetSpace(MaximumTilingContentsScale());
}
gfx::Size PictureLayerImpl::CalculateTileSize(
const gfx::Size& content_bounds) const {
int max_texture_size =
layer_tree_impl()->resource_provider()->max_texture_size();
if (is_mask_) {
// Masks are not tiled, so if we can't cover the whole mask with one tile,
// we shouldn't have such a tiling at all.
DCHECK_LE(content_bounds.width(), max_texture_size);
DCHECK_LE(content_bounds.height(), max_texture_size);
return content_bounds;
}
int default_tile_width = 0;
int default_tile_height = 0;
if (layer_tree_impl()->use_gpu_rasterization()) {
// For GPU rasterization, we pick an ideal tile size using the viewport
// so we don't need any settings. The current approach uses 4 tiles
// to cover the viewport vertically.
int viewport_width = gpu_raster_max_texture_size_.width();
int viewport_height = gpu_raster_max_texture_size_.height();
default_tile_width = viewport_width;
// Also, increase the height proportionally as the width decreases, and
// pad by our border texels to make the tiles exactly match the viewport.
int divisor = 4;
if (content_bounds.width() <= viewport_width / 2)
divisor = 2;
if (content_bounds.width() <= viewport_width / 4)
divisor = 1;
default_tile_height = MathUtil::RoundUp(viewport_height, divisor) / divisor;
// Grow default sizes to account for overlapping border texels.
default_tile_width += 2 * PictureLayerTiling::kBorderTexels;
default_tile_height += 2 * PictureLayerTiling::kBorderTexels;
default_tile_height =
std::max(default_tile_height, kMinHeightForGpuRasteredTile);
} else {
// For CPU rasterization we use tile-size settings.
const LayerTreeSettings& settings = layer_tree_impl()->settings();
int max_untiled_content_width = settings.max_untiled_layer_size.width();
int max_untiled_content_height = settings.max_untiled_layer_size.height();
default_tile_width = settings.default_tile_size.width();
default_tile_height = settings.default_tile_size.height();
// If the content width is small, increase tile size vertically.
// If the content height is small, increase tile size horizontally.
// If both are less than the untiled-size, use a single tile.
if (content_bounds.width() < default_tile_width)
default_tile_height = max_untiled_content_height;
if (content_bounds.height() < default_tile_height)
default_tile_width = max_untiled_content_width;
if (content_bounds.width() < max_untiled_content_width &&
content_bounds.height() < max_untiled_content_height) {
default_tile_height = max_untiled_content_height;
default_tile_width = max_untiled_content_width;
}
}
int tile_width = default_tile_width;
int tile_height = default_tile_height;
// Clamp the tile width/height to the content width/height to save space.
if (content_bounds.width() < default_tile_width) {
tile_width = std::min(tile_width, content_bounds.width());
tile_width = MathUtil::RoundUp(tile_width, kTileRoundUp);
tile_width = std::min(tile_width, default_tile_width);
}
if (content_bounds.height() < default_tile_height) {
tile_height = std::min(tile_height, content_bounds.height());
tile_height = MathUtil::RoundUp(tile_height, kTileRoundUp);
tile_height = std::min(tile_height, default_tile_height);
}
// Under no circumstance should we be larger than the max texture size.
tile_width = std::min(tile_width, max_texture_size);
tile_height = std::min(tile_height, max_texture_size);
return gfx::Size(tile_width, tile_height);
}
void PictureLayerImpl::GetContentsResourceId(ResourceId* resource_id,
gfx::Size* resource_size) const {
// The bounds and the pile size may differ if the pile wasn't updated (ie.
// PictureLayer::Update didn't happen). In that case the pile will be empty.
DCHECK_IMPLIES(!raster_source_->GetSize().IsEmpty(),
bounds() == raster_source_->GetSize())
<< " bounds " << bounds().ToString() << " pile "
<< raster_source_->GetSize().ToString();
gfx::Rect content_rect(bounds());
PictureLayerTilingSet::CoverageIterator iter(
tilings_.get(), 1.f, content_rect, ideal_contents_scale_);
// Mask resource not ready yet.
if (!iter || !*iter) {
*resource_id = 0;
return;
}
// Masks only supported if they fit on exactly one tile.
DCHECK(iter.geometry_rect() == content_rect)
<< "iter rect " << iter.geometry_rect().ToString() << " content rect "
<< content_rect.ToString();
const TileDrawInfo& draw_info = iter->draw_info();
if (!draw_info.IsReadyToDraw() ||
draw_info.mode() != TileDrawInfo::RESOURCE_MODE) {
*resource_id = 0;
return;
}
*resource_id = draw_info.resource_id();
*resource_size = draw_info.resource_size();
}
void PictureLayerImpl::SetNearestNeighbor(bool nearest_neighbor) {
if (nearest_neighbor_ == nearest_neighbor)
return;
nearest_neighbor_ = nearest_neighbor;
NoteLayerPropertyChanged();
}
PictureLayerTiling* PictureLayerImpl::AddTiling(float contents_scale) {
DCHECK(CanHaveTilings());
DCHECK_GE(contents_scale, MinimumContentsScale());
DCHECK_LE(contents_scale, MaximumContentsScale());
DCHECK(raster_source_->HasRecordings());
return tilings_->AddTiling(contents_scale, raster_source_);
}
void PictureLayerImpl::RemoveAllTilings() {
tilings_->RemoveAllTilings();
// If there are no tilings, then raster scales are no longer meaningful.
ResetRasterScale();
}
void PictureLayerImpl::AddTilingsForRasterScale() {
// Reset all resolution enums on tilings, we'll be setting new values in this
// function.
tilings_->MarkAllTilingsNonIdeal();
PictureLayerTiling* high_res =
tilings_->FindTilingWithScale(raster_contents_scale_);
// We always need a high res tiling, so create one if it doesn't exist.
if (!high_res)
high_res = AddTiling(raster_contents_scale_);
// Try and find a low res tiling.
PictureLayerTiling* low_res = nullptr;
if (raster_contents_scale_ == low_res_raster_contents_scale_)
low_res = high_res;
else
low_res = tilings_->FindTilingWithScale(low_res_raster_contents_scale_);
// Only create new low res tilings when the transform is static. This
// prevents wastefully creating a paired low res tiling for every new high res
// tiling during a pinch or a CSS animation.
bool can_have_low_res = layer_tree_impl()->create_low_res_tiling();
bool needs_low_res = !low_res;
bool is_pinching = layer_tree_impl()->PinchGestureActive();
bool is_animating = draw_properties().screen_space_transform_is_animating;
if (can_have_low_res && needs_low_res && !is_pinching && !is_animating)
low_res = AddTiling(low_res_raster_contents_scale_);
// Set low-res if we have one.
if (low_res && low_res != high_res)
low_res->set_resolution(LOW_RESOLUTION);
// Make sure we always have one high-res (even if high == low).
high_res->set_resolution(HIGH_RESOLUTION);
if (layer_tree_impl()->IsPendingTree()) {
// On the pending tree, drop any tilings that are non-ideal since we don't
// need them to activate anyway.
tilings_->RemoveNonIdealTilings();
}
SanityCheckTilingState();
}
bool PictureLayerImpl::ShouldAdjustRasterScale() const {
if (was_screen_space_transform_animating_ !=
draw_properties().screen_space_transform_is_animating)
return true;
if (draw_properties().screen_space_transform_is_animating &&
raster_contents_scale_ != ideal_contents_scale_ &&
ShouldAdjustRasterScaleDuringScaleAnimations())
return true;
bool is_pinching = layer_tree_impl()->PinchGestureActive();
if (is_pinching && raster_page_scale_) {
// We change our raster scale when it is:
// - Higher than ideal (need a lower-res tiling available)
// - Too far from ideal (need a higher-res tiling available)
float ratio = ideal_page_scale_ / raster_page_scale_;
if (raster_page_scale_ > ideal_page_scale_ ||
ratio > kMaxScaleRatioDuringPinch)
return true;
}
if (!is_pinching) {
// When not pinching, match the ideal page scale factor.
if (raster_page_scale_ != ideal_page_scale_)
return true;
}
// Always match the ideal device scale factor.
if (raster_device_scale_ != ideal_device_scale_)
return true;
// When the source scale changes we want to match it, but not when animating
// or when we've fixed the scale in place.
if (!draw_properties().screen_space_transform_is_animating &&
!raster_source_scale_is_fixed_ &&
raster_source_scale_ != ideal_source_scale_)
return true;
if (raster_contents_scale_ > MaximumContentsScale())
return true;
if (raster_contents_scale_ < MinimumContentsScale())
return true;
return false;
}
void PictureLayerImpl::RecalculateRasterScales() {
float old_raster_contents_scale = raster_contents_scale_;
float old_raster_page_scale = raster_page_scale_;
float old_raster_source_scale = raster_source_scale_;
raster_device_scale_ = ideal_device_scale_;
raster_page_scale_ = ideal_page_scale_;
raster_source_scale_ = ideal_source_scale_;
raster_contents_scale_ = ideal_contents_scale_;
// If we're not animating, or leaving an animation, and the
// ideal_source_scale_ changes, then things are unpredictable, and we fix
// the raster_source_scale_ in place.
if (old_raster_source_scale &&
!draw_properties().screen_space_transform_is_animating &&
!was_screen_space_transform_animating_ &&
old_raster_source_scale != ideal_source_scale_)
raster_source_scale_is_fixed_ = true;
// TODO(danakj): Adjust raster source scale closer to ideal source scale at
// a throttled rate. Possibly make use of invalidation_.IsEmpty() on pending
// tree. This will allow CSS scale changes to get re-rastered at an
// appropriate rate. (crbug.com/413636)
if (raster_source_scale_is_fixed_) {
raster_contents_scale_ /= raster_source_scale_;
raster_source_scale_ = 1.f;
}
// During pinch we completely ignore the current ideal scale, and just use
// a multiple of the previous scale.
bool is_pinching = layer_tree_impl()->PinchGestureActive();
if (is_pinching && old_raster_contents_scale) {
// See ShouldAdjustRasterScale:
// - When zooming out, preemptively create new tiling at lower resolution.
// - When zooming in, approximate ideal using multiple of kMaxScaleRatio.
bool zooming_out = old_raster_page_scale > ideal_page_scale_;
float desired_contents_scale = old_raster_contents_scale;
if (zooming_out) {
while (desired_contents_scale > ideal_contents_scale_)
desired_contents_scale /= kMaxScaleRatioDuringPinch;
} else {
while (desired_contents_scale < ideal_contents_scale_)
desired_contents_scale *= kMaxScaleRatioDuringPinch;
}
raster_contents_scale_ = tilings_->GetSnappedContentsScale(
desired_contents_scale, kSnapToExistingTilingRatio);
raster_page_scale_ =
raster_contents_scale_ / raster_device_scale_ / raster_source_scale_;
}
// If we're not re-rasterizing during animation, rasterize at the maximum
// scale that will occur during the animation, if the maximum scale is
// known. However we want to avoid excessive memory use. If the scale is
// smaller than what we would choose otherwise, then it's always better off
// for us memory-wise. But otherwise, we don't choose a scale at which this
// layer's rastered content would become larger than the viewport.
if (draw_properties().screen_space_transform_is_animating &&
!ShouldAdjustRasterScaleDuringScaleAnimations()) {
bool can_raster_at_maximum_scale = false;
bool should_raster_at_starting_scale = false;
float maximum_scale = draw_properties().maximum_animation_contents_scale;
float starting_scale = draw_properties().starting_animation_contents_scale;
if (maximum_scale) {
gfx::Size bounds_at_maximum_scale = gfx::ToCeiledSize(
gfx::ScaleSize(raster_source_->GetSize(), maximum_scale));
int64 maximum_area = static_cast<int64>(bounds_at_maximum_scale.width()) *
static_cast<int64>(bounds_at_maximum_scale.height());
gfx::Size viewport = layer_tree_impl()->device_viewport_size();
int64 viewport_area = static_cast<int64>(viewport.width()) *
static_cast<int64>(viewport.height());
if (maximum_area <= viewport_area)
can_raster_at_maximum_scale = true;
}
if (starting_scale && starting_scale > maximum_scale) {
gfx::Size bounds_at_starting_scale = gfx::ToCeiledSize(
gfx::ScaleSize(raster_source_->GetSize(), starting_scale));
int64 start_area = static_cast<int64>(bounds_at_starting_scale.width()) *
static_cast<int64>(bounds_at_starting_scale.height());
gfx::Size viewport = layer_tree_impl()->device_viewport_size();
int64 viewport_area = static_cast<int64>(viewport.width()) *
static_cast<int64>(viewport.height());
if (start_area <= viewport_area)
should_raster_at_starting_scale = true;
}
// Use the computed scales for the raster scale directly, do not try to use
// the ideal scale here. The current ideal scale may be way too large in the
// case of an animation with scale, and will be constantly changing.
if (should_raster_at_starting_scale)
raster_contents_scale_ = starting_scale;
else if (can_raster_at_maximum_scale)
raster_contents_scale_ = maximum_scale;
else
raster_contents_scale_ = 1.f * ideal_page_scale_ * ideal_device_scale_;
}
raster_contents_scale_ =
std::max(raster_contents_scale_, MinimumContentsScale());
raster_contents_scale_ =
std::min(raster_contents_scale_, MaximumContentsScale());
DCHECK_GE(raster_contents_scale_, MinimumContentsScale());
DCHECK_LE(raster_contents_scale_, MaximumContentsScale());
// If this layer would create zero or one tiles at this content scale,
// don't create a low res tiling.
gfx::Size raster_bounds = gfx::ToCeiledSize(
gfx::ScaleSize(raster_source_->GetSize(), raster_contents_scale_));
gfx::Size tile_size = CalculateTileSize(raster_bounds);
bool tile_covers_bounds = tile_size.width() >= raster_bounds.width() &&
tile_size.height() >= raster_bounds.height();
if (tile_size.IsEmpty() || tile_covers_bounds) {
low_res_raster_contents_scale_ = raster_contents_scale_;
return;
}
float low_res_factor =
layer_tree_impl()->settings().low_res_contents_scale_factor;
low_res_raster_contents_scale_ =
std::max(raster_contents_scale_ * low_res_factor, MinimumContentsScale());
DCHECK_LE(low_res_raster_contents_scale_, raster_contents_scale_);
DCHECK_GE(low_res_raster_contents_scale_, MinimumContentsScale());
DCHECK_LE(low_res_raster_contents_scale_, MaximumContentsScale());
}
void PictureLayerImpl::CleanUpTilingsOnActiveLayer(
const std::vector<PictureLayerTiling*>& used_tilings) {
DCHECK(layer_tree_impl()->IsActiveTree());
if (tilings_->num_tilings() == 0)
return;
float min_acceptable_high_res_scale = std::min(
raster_contents_scale_, ideal_contents_scale_);
float max_acceptable_high_res_scale = std::max(
raster_contents_scale_, ideal_contents_scale_);
PictureLayerImpl* twin = GetPendingOrActiveTwinLayer();
if (twin && twin->CanHaveTilings()) {
min_acceptable_high_res_scale = std::min(
min_acceptable_high_res_scale,
std::min(twin->raster_contents_scale_, twin->ideal_contents_scale_));
max_acceptable_high_res_scale = std::max(
max_acceptable_high_res_scale,
std::max(twin->raster_contents_scale_, twin->ideal_contents_scale_));
}
PictureLayerTilingSet* twin_set = twin ? twin->tilings_.get() : nullptr;
tilings_->CleanUpTilings(
min_acceptable_high_res_scale, max_acceptable_high_res_scale,
used_tilings, layer_tree_impl()->create_low_res_tiling(), twin_set);
DCHECK_GT(tilings_->num_tilings(), 0u);
SanityCheckTilingState();
}
float PictureLayerImpl::MinimumContentsScale() const {
float setting_min = layer_tree_impl()->settings().minimum_contents_scale;
// If the contents scale is less than 1 / width (also for height),
// then it will end up having less than one pixel of content in that
// dimension. Bump the minimum contents scale up in this case to prevent
// this from happening.
int min_dimension = std::min(raster_source_->GetSize().width(),
raster_source_->GetSize().height());
if (!min_dimension)
return setting_min;
return std::max(1.f / min_dimension, setting_min);
}
float PictureLayerImpl::MaximumContentsScale() const {
// Masks can not have tilings that would become larger than the
// max_texture_size since they use a single tile for the entire
// tiling. Other layers can have tilings of any scale.
if (!is_mask_)
return std::numeric_limits<float>::max();
int max_texture_size =
layer_tree_impl()->resource_provider()->max_texture_size();
float max_scale_width =
static_cast<float>(max_texture_size) / bounds().width();
float max_scale_height =
static_cast<float>(max_texture_size) / bounds().height();
float max_scale = std::min(max_scale_width, max_scale_height);
// We require that multiplying the layer size by the contents scale and
// ceiling produces a value <= |max_texture_size|. Because for large layer
// sizes floating point ambiguity may crop up, making the result larger or
// smaller than expected, we use a slightly smaller floating point value for
// the scale, to help ensure that the resulting content bounds will never end
// up larger than |max_texture_size|.
return nextafterf(max_scale, 0.f);
}
void PictureLayerImpl::ResetRasterScale() {
raster_page_scale_ = 0.f;
raster_device_scale_ = 0.f;
raster_source_scale_ = 0.f;
raster_contents_scale_ = 0.f;
low_res_raster_contents_scale_ = 0.f;
raster_source_scale_is_fixed_ = false;
}
bool PictureLayerImpl::CanHaveTilings() const {
if (raster_source_->IsSolidColor())
return false;
if (!DrawsContent())
return false;
if (!raster_source_->HasRecordings())
return false;
// If the |raster_source_| has a recording it should have non-empty bounds.
DCHECK(!raster_source_->GetSize().IsEmpty());
if (MaximumContentsScale() < MinimumContentsScale())
return false;
return true;
}
void PictureLayerImpl::SanityCheckTilingState() const {
#if DCHECK_IS_ON()
if (!CanHaveTilings()) {
DCHECK_EQ(0u, tilings_->num_tilings());
return;
}
if (tilings_->num_tilings() == 0)
return;
// We should only have one high res tiling.
DCHECK_EQ(1, tilings_->NumHighResTilings());
#endif
}
bool PictureLayerImpl::ShouldAdjustRasterScaleDuringScaleAnimations() const {
return layer_tree_impl()->use_gpu_rasterization();
}
float PictureLayerImpl::MaximumTilingContentsScale() const {
float max_contents_scale = tilings_->GetMaximumContentsScale();
return std::max(max_contents_scale, MinimumContentsScale());
}
scoped_ptr<PictureLayerTilingSet>
PictureLayerImpl::CreatePictureLayerTilingSet() {
const LayerTreeSettings& settings = layer_tree_impl()->settings();
return PictureLayerTilingSet::Create(
GetTree(), this, settings.max_tiles_for_interest_area,
layer_tree_impl()->use_gpu_rasterization()
? settings.gpu_rasterization_skewport_target_time_in_seconds
: settings.skewport_target_time_in_seconds,
settings.skewport_extrapolation_limit_in_content_pixels);
}
void PictureLayerImpl::UpdateIdealScales() {
DCHECK(CanHaveTilings());
float min_contents_scale = MinimumContentsScale();
DCHECK_GT(min_contents_scale, 0.f);
ideal_page_scale_ = IsAffectedByPageScale()
? layer_tree_impl()->current_page_scale_factor()
: 1.f;
ideal_device_scale_ = layer_tree_impl()->device_scale_factor();
ideal_contents_scale_ =
std::max(draw_properties().ideal_contents_scale, min_contents_scale);
ideal_source_scale_ =
ideal_contents_scale_ / ideal_page_scale_ / ideal_device_scale_;
}
void PictureLayerImpl::GetDebugBorderProperties(
SkColor* color,
float* width) const {
*color = DebugColors::TiledContentLayerBorderColor();
*width = DebugColors::TiledContentLayerBorderWidth(layer_tree_impl());
}
void PictureLayerImpl::GetAllPrioritizedTilesForTracing(
std::vector<PrioritizedTile>* prioritized_tiles) const {
if (!tilings_)
return;
tilings_->GetAllPrioritizedTilesForTracing(prioritized_tiles);
}
void PictureLayerImpl::AsValueInto(
base::trace_event::TracedValue* state) const {
LayerImpl::AsValueInto(state);
state->SetDouble("ideal_contents_scale", ideal_contents_scale_);
state->SetDouble("geometry_contents_scale", MaximumTilingContentsScale());
state->BeginArray("tilings");
tilings_->AsValueInto(state);
state->EndArray();
MathUtil::AddToTracedValue("tile_priority_rect",
viewport_rect_for_tile_priority_in_content_space_,
state);
MathUtil::AddToTracedValue("visible_rect", visible_layer_rect(), state);
state->BeginArray("pictures");
raster_source_->AsValueInto(state);
state->EndArray();
state->BeginArray("invalidation");
invalidation_.AsValueInto(state);
state->EndArray();
state->BeginArray("coverage_tiles");
for (PictureLayerTilingSet::CoverageIterator iter(
tilings_.get(), 1.f, gfx::Rect(raster_source_->GetSize()),
ideal_contents_scale_);
iter; ++iter) {
state->BeginDictionary();
MathUtil::AddToTracedValue("geometry_rect", iter.geometry_rect(), state);
if (*iter)
TracedValue::SetIDRef(*iter, state, "tile");
state->EndDictionary();
}
state->EndArray();
}
size_t PictureLayerImpl::GPUMemoryUsageInBytes() const {
return tilings_->GPUMemoryUsageInBytes();
}
void PictureLayerImpl::RunMicroBenchmark(MicroBenchmarkImpl* benchmark) {
benchmark->RunOnLayer(this);
}
WhichTree PictureLayerImpl::GetTree() const {
return layer_tree_impl()->IsActiveTree() ? ACTIVE_TREE : PENDING_TREE;
}
bool PictureLayerImpl::IsOnActiveOrPendingTree() const {
return !layer_tree_impl()->IsRecycleTree();
}
bool PictureLayerImpl::HasValidTilePriorities() const {
return IsOnActiveOrPendingTree() && IsDrawnRenderSurfaceLayerListMember();
}
} // namespace cc
| bsd-3-clause |
verma/PDAL | src/drivers/caris/config.h | 2443 | /************************************************************************
* Copyright (c) 2012, CARIS
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of CARIS 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.
************************************************************************/
#ifndef INCLUDED_DRIVERS_CSAR_CONFIG_HPP
#define INCLUDED_DRIVERS_CSAR_CONFIG_HPP
#ifdef _MSC_VER
// disable msvc's "secure" and "deperated" warnings
# ifndef _CRT_SECURE_NO_WARNINGS
# define _CRT_SECURE_NO_WARNINGS
# endif
# ifndef _CRT_SECURE_NO_DEPRECATE
# define _CRT_SECURE_NO_DEPRECATE
# endif
# ifndef _AFX_SECURE_NO_WARNINGS
# define _AFX_SECURE_NO_WARNINGS
# endif
# ifndef _ATL_SECURE_NO_WARNINGS
# define _ATL_SECURE_NO_WARNINGS
# endif
# ifndef _SCL_SECURE_NO_WARNINGS
# define _SCL_SECURE_NO_WARNINGS
# endif
//! Warnings to disable when including 3rd party headers
# define DISABLED_3RDPARTY_WARNINGS 4244 4251 4267 4345 4503 4510 4512 4610 4701 4702
#endif
#endif
| bsd-3-clause |
devartis/Spree-Mercado-Pago-payment-method | spec/models/spree/mercado_pago/order_preferences_builder_spec.rb | 2062 | require 'spec_helper'
describe 'OrderPreferencesBuilder' do
# Factory order_with_line_items is incredibly slow..
let(:order) do
order = create :order
create_list :line_item, 2, order:order
order.line_items.reload
order.update!
order
end
let!(:adjustment) { order.adjustments.create! label: 'Descuento', amount:-10.0, order: order}
let(:payment) { create :payment }
let(:callback_urls) { {success: 'http://example.com/success', pending: 'http://example.com/pending', failure: 'http://example.com/failure'}}
let(:payer_data) { {email: '[email protected]'}}
include ActionView::Helpers::TextHelper
include ActionView::Helpers::SanitizeHelper
include Spree::ProductsHelper
context "Calling preferences_hash" do
subject { Spree::MercadoPago::OrderPreferencesBuilder.new(order, payment, callback_urls, payer_data).preferences_hash }
it 'should return external reference' do
expect(subject).to include(external_reference:payment.identifier)
end
it 'should set callback urls' do
expect(subject).to include(back_urls:callback_urls)
end
it 'should set payer data if brought' do
expect(subject).to include(payer: payer_data)
end
it 'should set an item for every line item' do
expect(subject).to include(:items)
order.line_items.each do |line_item|
expect(subject[:items]).to include({
title: line_item_description_text(line_item.variant.product.name),
unit_price: line_item.price.to_f,
quantity: line_item.quantity.to_f,
currency_id: 'ARS'
})
end
end
it 'should set its adjustments as items' do
expect(subject[:items]).to include({
title: line_item_description_text(adjustment.label),
unit_price: adjustment.amount.to_f,
quantity: 1,
currency_id: 'ARS'
})
end
it 'should only have line items and adjustments in items' do
expect(subject[:items]).to have(order.line_items.count + order.adjustments.count).items
end
end
end | bsd-3-clause |
MarginC/kame | netbsd/sys/lkm/compat/osf1/lkminit_emul.c | 2694 | /* $NetBSD: lkminit_emul.c,v 1.5 2001/11/12 23:23:04 lukem Exp $ */
/*-
* Copyright (c) 1996 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Michael Graff <[email protected]>.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the NetBSD
* Foundation, Inc. and its contributors.
* 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. 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 FOUNDATION OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <sys/cdefs.h>
__KERNEL_RCSID(0, "$NetBSD: lkminit_emul.c,v 1.5 2001/11/12 23:23:04 lukem Exp $");
#include <sys/param.h>
#include <sys/ioctl.h>
#include <sys/systm.h>
#include <sys/conf.h>
#include <sys/mount.h>
#include <sys/exec.h>
#include <sys/lkm.h>
#include <sys/file.h>
#include <sys/errno.h>
extern const struct emul emul_osf1;
int compat_osf1_lkmentry __P((struct lkm_table *, int, int));
/*
* declare the emulation
*/
MOD_COMPAT("compat_osf1", -1, &emul_osf1);
/*
* entry point
*/
int
compat_osf1_lkmentry(lkmtp, cmd, ver)
struct lkm_table *lkmtp;
int cmd;
int ver;
{
DISPATCH(lkmtp, cmd, ver, lkm_nofunc, lkm_nofunc, lkm_nofunc);
}
| bsd-3-clause |
FreeCodeCamp/FreeCodeCamp | curriculum/challenges/ukrainian/10-coding-interview-prep/project-euler/problem-356-largest-roots-of-cubic-polynomials.md | 971 | ---
id: 5900f4d01000cf542c50ffe3
title: 'Задача 356: Найбільші корені кубічних поліномів'
challengeType: 5
forumTopicId: 302016
dashedName: problem-356-largest-roots-of-cubic-polynomials
---
# --description--
Нехай an - найбільший дійсний корінь полінома $g(x) = x^3 - 2^n \times x^2 + n$.
Наприклад, $a_2 = 3.86619826\ldots$
Знайдіть останні вісім цифр $\displaystyle\sum_{i = 1}^{30} \lfloor {a_i}^{987654321}\rfloor$.
**Зверніть увагу:**$\lfloor a\rfloor$ представляє функцію підлога.
# --hints--
`rootsOfCubicPolynomials()` повинен повернути `28010159`.
```js
assert.strictEqual(rootsOfCubicPolynomials(), 28010159);
```
# --seed--
## --seed-contents--
```js
function rootsOfCubicPolynomials() {
return true;
}
rootsOfCubicPolynomials();
```
# --solutions--
```js
// solution required
```
| bsd-3-clause |
marcopompili/django-market | django_market/__init__.py | 94 |
#from django.conf import settings
#settings.INSTALLED_APPS += ("mptt", "hvad", "galleries",) | bsd-3-clause |
AndyMark/AMCrosslink-Java | src/com/andymark/crosslink/UpdateJaguarPacket.java | 811 | package com.andymark.crosslink;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public class UpdateJaguarPacket implements Message {
private short[] uiMode = new short[20];
private short[] uiSetVoltage = new short[20];
@Override
public ByteBuffer getMessage() {
for (int i = 16; i < 20; i++) {
uiMode[i] = (short) 0xffff;
}
uiSetVoltage[1] = (short) 0x1999;
ByteBuffer buffer = ByteBuffer.allocate(86);
buffer.order(ByteOrder.LITTLE_ENDIAN);
buffer.putShort((short) 0xaaa0); // sig
buffer.putShort((short) 86); // byte len
for (short val : uiMode) {
buffer.putShort(val);
}
for (short val : uiSetVoltage) {
buffer.putShort(val);
}
short checksum = (short) Utilities.checksum(buffer, 0, 84);
buffer.putShort(checksum);
return buffer;
}
}
| bsd-3-clause |
samsonasik/zf_111_support_php532_with_modulewizard | public/themes/zend_prj/js/modules/modules.js | 751 | function installthis(id)
{
var answer = confirm('Are you sure ? ');
if (answer){
//delete img...
$.post(base_url+'/zfmodules/index/installmod/id/'+id, function(data){
window.location.reload(false);
});
}
}
function installnotvalidthis(id)
{
var answer = confirm('Your module is not valid,\n if you continue, it\'s will be installed to another unique name,\n Are You sure ?');
if (answer){
//delete img...
$.post(base_url+'/zfmodules/index/installmodtovalid/id/'+id, function(data){
window.location.reload(false);
});
}
} | bsd-3-clause |
all-of-us/raw-data-repository | rdr_service/tools/tool_libs/backfill_gvcf_paths.py | 2248 | from rdr_service.model.genomics import GenomicGCValidationMetrics, GenomicSetMember
from rdr_service.tools.tool_libs.tool_base import cli_run, ToolBase
tool_cmd = 'backfill-gvcf'
tool_desc = 'Backfill the gVCF paths in genomic_gc_validation_metrics'
class GVcfBackfillTool(ToolBase):
def run(self):
super(GVcfBackfillTool, self).run()
# Get list of paths
path_list = self.get_paths_from_file()
for path in path_list:
sample_id = self.get_sample_id_from_gvcf_path(path)
metric = self.get_metric_from_sample_id(sample_id)
self.update_metric_gvcf_path(metric, path)
def get_paths_from_file(self):
path_set = set()
with open(self.args.input_file, encoding='utf-8-sig') as f:
lines = f.readlines()
for line in lines:
path_set.add(line.strip())
return list(path_set)
@staticmethod
def get_sample_id_from_gvcf_path(path):
# Based on naming convention:
# gs://prod-genomics-data-northwest/Wgs_sample_raw_data/
# SS_VCF_research/UW_A100329930_21055000718_702252_v1.hard-filtered.gvcf.gz
return path.split("_")[7]
def get_metric_from_sample_id(self, sample_id):
with self.get_session() as session:
return session.query(GenomicGCValidationMetrics).join(
GenomicSetMember,
GenomicSetMember.id == GenomicGCValidationMetrics.genomicSetMemberId
).filter(
GenomicSetMember.sampleId == sample_id
).one_or_none()
def update_metric_gvcf_path(self, metric, path):
if self.args.md5:
metric.gvcfMd5Received = 1
metric.gvcfMd5Path = path
else:
metric.gvcfReceived = 1
metric.gvcfPath = path
with self.get_session() as session:
session.merge(metric)
def add_additional_arguments(parser):
parser.add_argument('--input-file', required=True, help='path of text file with list of gVCF paths')
parser.add_argument('--md5', required=False, action="store_true", help='backfilling md5 files')
def run():
return cli_run(tool_cmd, tool_desc, GVcfBackfillTool, add_additional_arguments)
| bsd-3-clause |
jmnarloch/akka.js | akka-js-actor/js/src/main/scala/akka/actor/dungeon/DeathWatch.scala | 9120 | /**
* Copyright (C) 2009-2014 Typesafe Inc. <http://www.typesafe.com>
*/
package akka.actor.dungeon
import akka.actor.{ Terminated, InternalActorRef, ActorRef, ActorRefScope, ActorCell, Actor, Address }
import akka.dispatch.sysmsg.{ DeathWatchNotification, Watch, Unwatch }
import akka.event.Logging.{ Warning, Error, Debug }
import scala.util.control.NonFatal
import akka.actor.MinimalActorRef
/**
* @note IMPLEMENT IN SCALA.JS
*
import akka.event.AddressTerminatedTopic
*/
private[akka] trait DeathWatch { this: ActorCell ⇒
private var watching: Set[ActorRef] = ActorCell.emptyActorRefSet
private var watchedBy: Set[ActorRef] = ActorCell.emptyActorRefSet
private var terminatedQueued: Set[ActorRef] = ActorCell.emptyActorRefSet
override final def watch(subject: ActorRef): ActorRef = subject match {
case a: InternalActorRef ⇒
if (a != self && !watchingContains(a)) {
maintainAddressTerminatedSubscription(a) {
a.sendSystemMessage(Watch(a, self)) // ➡➡➡ NEVER SEND THE SAME SYSTEM MESSAGE OBJECT TO TWO ACTORS ⬅⬅⬅
watching += a
}
}
a
}
override final def unwatch(subject: ActorRef): ActorRef = subject match {
case a: InternalActorRef ⇒
if (a != self && watchingContains(a)) {
a.sendSystemMessage(Unwatch(a, self)) // ➡➡➡ NEVER SEND THE SAME SYSTEM MESSAGE OBJECT TO TWO ACTORS ⬅⬅⬅
maintainAddressTerminatedSubscription(a) {
watching = removeFromSet(a, watching)
}
}
terminatedQueued = removeFromSet(a, terminatedQueued)
a
}
protected def receivedTerminated(t: Terminated): Unit =
if (terminatedQueued(t.actor)) {
terminatedQueued -= t.actor // here we know that it is the SAME ref which was put in
receiveMessage(t)
}
/**
* When this actor is watching the subject of [[akka.actor.Terminated]] message
* it will be propagated to user's receive.
*/
protected def watchedActorTerminated(actor: ActorRef, existenceConfirmed: Boolean, addressTerminated: Boolean): Unit = {
if (watchingContains(actor)) {
maintainAddressTerminatedSubscription(actor) {
watching = removeFromSet(actor, watching)
}
if (!isTerminating) {
self.tell(Terminated(actor)(existenceConfirmed, addressTerminated), actor)
terminatedQueuedFor(actor)
}
}
if (childrenRefs.getByRef(actor).isDefined) handleChildTerminated(actor)
}
private[akka] def terminatedQueuedFor(subject: ActorRef): Unit =
terminatedQueued += subject
// TODO this should be removed and be replaced with `watching.contains(subject)`
// when all actor references have uid, i.e. actorFor is removed
private def watchingContains(subject: ActorRef): Boolean =
watching.contains(subject) || (subject.path.uid != ActorCell.undefinedUid &&
watching.contains(new UndefinedUidActorRef(subject)))
// TODO this should be removed and be replaced with `set - subject`
// when all actor references have uid, i.e. actorFor is removed
private def removeFromSet(subject: ActorRef, set: Set[ActorRef]): Set[ActorRef] =
if (subject.path.uid != ActorCell.undefinedUid) (set - subject) - new UndefinedUidActorRef(subject)
else set filterNot (_.path == subject.path)
protected def tellWatchersWeDied(): Unit =
if (!watchedBy.isEmpty) {
try {
// Don't need to send to parent parent since it receives a DWN by default
def sendTerminated(ifLocal: Boolean)(watcher: ActorRef): Unit =
if (watcher.asInstanceOf[ActorRefScope].isLocal == ifLocal && watcher != parent)
watcher.asInstanceOf[InternalActorRef].sendSystemMessage(DeathWatchNotification(self, existenceConfirmed = true, addressTerminated = false))
/*
* It is important to notify the remote watchers first, otherwise RemoteDaemon might shut down, causing
* the remoting to shut down as well. At this point Terminated messages to remote watchers are no longer
* deliverable.
*
* The problematic case is:
* 1. Terminated is sent to RemoteDaemon
* 1a. RemoteDaemon is fast enough to notify the terminator actor in RemoteActorRefProvider
* 1b. The terminator is fast enough to enqueue the shutdown command in the remoting
* 2. Only at this point is the Terminated (to be sent remotely) enqueued in the mailbox of remoting
*
* If the remote watchers are notified first, then the mailbox of the Remoting will guarantee the correct order.
*/
watchedBy foreach sendTerminated(ifLocal = false)
watchedBy foreach sendTerminated(ifLocal = true)
} finally watchedBy = ActorCell.emptyActorRefSet
}
protected def unwatchWatchedActors(actor: Actor): Unit =
if (!watching.isEmpty) {
maintainAddressTerminatedSubscription() {
try {
watching foreach { // ➡➡➡ NEVER SEND THE SAME SYSTEM MESSAGE OBJECT TO TWO ACTORS ⬅⬅⬅
case watchee: InternalActorRef ⇒ watchee.sendSystemMessage(Unwatch(watchee, self))
}
} finally {
watching = ActorCell.emptyActorRefSet
terminatedQueued = ActorCell.emptyActorRefSet
}
}
}
protected def addWatcher(watchee: ActorRef, watcher: ActorRef): Unit = {
val watcheeSelf = watchee == self
val watcherSelf = watcher == self
if (watcheeSelf && !watcherSelf) {
if (!watchedBy.contains(watcher)) maintainAddressTerminatedSubscription(watcher) {
watchedBy += watcher
if (system.settings.DebugLifecycle) publish(Debug(self.path.toString, clazz(actor), s"now watched by $watcher"))
}
} else if (!watcheeSelf && watcherSelf) {
watch(watchee)
} else {
publish(Warning(self.path.toString, clazz(actor), "BUG: illegal Watch(%s,%s) for %s".format(watchee, watcher, self)))
}
}
protected def remWatcher(watchee: ActorRef, watcher: ActorRef): Unit = {
val watcheeSelf = watchee == self
val watcherSelf = watcher == self
if (watcheeSelf && !watcherSelf) {
if (watchedBy.contains(watcher)) maintainAddressTerminatedSubscription(watcher) {
watchedBy -= watcher
if (system.settings.DebugLifecycle) publish(Debug(self.path.toString, clazz(actor), s"no longer watched by $watcher"))
}
} else if (!watcheeSelf && watcherSelf) {
unwatch(watchee)
} else {
publish(Warning(self.path.toString, clazz(actor), "BUG: illegal Unwatch(%s,%s) for %s".format(watchee, watcher, self)))
}
}
protected def addressTerminated(address: Address): Unit = {
// cleanup watchedBy since we know they are dead
maintainAddressTerminatedSubscription() {
for (a ← watchedBy; if a.path.address == address) watchedBy -= a
}
// send DeathWatchNotification to self for all matching subjects
// that are not child with existenceConfirmed = false because we could have been watching a
// non-local ActorRef that had never resolved before the other node went down
// When a parent is watching a child and it terminates due to AddressTerminated
// it is removed by sending DeathWatchNotification with existenceConfirmed = true to support
// immediate creation of child with same name.
for (a ← watching; if a.path.address == address) {
self.sendSystemMessage(DeathWatchNotification(a, existenceConfirmed = childrenRefs.getByRef(a).isDefined, addressTerminated = true))
}
}
/**
* Starts subscription to AddressTerminated if not already subscribing and the
* block adds a non-local ref to watching or watchedBy.
* Ends subscription to AddressTerminated if subscribing and the
* block removes the last non-local ref from watching and watchedBy.
*/
private def maintainAddressTerminatedSubscription[T](change: ActorRef = null)(block: ⇒ T): T = {
def isNonLocal(ref: ActorRef) = ref match {
case null ⇒ true
case a: InternalActorRef if !a.isLocal ⇒ true
case _ ⇒ false
}
if (isNonLocal(change)) {
def hasNonLocalAddress: Boolean = ((watching exists isNonLocal) || (watchedBy exists isNonLocal))
val had = hasNonLocalAddress
val result = block
val has = hasNonLocalAddress
if (had && !has) unsubscribeAddressTerminated()
else if (!had && has) subscribeAddressTerminated()
result
} else {
block
}
}
private def unsubscribeAddressTerminated(): Unit = {
/**
* @note IMPLEMENT IN SCALA.JS
*
AddressTerminatedTopic(system).unsubscribe(self)
*/
}
private def subscribeAddressTerminated(): Unit = {
/**
* @note IMPLEMENT IN SCALA.JS
*
AddressTerminatedTopic(system).subscribe(self)
*/
}
}
private[akka] class UndefinedUidActorRef(ref: ActorRef) extends MinimalActorRef {
override val path = ref.path.withUid(ActorCell.undefinedUid)
override def provider = throw new UnsupportedOperationException("UndefinedUidActorRef does not provide")
}
| bsd-3-clause |
ChromiumWebApps/chromium | tools/clang/blink_gc_plugin/BlinkGCPlugin.cpp | 2082 | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This clang plugin checks various invariants of the Blink garbage
// collection infrastructure.
//
// Checks that are implemented:
// [currently none]
#include "Config.h"
#include "clang/AST/AST.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendPluginRegistry.h"
using namespace clang;
using std::string;
namespace {
struct BlinkGCPluginOptions {
BlinkGCPluginOptions() {
}
};
// Main class containing checks for various invariants of the Blink
// garbage collection infrastructure.
class BlinkGCPluginConsumer : public ASTConsumer {
public:
BlinkGCPluginConsumer(CompilerInstance& instance,
const BlinkGCPluginOptions& options) {
}
virtual void HandleTranslationUnit(ASTContext& context) {
// FIXME: implement consistency checks.
}
};
class BlinkGCPluginAction : public PluginASTAction {
public:
BlinkGCPluginAction() {
}
protected:
// Overridden from PluginASTAction:
virtual ASTConsumer* CreateASTConsumer(CompilerInstance& instance,
llvm::StringRef ref) {
return new BlinkGCPluginConsumer(instance, options_);
}
virtual bool ParseArgs(const CompilerInstance& instance,
const std::vector<string>& args) {
bool parsed = true;
for (size_t i = 0; i < args.size() && parsed; ++i) {
if (args[i] == "enable-oilpan") {
// TODO: Remove this once all transition types are eliminated.
Config::set_oilpan_enabled(true);
} else {
parsed = false;
llvm::errs() << "Unknown blink-gc-plugin argument: " << args[i] << "\n";
}
}
return parsed;
}
private:
BlinkGCPluginOptions options_;
};
} // namespace
bool Config::oilpan_enabled_ = false;
static FrontendPluginRegistry::Add<BlinkGCPluginAction>
X("blink-gc-plugin", "Check Blink GC invariants");
| bsd-3-clause |
yonglehou/shuttle-scheduling | Shuttle.Scheduling/DataAccess/Queries/ScheduleQuery.cs | 703 | using Shuttle.Core.Data;
using Shuttle.Core.Infrastructure;
namespace Shuttle.Scheduling
{
public class ScheduleQuery : IScheduleQuery
{
private readonly IDatabaseGateway _databaseGateway;
private readonly IScheduleQueryFactory _queryFactory;
public ScheduleQuery(IDatabaseGateway databaseGateway, IScheduleQueryFactory queryFactory)
{
Guard.AgainstNull(databaseGateway, "databaseGateway");
Guard.AgainstNull(queryFactory, "queryFactory");
_databaseGateway = databaseGateway;
_queryFactory = queryFactory;
}
public bool HasScheduleStructures(DataSource source)
{
return _databaseGateway.GetScalarUsing<int>(source, _queryFactory.HasScheduleStructures()) == 1;
}
}
} | bsd-3-clause |
google-code/alkes | sample/01_application/TransformContents.h | 2096 | /*
* Copyright (c) 2010-2011, okazoh_tk. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef ALKES_SAMPLE_01_TRANSFORM_CONTENTS_H_INCLUDED_
#define ALKES_SAMPLE_01_TRANSFORM_CONTENTS_H_INCLUDED_
#include "alkes/graph.h"
class TransformContents
: public alkes::Scene
{
public:
TransformContents();
TransformContents(alkes::IGraphics2DDevice* graphics, alkes::ImageBuffer* image);
virtual ~TransformContents();
void construct(alkes::IGraphics2DDevice* graphics, alkes::ImageBuffer* image);
private:
alkes::ImageShapeNode image1_;
alkes::ImageShapeNode image2_;
};
#endif
| bsd-3-clause |
youtube/cobalt | cobalt/build/sync_to_build_id.py | 6399 | #!/usr/bin/python2
"""Syncs to a given Cobalt build id.
Syncs current gclient instance to a given build id, as
generated by "build_id.py" and stored on carbon-airlock-95823.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import json
import os
import shutil
import subprocess
import sys
import requests
_BUILD_ID_QUERY_URL = (
"https://carbon-airlock-95823.appspot.com/build_version/search")
_BUILD_ID_QUERY_PARAMETER_NAME = "build_number"
class SubprocessFailedException(Exception):
"""Exception for non-zero subprocess exits."""
def __init__(self, command):
super(SubprocessFailedException, self).__init__() # pylint: disable=super-with-arguments
self.command = command
def __str__(self):
return "Subprocess failed '{0}'".format(self.command)
def _RunGitCommand(gitargs, **kwargs):
"""Runs a git command with "gitargs", returning the output splitlines().
Args:
gitargs: Commandline args that follow 'git'.
**kwargs: Keyword args for Popen.
Returns:
All of stdout, as an array of lines.
Raises:
SubprocessFailedException: if the exit code is nonzero.
"""
result_tuple = _RunGitCommandReturnExitCode(gitargs, **kwargs)
if result_tuple[0] != 0:
raise SubprocessFailedException(" ".join(["git"] + gitargs))
return result_tuple[1]
def _RunGitCommandReturnExitCode(gitargs, **kwargs):
"""Runs a git command with "gitargs", returning the exit code and output.
Args:
gitargs: Commandline args that follow 'git'.
**kwargs: Keyword args for Popen.
Returns:
Tuple of (exit code, all of stdout as an array of lines).
"""
popen_args = ["git"] + gitargs
with subprocess.Popen(popen_args, stdout=subprocess.PIPE, **kwargs) as p:
output = p.stdout.read().splitlines()
return p.wait(), output
def main():
dev_null = open(os.devnull, "w") # pylint: disable=consider-using-with
arg_parser = argparse.ArgumentParser(
description="Syncs to a given Cobalt build id")
arg_parser.add_argument("buildid", nargs=1)
arg_parser.add_argument(
"--force",
default=False,
action="store_true",
help="Deletes directories that don't match the requested format.")
args = arg_parser.parse_args()
r = requests.get(
_BUILD_ID_QUERY_URL,
params={_BUILD_ID_QUERY_PARAMETER_NAME: args.buildid[0]})
if not r.ok:
print(
"HTTP request failed\n{0} {1}\n{2}".format(r.status_code, r.reason,
r.text),
file=sys.stderr)
return 1
# The response starts with a security-related close expression line
outer_json = json.loads(r.text.splitlines()[1])
hashes = json.loads(outer_json["deps"])
git_root = os.getcwd()
for relpath, rep_hash in hashes.items():
path = os.path.normpath(os.path.join(git_root, relpath))
if not os.path.exists(path):
# No warning in this case, we will attempt to clone the repository in
# the next pass through the repos.
continue
is_dirty = (
bool(
_RunGitCommandReturnExitCode(["diff", "--no-ext-diff", "--quiet"],
cwd=path,
stderr=dev_null)[0]) or
bool(
_RunGitCommandReturnExitCode(
["diff", "--no-ext-diff", "--quiet", "--cached"],
cwd=path,
stderr=dev_null)[0]))
if is_dirty:
print("{0} is dirty, please resolve".format(relpath))
return 1
(requested_repo, _) = rep_hash.split("@")
remote_url = _RunGitCommand(["config", "--get", "remote.origin.url"],
cwd=path)[0].strip().decode("utf-8")
if requested_repo.endswith(".git"):
if remote_url + ".git" == requested_repo:
print(("WARNING: You are syncing to {0} instead of {1}. While these "
"point to the same repo, the differing extension will cause "
"different build ids to be generated. If you need the same "
"id, you'll need to specifically clone {0} (note the .git "
"extension).").format(requested_repo, remote_url))
remote_url += ".git"
if remote_url != requested_repo:
if args.force and path != git_root:
shutil.rmtree(path)
else:
print(("{0} exists but does not point to the requested repo for that "
"path, {1}. Either replace that directory manually or run this "
"script with --force. --force will not try to remove the top "
"level repository.").format(path, requested_repo))
return 1
for relpath, rep_hash in hashes.items():
path = os.path.normpath(os.path.join(git_root, relpath))
# repo_hash has a repo path prefix like this:
# 'https://chromium.googlesource.com/chromium/llvm-project/libcxx.git
# @48198f9110397fff47fe7c37cbfa296be7d44d3d'
(requested_repo, requested_hash) = rep_hash.split("@")
if not os.path.exists(path):
print("Missing path {0}, cloning from {1}.".format(path, requested_repo))
try:
# The clone command will create all missing directories leading to the
# path. If the clone is successful, we continue on as usual and let
# the subsequent logic here checkout the appropriate git hash.
_RunGitCommand(["clone", "-q", requested_repo, path])
except SubprocessFailedException:
print("There was an error cloning the repository.")
continue
current_hash = _RunGitCommand(["rev-parse", "HEAD"], cwd=path)[0]
if requested_hash == current_hash:
continue
symbolic_ref = None
try:
symbolic_ref = _RunGitCommand(["symbolic-ref", "--short", "-q", "HEAD"],
cwd=path,
stderr=dev_null)[0]
except SubprocessFailedException:
pass
user_visible_commit = symbolic_ref if symbolic_ref else current_hash[0:7]
print("{0} was at {1} now {2}".format(path, user_visible_commit,
requested_hash[0:7]))
_RunGitCommand(["checkout", "-q", "--detach", requested_hash], cwd=path)
return 0
if __name__ == "__main__":
try:
sys.exit(main())
except SubprocessFailedException as ex:
print(str(ex), file=sys.stderr)
sys.exit(1)
| bsd-3-clause |
GCRC/nunaliit | nunaliit2-couch-command/src/main/java/ca/carleton/gcrc/couch/command/CommandUpgrade.java | 7080 | package ca.carleton.gcrc.couch.command;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.StringWriter;
import java.util.Calendar;
import org.json.JSONObject;
import org.json.JSONTokener;
import ca.carleton.gcrc.couch.command.impl.FileSetManifest;
import ca.carleton.gcrc.couch.command.impl.PathComputer;
import ca.carleton.gcrc.couch.command.impl.UpgradeOperations;
import ca.carleton.gcrc.couch.command.impl.UpgradeOperationsBasic;
import ca.carleton.gcrc.couch.command.impl.UpgradeOperationsNull;
import ca.carleton.gcrc.couch.command.impl.UpgradeOperationsReporting;
import ca.carleton.gcrc.couch.command.impl.UpgradeProcess;
import ca.carleton.gcrc.couch.command.impl.UpgradeReport;
import ca.carleton.gcrc.utils.StreamUtils;
public class CommandUpgrade implements Command {
@Override
public String getCommandString() {
return "upgrade";
}
@Override
public boolean matchesKeyword(String keyword) {
if( getCommandString().equalsIgnoreCase(keyword) ) {
return true;
}
return false;
}
@Override
public boolean isDeprecated() {
return false;
}
@Override
public String[] getExpectedOptions() {
return new String[]{
Options.OPTION_ATLAS_DIR
,Options.OPTION_NO_CONFIG
,Options.OPTION_TEST
};
}
@Override
public boolean requiresAtlasDir() {
return true;
}
@Override
public void reportHelp(PrintStream ps) {
ps.println("Nunaliit2 Atlas Framework - Upgrade Command");
ps.println();
ps.println("The upgrade command allows a user to modifies the files located in an atlas");
ps.println("so that they correspond to a different version of Nunaliit. This command");
ps.println("should be used when a newer version of Nunaliit is available and the");
ps.println("atlas creator wishes to use the newer version.");
ps.println();
ps.println("Command Syntax:");
ps.println(" nunaliit upgrade <options>");
ps.println();
ps.println("options:");
ps.println(" "+Options.OPTION_TEST);
ps.println(" Does not perform any changes. Simply print what would happen. Does ");
ps.println(" not run 'config' command.");
ps.println();
ps.println(" "+Options.OPTION_NO_CONFIG);
ps.println(" Supresses the automatic 'config' command after completing upgrade");
ps.println(" process.");
ps.println();
CommandHelp.reportGlobalOptions(ps,getExpectedOptions());
}
@Override
public void runCommand(
GlobalSettings gs
,Options options
) throws Exception {
if( options.getArguments().size() > 1 ){
throw new Exception("Unexpected argument: "+options.getArguments().get(1));
}
// Pick up options
boolean noConfig = false;
if( null != options.getNoConfig() ){
noConfig = options.getNoConfig().booleanValue();
}
boolean justTest = false;
if( null != options.getTest() ){
justTest = options.getTest().booleanValue();
}
File atlasDir = gs.getAtlasDir();
// Verify that content directory is available (contentDir includes new
// versions for files under docs and htdocs)
File contentDir = PathComputer.computeContentDir( gs.getInstallDir() );
if( null == contentDir
|| false == contentDir.exists()
|| false == contentDir.isDirectory() ){
throw new Exception("Unable to find content directory");
}
// Verify that the installation directory is available (installationFilesDir includes
// new versions of files under the templates directory. These are files that should not
// be upgraded, just installed once).
File installationFilesDir = PathComputer.computeTemplatesDir( gs.getInstallDir() );
if( null == installationFilesDir
|| false == installationFilesDir.exists()
|| false == installationFilesDir.isDirectory() ){
throw new Exception("Unable to find installation files directory");
}
// Compute upgrade directory
File upgradeCollisionDir = null;
{
Calendar calendar = Calendar.getInstance();
String name = String.format(
"upgrade_%04d-%02d-%02d_%02d:%02d:%02d"
,calendar.get(Calendar.YEAR)
,(calendar.get(Calendar.MONTH)+1)
,calendar.get(Calendar.DAY_OF_MONTH)
,calendar.get(Calendar.HOUR_OF_DAY)
,calendar.get(Calendar.MINUTE)
,calendar.get(Calendar.SECOND)
);
upgradeCollisionDir = new File(atlasDir, "upgrade/"+name);
}
// Figure out upgrade operations
UpgradeOperations operations = null;
if( justTest ) {
operations = new UpgradeOperationsNull();
} else {
operations = new UpgradeOperationsBasic(
atlasDir
,contentDir
,upgradeCollisionDir
);
}
// Figure out reporting level
UpgradeOperationsReporting reporting = new UpgradeOperationsReporting(
atlasDir
,upgradeCollisionDir
,operations
,gs.getOutStream()
);
if( justTest ) {
reporting.setReportOperations(true);
reporting.setReportCollisions(false);
}
// Compute installed file manifest
FileSetManifest installedFileSetManifest = new FileSetManifest();
try {
File configDir = new File(atlasDir,"config");
File manifestFile = new File(configDir,"nunaliit_manifest.json");
if( manifestFile.exists() ){
StringWriter sw = new StringWriter();
FileInputStream is = null;
InputStreamReader isr = null;
try {
is = new FileInputStream(manifestFile);
isr = new InputStreamReader(is, "UTF-8");
StreamUtils.copyStream(isr, sw);
sw.flush();
JSONTokener tokener = new JSONTokener(sw.toString());
Object result = tokener.nextValue();
if( result instanceof JSONObject ){
JSONObject jsonManifest = (JSONObject)result;
installedFileSetManifest = FileSetManifest.fromJSON(jsonManifest);
} else {
throw new Exception("Unexpected JSON found in manifext file: "+result.getClass().getName());
}
} catch (Exception e) {
throw new Exception("Error while reading file: "+manifestFile.getName(), e);
} finally {
if( null != isr ) {
try {
isr.close();
} catch (Exception e) {
// Ignore
}
}
if( null != is ) {
try {
is.close();
} catch (Exception e) {
// Ignore
}
}
}
}
} catch(Exception e) {
throw new Exception("Unable to load installed file manifest",e);
}
// Upgrade content
try {
UpgradeProcess upgradeProcess = new UpgradeProcess();
upgradeProcess.setUpgradedFilesDir(contentDir);
upgradeProcess.setInstallationFilesDir(installationFilesDir);
upgradeProcess.setTargetDir(atlasDir);
upgradeProcess.setInstalledManifest(installedFileSetManifest);
UpgradeReport upgradeReport = upgradeProcess.computeUpgrade();
UpgradeProcess.performUpgrade(
upgradeReport
,reporting
);
} catch(Exception e) {
throw new Exception("Unable to upgrade content",e);
}
// Perform configuration, unless disabled
if( false == noConfig && false == justTest ){
CommandConfig config = new CommandConfig();
Options configOptions = new Options();
config.runCommand(gs, configOptions);
}
}
}
| bsd-3-clause |
voidstart/ror_depot_reboot_1 | app/controllers/line_item_controller.rb | 53 | class LineItemController < ApplicationController
end
| bsd-3-clause |
bovee/Aston | README.md | 1287 | [](https://travis-ci.org/bovee/Aston/)
# Aston
Aston is a cross-platform, open source library for the analysis of chromatographic data. It's named for Francis William Aston, creator of the first fully functional mass spectrometer, and written using Python, Numpy, and Scipy. A graphical front-end is also available at https://github.com/bovee/AstonQt.
## Installation
Before you can use Aston, you must install Numpy and Scipy. Because these two packages contain C and Fortran code, installing via `pip` may be difficult (if you take this route, install them separately -- `pip install numpy` then `pip install scipy`) so I recommend installing them with your operating systems native facilities:
- Arch: `sudo pacman -Syu python-numpy python-scipy`
- Ubuntu/Debian: `sudo apt-get install python3-numpy python3-scipy`
- Mac OS X: `brew install numpy` and `brew install scipy` ( you will need Homebrew for this: http://brew.sh/ )
- Windows: graphical Anaconda installer @ https://www.continuum.io/downloads
Once these are installed, you can check that everything works by running the tests with `python setup.py test`.
## Usage
```python
from aston.tracefile import TraceFile
c = TraceFile('./test.cdf')
```
| bsd-3-clause |
hughsons/saltwaterfish | classes_bkp_0621.py | 19445 | from models import *
from django.db import connection
import collections
import time
import calendar
def GetCreditCardList(contactid):
cards_list = []
orders = Orders.objects.all().filter(ocustomerid = contactid)
cards_hash = {}
for order in orders:
if order.ocardno:
if order.ocardno not in cards_hash:
cards_hash[order.ocardno] = "Card Ending in %s" %order.ocardno[-4:]
# Preparing Cards List
cards_list = []
for key, value in cards_hash.items():
cards_list.append((key, value))
return cards_list
def GenerateShippingCalander():
month = [['', '', '','','', '', ''],
['', '', '','','', '', ''],
['', '', '','','', '', ''],
['', '', '','','', '', ''],
['', '', '','','', '', ''],
['', '', '','','', '', ''],
]
today = time.localtime().tm_mday
start_time = time.strptime("2013/06/01", "%Y/%m/01")
day = start_time.tm_mday
wday = start_time.tm_wday
last_day = calendar.monthrange(start_time.tm_year, start_time.tm_mon)[1]
row_no = 0
while day <= last_day:
cur_time = time.strptime(time.strftime("%Y/%m/" + str(day), start_time), "%Y/%m/%d")
day = cur_time.tm_mday
wday = cur_time.tm_wday
script = ''
bgcolor = "#FFFFFF"
if day < today:
bgcolor = "#999999"
elif day == today:
bgcolor = "#CC9966"
elif day == today + 1:
bgcolor = "#99CC00"
script = time.strftime("%m/" + str(day).zfill(2) + "/%Y", start_time)
elif day == today + 2:
bgcolor = "#663366"
script = time.strftime("%m/" + str(day).zfill(2) + "/%Y", start_time)
elif day > today + 2:
bgcolor = "#00CCCC"
script = time.strftime("%m/" + str(day).zfill(2) + "/%Y", start_time)
if day >= today:
if wday == 6:
bgcolor = "#DB9E9B"
script = ''
elif wday == 5:
script = time.strftime("%m/" + str(day).zfill(2) + "/%Y", start_time)
bgcolor = "#FFCC33"
day_hash = {'wday': wday, 'day': day, 'bgcolor':bgcolor, 'script':script}
month[row_no][wday] = day_hash
if wday == 6:
row_no += 1
day += 1
return month
def GetPriorityShippingCharge(category_id):
shipping_cat_obj = ShippingCategory.objects.filter(id = category_id, status='ACTIVE')[0]
return shipping_cat_obj.priority_shipping
def GetSaturdayShippingCharge(category_id):
shipping_cat_obj = ShippingCategory.objects.filter(id = category_id, status='ACTIVE')[0]
return shipping_cat_obj.saturday_delivery
def GetAlaskaShippingCharge(category_id):
shipping_cat_obj = ShippingCategory.objects.filter(id = category_id, status='ACTIVE')[0]
return shipping_cat_obj.alaska_delivery
class Error(object):
def __init__(self):
self.IsError = False
self._error_number = 0
self._error_message = ''
def RaiseError(self, p_message):
self.IsError = True
self._error_message = p_message
def Error(self):
self.IsError = False;
msg = self._error_message
self._error_message = ""
return msg
class StoreCredit(object):
def __init__(self):
self.id = 0
self.credit_value = 0.0
class MyShippingCategory(object):
def __init__(self):
self.id = -1
self.shipping_charge = 0.0
self.fuel_charge = 0.0
self.tax = 0.0
self.tax_value = 0.0
self.promotions = 0.0
self.shipping_value = 0.0
self.supplies_total = 0.0
self.freeshipping_diff = 0.0
self.shipping_items = []
class CartInfo(Error):
'''Holds final order summary of the Cart'''
def __init__(self):
super(CartInfo, self).__init__()
self.subtotal = 0.0
self.shipping_total = 0.0
self.fuelcharge_total = 0.0
self.tax_total = 0.0
self.promotions_total = 0
self.store_credit = 0.0
self.order_total = 0.0
self.is_storecredit_applied = False
self.store_credit_id = 0
self.store_credit = 0.0
self.cc_approval_code = ''
def ApplyStoreCredit(self, obj):
self.store_credit_id = obj.id
credit_value = obj.credit_value
self.store_credit = credit_value
if self.order_total >= self.store_credit:
self.order_total -= self.store_credit
self.store_credit = 0
elif self.order_total < self.store_credit and self.order_total > 0:
self.store_credit -= self.order_total
self.order_total = 0
def GetShippingCategoryID(self, catalog_id):
#pc_object = ProductCategory.objects.get(catalogid=catalog_id)
#psc_object = ProductShippingCategories.objects.get(product_category_id = pc_object.categoryid)
cursor = connection.cursor()
cursor.execute("SELECT psc.shipping_category_id, sc.category_name FROM product_shipping_categories psc "
"inner join product_category pc on (psc.product_category_id = pc.categoryid) "
"inner join shipping_category sc on (psc.shipping_category_id = sc.id)"
"where product_category_id in (SELECT categoryid FROM product_category WHERE catalogid = %d) " %catalog_id)
row = cursor.fetchone()
cursor.close()
shipping_category_id = row[0]
shipping_category_name = row[1]
return shipping_category_id, shipping_category_name
def Add(self, cart_dict, catalog_id):
items_dict = cart_dict # key is ItemID and value is CartItem object
if catalog_id in items_dict.keys():
cart_item = items_dict[catalog_id]
# Checking whether the one more item is allowed the the existing quantity.
if (cart_item.quantity + 1) > cart_item.qoh:
self.RaiseError("Quantity out of order. You can not add more items.")
return items_dict
cart_item.quantity += 1
items_dict[catalog_id] = cart_item
else:
cart_item = CartItem(catalog_id)
if cart_item.qoh <= 0:
self.RaiseError("Quantity is out of order")
return cart_dict
cart_item.shipping_category, cart_item.shipping_category_name = self.GetShippingCategoryID(catalog_id)
cart_item.quantity = 1
items_dict[catalog_id] = cart_item
return items_dict
def Delete(self, cart_dict, catalog_id):
del cart_dict[catalog_id]
return cart_dict
def Update(self, cart_dict, catalog_id, quantity):
cart_item = cart_dict[catalog_id]
if quantity <= 0:
self.RaiseError("Quantity should be greater than 0 or remove from cart")
return cart_dict
if quantity <= cart_item.qoh:
cart_item.quantity = quantity
else:
self.RaiseError("Quantity is out of order")
return cart_dict
return cart_dict
def GetOrderValue(self, cart_dict):
order_value = 0
for key, value in cart_dict.items():
value.CalculateTotals()
order_value += value.subtotal
return order_value
def GetShippingCharge(self, category_id, shipping_value, state, excluded_zip_codes):
shipping_charge = -1
fuel_charge = 0
free_shipping_diff = 0
shipping_cat_obj = ShippingCategory.objects.filter(id = category_id, status='ACTIVE')[0]
fuel_charge = shipping_cat_obj.fuel_charge
if shipping_cat_obj.is_free_shipping == 1:
# Return 0 as shipping charge and also get fuel charge as Tuple
shipping_charge = 0
return (shipping_charge, fuel_charge, free_shipping_diff)
if shipping_cat_obj.flatrate_shipping_charge > 0.0:
shipping_charge = shipping_cat_obj.flatrate_shipping_charge
return (shipping_charge, fuel_charge, free_shipping_diff)
# Fetching Rules.
shipping_charge_objs = ShippingCharges.objects.filter(shipping_category_id = category_id,
order_total_min__lte = shipping_value,
order_total_max__gte = shipping_value,
shipping_state = state)
# Calculating shipping charge as per the rules.
# If no rules, applying flat_rate shipping charge
if shipping_charge_objs:
shp_charge_obj = shipping_charge_objs[0]
shipping_charge = shp_charge_obj.shipping_charge
else:
shipping_charge = shp_charge_obj.flatrate_shipping_charge
# Calculating free shipping suggestion.
if shipping_charge > 0:
shipping_charge_objs = ShippingCharges.objects.filter(shipping_category_id = category_id,
shipping_charge = 0,
shipping_state = state)
if shipping_charge_objs:
shp_charge_obj = shipping_charge_objs[0]
free_shipping_diff = (shp_charge_obj.order_total_min - shipping_value)
else:
free_shipping_diff = 0
return (shipping_charge, fuel_charge, free_shipping_diff)
def GetItemsByShippingCategory(self, cart_dict):
items_dict = cart_dict
state = 'FL'
excluded_zips = []
tax_list = Tax.objects.filter(tax_country = 'US', tax_state = state)
if tax_list:
tax = tax_list[0].tax_value1
else:
tax = 7.0
# Dictionary contains shipping category id as a key and a list of items as values.
shipping_categories_dict = {}
shipping_cat_names_hash = {}
# Collecting Category wise Items
for key, item in items_dict.items():
item.CalculateTotals()
shipping_category_id = item.shipping_category
if item.shipping_category in shipping_categories_dict:
shipping_categories_dict[item.shipping_category].append(item)
else:
shipping_categories_dict[item.shipping_category] = [item]
shipping_cat_names_hash[item.shipping_category] = item.shipping_category_name
# Calculating Shipping Charge, Fuel Charge and Tax for each category
my_shipping_obj_list = []
for key, value in shipping_categories_dict.items():
shipping_category = MyShippingCategory()
shipping_category.id = key
shipping_category.name = shipping_cat_names_hash[key]
shipping_category.shipping_items = value
# Calculating Shipping Value
for item in shipping_category.shipping_items:
shipping_category.shipping_value += float(item.subtotal)
(shipping_category.shipping_charge, shipping_category.fuel_charge,
shipping_category.freeshipping_diff) = self.GetShippingCharge(shipping_category.id,
shipping_category.shipping_value,
state, excluded_zips)
shipping_category.tax = tax
shipping_category.tax_value = (shipping_category.shipping_value * shipping_category.tax)/100
shipping_category.supplies_total = (shipping_category.shipping_value +
shipping_category.shipping_charge +
shipping_category.fuel_charge +
shipping_category.tax_value -
shipping_category.promotions)
self.subtotal += shipping_category.shipping_value
self.shipping_total += shipping_category.shipping_charge
self.fuelcharge_total += shipping_category.fuel_charge
self.tax_total += shipping_category.tax_value
self.promotions_total += shipping_category.promotions
my_shipping_obj_list.append(shipping_category)
self.order_total = self.subtotal + self.shipping_total + self.fuelcharge_total + self.tax_total - self.promotions_total
# Applying Store Credit
#if self.is_storecredit_applied:
#od = collections.OrderedDict(sorted(shipping_categories_dict.items()))
return my_shipping_obj_list
def GetNumberOfItems(self, p_dict):
cart_dict = p_dict;
item_count = 0
for key, value in cart_dict.items():
item_count += value
return item_count
class CartItem(Error):
def __init__(self, item_id=None):
super(CartItem, self).__init__()
self.catalog_id = -1
self.item_name = ''
self.price = 0.0
self.saleprice = 0.0
self.quantity = 0
self.qoh = 0 # (Quantity on Hand)
self.shipping_category = 0
self.shipping_category_name = ''
self.shipping_charge = 0
self.tax_percent = 0.0
self.tax_value = 0.0
self.fuel_charge = 0.0
self.promotions = 0.0
self.is_reward_enabled = False
self.reward_points = 0
self.thumbnail = ''
self.image1 = ''
self.image2 = ''
self.image3 = ''
self.extra_fied_3 = ''
self.subtotal = 0.0
self.shipping_total = 0.0
self.fuel_charge_total = 0.0
self.promotions_total = 0.0
self.tax_total = 0.0
self.supplies_total = 0.0
if item_id:
self.FillItem(item_id)
return
def CalculateTotals(self):
if self.saleprice > 0:
self.subtotal = self.saleprice * self.quantity
else:
self.subtotal = self.price * self.quantity
self.shipping_total = 0.0
self.fuel_charge_total = 0.0
self.promotions_total = 0.0
self.tax_total = 0.0
self.supplies_total = 0.0
def FillItem(self, p_catalog_id):
'''Fills the current class object with the data fetched from the DB.
Returns: False if product not found.
'''
# Fetching product from the DB.
product_list = Products.objects.filter(catalogid=p_catalog_id)
if not product_list:
self.RaiseError("Item not found")
return False
product = product_list[0]
#product = Products()
self.catalog_id = product.catalogid
self.item_name = product.name
self.price = product.price
self.saleprice = product.saleprice
self.qoh = product.stock # (Quantity on Hand)
# No need to fill the values. Will be calculated for every category.
self.shipping_category = 0
self.shipping_charge = 0
self.tax_percent = 0.0
self.tax_value = 0.0
self.fuel_charge = 0.0
# Update this value when User is applied Coupon.
self.promotions = 0.0
if product.reward_disable == 1:
self.is_reward_enabled = False
else:
self.is_reward_enabled = True
self.reward_points = product.reward_points
self.thumbnail = product.thumbnail
self.image1 = product.image1
self.image2 = product.image2
self.image3 = product.image3
self.extra_fied_3 = product.extra_field_3
#self.subtotal = 0.0
#self.shipping_total = 0.0
#self.fuel_charge_total = 0.0
#self.promotions_total = 0.0
#self.tax_total = 0.0
#self.supplies_total = 0.0
def Set(self, p_catalog_id, p_item_name, p_price, p_saleprice, p_quantity,
p_qoh, p_shipping_category, p_shipping_charge, p_tax_percent,
p_fuel_charge, p_promotions, p_is_rewards_enabled,
p_reward_points, p_thumbnail, p_image1, p_image2, p_image3,
p_extra_field_3=""):
self.catalog_id = p_catalog_id
self.item_name = p_item_name
self.price = p_price
self.saleprice = p_saleprice
self.quantity = p_quantity
self.qoh = p_qoh # (Quantity on Hand)
self.shipping_category = p_shipping_category
self.shipping_charge = p_shipping_charge
self.tax_percent = p_tax_percent
self.fuel_charge = p_fuel_charge
self.promotions = p_promotions
self.is_reward_enabled = p_is_rewards_enabled
self.reward_points = p_reward_points
self.thumbnail = p_thumbnail
self.image1 = p_image1
self.image2 = p_image2
self.image3 = p_image3
self.extra_fied_3 = p_extra_fied_3
#
# self.id = id
# self.name = name
# self.quantity = quantity
# self.price = price
# self.saleprice = saleprice
# #self.fuelcharge = fuelcharge
# self.fuelcharge = 2.99 * quantity
# self.promotions = promotions
# if saleprice <= 0 :
# self.subtotal = price * quantity
# else:
# self.subtotal = saleprice * quantity
#
# self.shipping = shipping
# self.tax = tax
# self.taxvalue = float(self.subtotal) * float(tax)/float(100)
# self.total = float(self.subtotal) + float(shipping) + self.taxvalue + self.fuelcharge - self.promotions
# self.thumbnail = thumbnail
# self.image1 = image1
# self.image2 = image2
# self.image3 = image3
# self.extra_field_3 = extra_field_3
#
# if reward_disable == 0:
# self.reward_points = reward_points
# else:
# self.reward_points = 0
#
# product_category_list = ProductCategory.objects.filter(catalogid = id)
#
# logging.info(product_category_list[0].id)
# if product_category_list:
# category_id, category_name, parent_id = self.GetParentCategory(product_category_list[0].categoryid)
#
# (self.shipping, free_shipping_min_value) = self.GetShippingCharge(category_name, self.subtotal)
# self.free_shipping_suggestion_val = free_shipping_min_value - self.subtotal
#
#
# self.category_id = 0
# def GetParentCategory(self, category_id):
# #SELECT category_name, category_parent from category where id = 4
# cursor = connection.cursor()
# parent_id = 99999
# levels = 0
# while (parent_id > 0 and levels < 100):
# cursor.execute("SELECT id, category_name, category_parent from category where id = %d" %category_id)
# row = cursor.fetchone()
# category_id = row[0]
# category_name = row[1]
# parent_id = row[2]
# category_id = parent_id
# levels += 1
#
# return (category_id, category_name, parent_id)
#
# def GetShippingCharge(self, category_name, sub_total):
# shipping_charge = 0.0
# free_shipping_min_value = -1
# if category_name.__contains__('Marine Life'):
# free_shipping_min_value = 199
# if sub_total >= 00.01 and sub_total <= 98.99:
# shipping_charge = 34.99
# elif sub_total >= 99.00 and sub_total <= 198.99:
# shipping_charge = 24.99
# else:
# shipping_charge = 0
#
# elif category_name.__contains__('Live Goods'):
# free_shipping_min_value = 199
# if sub_total >= 00.01 and sub_total <= 98.99:
# shipping_charge = 34.99
# elif sub_total >= 99.00 and sub_total <= 198.99:
# shipping_charge = 24.99
# else:
# shipping_charge = 0
#
# elif category_name.__contains__('Live Rock & Sand'):
# free_shipping_min_value = 0
# if sub_total >= 00.01 and sub_total <= 98.99:
# shipping_charge = 4.99
# elif sub_total >= 99.00 and sub_total <= 198.99:
# shipping_charge = 4.99
# else:
# shipping_charge = 4.99
#
# elif category_name.__contains__('FastTrack Supplies'):
# free_shipping_min_value = 0
# if sub_total >= 00.01 and sub_total <= 98.99:
# shipping_charge = 4.99
# elif sub_total >= 99.00 and sub_total <= 198.99:
# shipping_charge = 4.99
# else:
# shipping_charge = 4.99
#
# elif category_name.__contains__('Aquarium Supplies On Sale'):
# free_shipping_min_value = 0
# if sub_total >= 00.01 and sub_total <= 98.99:
# shipping_charge = 4.99
# elif sub_total >= 99.00 and sub_total <= 198.99:
# shipping_charge = 4.99
# else:
# shipping_charge = 4.99
#
# return (shipping_charge, free_shipping_min_value)
| bsd-3-clause |
calee88/ParlAI | parlai/tasks/vqa_v2/build.py | 2271 | # Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
# Download and build the data if it does not exist.
import parlai.core.build_data as build_data
import os
def buildImage(opt):
dpath = os.path.join(opt['datapath'], 'COCO-IMG')
if not build_data.built(dpath):
print('[building image data: ' + dpath + ']')
build_data.remove_dir(dpath)
build_data.make_dir(dpath)
# download the image data.
fname1 = 'train2014.zip'
fname2 = 'val2014.zip'
fname3 = 'test2014.zip'
url = 'http://msvocds.blob.core.windows.net/coco2014/'
build_data.download(dpath, url + fname1)
build_data.download(dpath, url + fname2)
build_data.download(dpath, url + fname3)
build_data.untar(dpath, fname1, False)
build_data.untar(dpath, fname2, False)
build_data.untar(dpath, fname3, False)
# Mark the data as built.
build_data.mark_done(dpath)
def build(opt):
dpath = os.path.join(opt['datapath'], 'VQA-v2')
if not build_data.built(dpath):
print('[building data: ' + dpath + ']')
build_data.remove_dir(dpath)
build_data.make_dir(dpath)
# Download the data.
fname1 = 'v2_Questions_Train_mscoco.zip'
fname2 = 'v2_Questions_Val_mscoco.zip'
fname3 = 'v2_Questions_Test_mscoco.zip'
fname4 = 'v2_Annotations_Val_mscoco.zip'
fname5 = 'v2_Annotations_Train_mscoco.zip'
url = 'http://visualqa.org/data/mscoco/vqa/'
build_data.download(dpath, url + fname1)
build_data.download(dpath, url + fname2)
build_data.download(dpath, url + fname3)
build_data.download(dpath, url + fname4)
build_data.download(dpath, url + fname5)
build_data.untar(dpath, fname1)
build_data.untar(dpath, fname2)
build_data.untar(dpath, fname3)
build_data.untar(dpath, fname4)
build_data.untar(dpath, fname5)
# Mark the data as built.
build_data.mark_done(dpath)
| bsd-3-clause |
hfp/libxsmm | samples/deeplearning/sparse_weight_mult/parallel_sparse_weight_B_conv.c | 17192 | /******************************************************************************
* Copyright (c) Intel Corporation - All rights reserved. *
* This file is part of the LIBXSMM library. *
* *
* For information on the license, see the LICENSE file. *
* Further information: https://github.com/hfp/libxsmm/ *
* SPDX-License-Identifier: BSD-3-Clause *
******************************************************************************/
/* Alexander Heinecke (Intel Corp.)
******************************************************************************/
#include <libxsmm.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
void BlockSpMatStep1(int K, int C, int KB, int CB, int num_blocks,
unsigned int *colptr, unsigned int *rowidx, unsigned int *b_colptr[],
int *nnzb) {
int blk_idx, i, k;
for (blk_idx = 0; blk_idx < num_blocks; ++blk_idx) {
nnzb[blk_idx] = 0;
for (i = 0; i <= KB; ++i) {
b_colptr[blk_idx][i] = 0;
}
}
for (k = 0; k < K; ++k) {
int k_blk_idx = k / KB;
int k_blk_offset = k % KB;
unsigned colstart = colptr[k];
unsigned colend = colptr[k + 1];
for (i = colstart; i < (int)colend; ++i) {
int c = rowidx[i];
int c_blk_idx = c / CB;
blk_idx = k_blk_idx * C / CB + c_blk_idx;
nnzb[blk_idx]++;
b_colptr[blk_idx][k_blk_offset + 1]++;
}
}
for (blk_idx = 0; blk_idx < num_blocks; ++blk_idx) {
for (i = 0; i < KB; ++i) {
b_colptr[blk_idx][i + 1] += b_colptr[blk_idx][i];
}
}
}
void BlockSpMatStep2(int K, int C, int KB, int CB, int num_blocks,
unsigned int *colptr, unsigned int *rowidx, float *values,
unsigned int *b_colptr[], unsigned int *b_rowidx[],
float *b_values[]) {
int blk_idx, k, i;
for (k = 0; k < K; ++k) {
int k_blk_idx = k / KB;
int k_blk_offset = k % KB;
unsigned colstart = colptr[k];
unsigned colend = colptr[k + 1];
for (i = colstart; i < (int)colend; ++i) {
int c = rowidx[i];
int c_blk_idx = c / CB;
int c_blk_offset = c % CB;
blk_idx = k_blk_idx * C / CB + c_blk_idx;
b_rowidx[blk_idx][b_colptr[blk_idx][k_blk_offset]] = c_blk_offset;
b_values[blk_idx][b_colptr[blk_idx][k_blk_offset]] = values[i];
b_colptr[blk_idx][k_blk_offset]++;
}
}
for (blk_idx = 0; blk_idx < num_blocks; ++blk_idx) {
for (i = KB; i > 0; --i) {
b_colptr[blk_idx][i] = b_colptr[blk_idx][i - 1];
}
b_colptr[blk_idx][0] = 0;
}
}
int main(int argc, char **argv) {
int N = (argc > 1) ? atoi(argv[1]) : 32;
int H = (argc > 2) ? atoi(argv[2]) : 14;
int W = (argc > 3) ? atoi(argv[3]) : 14;
int C = (argc > 4) ? atoi(argv[4]) : 256;
int K = (argc > 5) ? atoi(argv[5]) : 256;
int R = (argc > 6) ? atoi(argv[6]) : 1;
int S = (argc > 7) ? atoi(argv[7]) : 1;
int padh = (argc > 8) ? atoi(argv[8]) : 0;
int padw = (argc > 9) ? atoi(argv[9]) : 0;
int sh = (argc > 10) ? atoi(argv[10]) : 1;
int sw = (argc > 11) ? atoi(argv[11]) : 1;
int NB = (argc > 12) ? atoi(argv[12]) : 32;
int CB = (argc > 13) ? atoi(argv[13]) : 32;
int KB = (argc > 14) ? atoi(argv[14]) : 32;
int nb = (argc > 15) ? atoi(argv[15]) : 16;
double sparse_frac = (argc > 16) ? atof(argv[16]) : 0.90;
unsigned int REPS = (argc > 17) ? atoi(argv[17]) : 10;
if ( CB > C ) {
CB = C;
}
if ( KB > K ) {
KB = K;
}
if (N < NB ||
H < 1 ||
W < 1 ||
K < KB ||
C < CB ||
R < 1 ||
S < 1 ||
sh < 1 ||
sw < 1 ||
padh < 0 ||
padw < 0 ||
NB < nb ||
C % CB != 0 ||
N % NB != 0 ||
nb % 16 != 0 ||
NB % nb != 0 ||
sparse_frac <= 0.0 ||
sparse_frac >= 1.0 ||
REPS <= 0) {
return -1;
}
int l_n, l_h, l_w, l_p, l_q, l_c, l_r, l_s, l_nn, l_cc, l_nnn, l_k, l_kk, blk_idx;
int i, k, n, c;
int P = (H + 2*padh - R)/sh + 1;
int Q = (W + 2*padw - S)/sw + 1;
libxsmm_gemm_prefetch_type prefetch = LIBXSMM_GEMM_PREFETCH_NONE;
int flags = LIBXSMM_GEMM_FLAGS('N', 'N');
float *l_A = (float *)libxsmm_aligned_malloc(sizeof(float) * N * H * W * C, 64);
float *l_B = (float *)libxsmm_aligned_malloc(sizeof(float) * R * S * C * K, 64);
float *l_C = (float *)libxsmm_aligned_malloc(sizeof(float) * N * P * Q * K, 64);
float *l_C_gold =
(float *)libxsmm_aligned_malloc(sizeof(float) * N * P * Q * K, 64);
LIBXSMM_VLA_DECL(7, float, l_p_A, l_A, H, W, C / CB, NB / nb, CB, nb);
LIBXSMM_VLA_DECL(4, float, l_p_B, l_B, S, K, C);
LIBXSMM_VLA_DECL(7, float, l_p_C, l_C, P, Q, K / KB, NB / nb, KB, nb);
LIBXSMM_VLA_DECL(7, float, l_p_C_gold, l_C_gold, P, Q, K / KB, NB / nb, KB, nb);
/* print sizes */
printf("Sparse Convolution kernel FWD\n");
printf("N: %i, H:%i, W: %i, C: %i, K: %i, P: %i, Q: %i, R: %i, S: %i, sh: %i, sw: %i, padh: %i, padw: %i\n", N, H, W, C, K, P, Q, R, S, sh, sw, padh, padw);
/* touch A */
for (l_n = 0; l_n < N / NB; ++l_n) {
for (l_h = 0; l_h < H; ++l_h) {
for (l_w = 0; l_w < W; ++l_w) {
for (l_c = 0; l_c < C / CB; ++l_c) {
for (l_nn = 0; l_nn < NB / nb; ++l_nn) {
for (l_cc = 0; l_cc < CB; ++l_cc) {
for (l_nnn = 0; l_nnn < nb; ++l_nnn) {
LIBXSMM_VLA_ACCESS(7, l_p_A, l_n, l_h, l_w, l_c, l_nn, l_cc,
l_nnn, H, W, C / CB, NB / nb, CB, nb) =
(float)libxsmm_rng_f64();
}
}
}
}
}
}
}
/* touch dense B and init sparse B*/
/* we use [R][S][K][C] layout */
int nnz = 0;
int *rsnnz = (int*)libxsmm_aligned_malloc( R * S * sizeof(int), 64 );
unsigned int *colptr = (unsigned int *)libxsmm_aligned_malloc(
R * S * (K + 1) * sizeof(unsigned int), 64);
LIBXSMM_VLA_DECL(3, unsigned int, l_p_colptr, colptr, S, K+1);
LIBXSMM_VLA_DECL(2, int, l_p_rsnnz, rsnnz, S);
/* fill in dense and global CSC */
for (l_r = 0; l_r < R; l_r++) {
for (l_s = 0; l_s < S; l_s++) {
LIBXSMM_VLA_ACCESS(3, l_p_colptr, l_r, l_s, 0, S, K+1) = 0;
LIBXSMM_VLA_ACCESS(2, l_p_rsnnz, l_r, l_s, S) = 0;
for (l_k = 0; l_k < K; l_k++) {
LIBXSMM_VLA_ACCESS(3, l_p_colptr, l_r, l_s, l_k+1, S, K+1) = 0;
for (l_c = 0; l_c < C; l_c++) {
double tmp = libxsmm_rng_f64();
if (tmp < sparse_frac) {
tmp = 0.0;
} else {
LIBXSMM_VLA_ACCESS(2, l_p_rsnnz, l_r, l_s, S) = LIBXSMM_VLA_ACCESS(2, l_p_rsnnz, l_r, l_s, S) + 1;
LIBXSMM_VLA_ACCESS(3, l_p_colptr, l_r, l_s, l_k+1, S, K+1) = LIBXSMM_VLA_ACCESS(3, l_p_colptr, l_r, l_s, l_k+1, S, K+1)+1;
nnz++;
}
LIBXSMM_VLA_ACCESS(4, l_p_B, l_r, l_s, l_k, l_c, S, K, C) = (float)tmp;
}
}
for (l_k = 0; l_k < K; l_k++) {
LIBXSMM_VLA_ACCESS(3, l_p_colptr, l_r, l_s, l_k+1, S, K+1) += LIBXSMM_VLA_ACCESS(3, l_p_colptr, l_r, l_s, l_k, S, K+1);
}
}
}
/* alloc sparse structure */
unsigned int *rowidx =
(unsigned int *)libxsmm_aligned_malloc(nnz * sizeof(unsigned int), 64);
float *values = (float *)libxsmm_aligned_malloc(nnz * sizeof(float), 64);
int proc_nnz = 0;
for (l_r = 0; l_r < R; ++l_r) {
for (l_s = 0; l_s < S; ++l_s) {
unsigned int *l_rowidx = rowidx + proc_nnz;
float* l_values = values + proc_nnz;
for (l_k = 0; l_k < K; l_k++) {
int offset = LIBXSMM_VLA_ACCESS(3, l_p_colptr, l_r, l_s, l_k, S, K+1);
for (l_c = 0; l_c < C; l_c++) {
if (LIBXSMM_VLA_ACCESS(4, l_p_B, l_r, l_s, l_k, l_c, S, K, C) != 0) {
l_rowidx[offset] = l_c;
l_values[offset] = LIBXSMM_VLA_ACCESS(4, l_p_B, l_r, l_s, l_k, l_c, S, K, C);
offset++;
}
}
}
proc_nnz += LIBXSMM_VLA_ACCESS(2, l_p_rsnnz, l_r, l_s, S);
}
}
unsigned num_k_blocks = K / KB;
unsigned num_c_blocks = C / CB;
int num_blocks = num_k_blocks * num_c_blocks;
int RSnum_blocks = R * S * num_blocks;
unsigned int **b_colptr = (unsigned int **)libxsmm_aligned_malloc(
RSnum_blocks * sizeof(unsigned int *), 64);
unsigned int **b_rowidx = (unsigned int **)libxsmm_aligned_malloc(
RSnum_blocks * sizeof(unsigned int *), 64);
float **b_values =
(float **)libxsmm_aligned_malloc( RSnum_blocks * sizeof(float *), 64);
int *nnzb = (int *)libxsmm_aligned_malloc( RSnum_blocks * sizeof(int), 64);
for (blk_idx = 0; blk_idx < RSnum_blocks; ++blk_idx) {
b_colptr[blk_idx] = (unsigned int *)libxsmm_aligned_malloc(
(KB + 1) * sizeof(unsigned int), 64);
}
int offset = 0;
proc_nnz = 0;
for (l_r = 0; l_r < R; ++l_r) {
for (l_s = 0; l_s < S; ++l_s) {
offset = (l_r*S)+l_s;
BlockSpMatStep1(K, C, KB, CB, num_blocks, &LIBXSMM_VLA_ACCESS(3, l_p_colptr, l_r, l_s, 0, S, K+1), rowidx + proc_nnz, b_colptr+(offset*num_blocks), nnzb+(offset*num_blocks));
proc_nnz += LIBXSMM_VLA_ACCESS(2, l_p_rsnnz, l_r, l_s, S);
}
}
for (blk_idx = 0; blk_idx < RSnum_blocks; ++blk_idx) {
b_rowidx[blk_idx] = (unsigned int *)libxsmm_aligned_malloc(
nnzb[blk_idx] * sizeof(unsigned int), 64);
b_values[blk_idx] =
(float *)libxsmm_aligned_malloc(nnzb[blk_idx] * sizeof(float), 64);
}
offset = 0;
proc_nnz = 0;
for (l_r = 0; l_r < R; ++l_r) {
for (l_s = 0; l_s < S; ++l_s) {
offset = (l_r*S)+l_s;
BlockSpMatStep2(K, C, KB, CB, num_blocks, &LIBXSMM_VLA_ACCESS(3, l_p_colptr, l_r, l_s, 0, S, K+1), rowidx + proc_nnz, values + proc_nnz,
b_colptr+(offset*num_blocks), b_rowidx+(offset*num_blocks), b_values+(offset*num_blocks));
proc_nnz += LIBXSMM_VLA_ACCESS(2, l_p_rsnnz, l_r, l_s, S);
}
}
/* touch C */
for (l_n = 0; l_n < N / NB; ++l_n) {
for (l_p = 0; l_p < P; ++l_p) {
for (l_q = 0; l_q < Q; ++l_q) {
for (l_k = 0; l_k < K / KB; ++l_k) {
for (l_nn = 0; l_nn < NB / nb; ++l_nn) {
for (l_kk = 0; l_kk < KB; ++l_kk) {
for (l_nnn = 0; l_nnn < nb; ++l_nnn) {
LIBXSMM_VLA_ACCESS(7, l_p_C_gold, l_n, l_p, l_q, l_k, l_nn, l_kk,
l_nnn, P, Q, K / KB, NB / nb, KB, nb) =
0.0f;
LIBXSMM_VLA_ACCESS(7, l_p_C, l_n, l_p, l_q, l_k, l_nn, l_kk,
l_nnn, P, Q, K / KB, NB / nb, KB, nb) =
0.0f;
}
}
}
}
}
}
}
/* dense routine */
for (l_n = 0; l_n < N / NB; ++l_n) {
for (l_p = 0; l_p < P; ++l_p) {
l_h = l_p*sh - padh;
for (l_q = 0; l_q < Q; ++l_q) {
l_w = l_q*sw - padw;
for (l_k = 0; l_k < K / KB; ++l_k) {
for (l_c = 0; l_c < C / CB; ++l_c) {
for (l_r = 0; l_r < R; ++l_r) {
if ( l_h+l_r < 0 || l_h+l_r >= H ) continue;
for (l_s = 0; l_s < S; ++l_s) {
if ( l_w+l_s < 0 || l_w+l_s >= W ) continue;
for (l_nn = 0; l_nn < NB / nb; ++l_nn) {
for (l_kk = 0; l_kk < KB; ++l_kk) {
k = l_k * KB + l_kk;
for (l_cc = 0; l_cc < CB; ++l_cc) {
c = l_c * CB + l_cc;
for (l_nnn = 0; l_nnn < nb; ++l_nnn) {
LIBXSMM_VLA_ACCESS(7, l_p_C_gold, l_n, l_p, l_q, l_k,
l_nn, l_kk, l_nnn, P, Q, K / KB, NB / nb, KB, nb) +=
LIBXSMM_VLA_ACCESS(7, l_p_A, l_n, l_h+l_r, l_w+l_s, l_c,
l_nn, l_cc, l_nnn, H, W, C / CB, NB / nb, CB, nb) *
LIBXSMM_VLA_ACCESS(4, l_p_B, l_r, l_s, k, c, S, K, C);
}
}
}
}
}
}
}
}
}
}
}
/* FWD */
float alpha = 1.0;
float beta = 1.0;
libxsmm_descriptor_blob l_xgemm_blob;
libxsmm_gemm_descriptor **l_xgemm_desc =
(libxsmm_gemm_descriptor **)libxsmm_aligned_malloc(
RSnum_blocks * sizeof(libxsmm_gemm_descriptor *), 64);
libxsmm_smmfunction *mykernel =
(libxsmm_smmfunction *)libxsmm_aligned_malloc(
RSnum_blocks * sizeof(libxsmm_smmfunction), 64);
for (blk_idx = 0; blk_idx < RSnum_blocks; ++blk_idx) {
l_xgemm_desc[blk_idx] = libxsmm_gemm_descriptor_dinit(
&l_xgemm_blob, LIBXSMM_DATATYPE(float), NB / nb, KB, CB, CB,
0, KB, alpha, beta, flags, prefetch);
mykernel[blk_idx] =
libxsmm_create_packed_spxgemm_csc(l_xgemm_desc[blk_idx], nb, b_colptr[blk_idx],
b_rowidx[blk_idx],
(const void *)b_values[blk_idx]).smm;
}
#ifdef _OPENMP
# pragma omp parallel for LIBXSMM_OPENMP_COLLAPSE(4) private(k,n,c,l_p,l_q,l_h,l_w,l_r,l_s)
#endif
for (k = 0; k < K / KB; ++k) {
for (n = 0; n < N / NB; ++n) {
for (l_p = 0; l_p < P; ++l_p) {
for (l_q = 0; l_q < Q; ++l_q) {
l_h = l_p*sh - padh;
l_w = l_q*sw - padw;
for (l_r = 0; l_r < R; ++l_r) {
if ( l_h+l_r < 0 || l_h+l_r >= H ) continue;
for (l_s = 0; l_s < S; ++l_s) {
if ( l_w+l_s < 0 || l_w+l_s >= W ) continue;
for (c = 0; c < C / CB; ++c) {
mykernel[l_r * S * (K/KB) * (C/CB) + l_s * (K/KB * C/CB) + k * (C/CB) + c](&(LIBXSMM_VLA_ACCESS(7, l_p_A, n, l_h+l_r, l_w+l_s, c, 0, 0, 0, H, W, C / CB, NB / nb, CB, nb)),
b_values[l_r * S * (K/KB) * (C/CB) + l_s * (K/KB * C/CB) + k * (C/CB) + c],
&(LIBXSMM_VLA_ACCESS(7, l_p_C, n, l_p, l_q, k, 0, 0, 0, P, Q, K / KB, NB / nb, KB, nb)) );
}
}
}
}
}
}
}
/* check error */
float l_max_error = 0.0f;
for (i = 0; i < N * P * Q * K; ++i) {
if (fabs(l_C[i] - l_C_gold[i]) > l_max_error) {
l_max_error = (float)fabs(l_C[i] - l_C_gold[i]);
}
}
printf("max error = %f\n", l_max_error);
/* check performace */
unsigned long long l_start = libxsmm_timer_tick();
for (i = 0; i < (int)REPS; ++i) {
#ifdef _OPENMP
# pragma omp parallel for LIBXSMM_OPENMP_COLLAPSE(4) private(k,n,c,l_p,l_q,l_h,l_w,l_r,l_s)
#endif
for (k = 0; k < K / KB; ++k) {
for (n = 0; n < N / NB; ++n) {
for (l_p = 0; l_p < P; ++l_p) {
for (l_q = 0; l_q < Q; ++l_q) {
l_h = l_p*sh - padh;
l_w = l_q*sw - padw;
for (l_r = 0; l_r < R; ++l_r) {
if ( l_h+l_r < 0 || l_h+l_r >= H ) continue;
for (l_s = 0; l_s < S; ++l_s) {
if ( l_w+l_s < 0 || l_w+l_s >= W ) continue;
for (c = 0; c < C / CB; ++c) {
mykernel[l_r * S * (K/KB) * (C/CB) + l_s * (K/KB * C/CB) + k * (C/CB) + c](&(LIBXSMM_VLA_ACCESS(7, l_p_A, n, l_h+l_r, l_w+l_s, c, 0, 0, 0, H, W, C / CB, NB / nb, CB, nb)),
b_values[l_r * S * (K/KB) * (C/CB) + l_s * (K/KB * C/CB) + k * (C/CB) + c],
&(LIBXSMM_VLA_ACCESS(7, l_p_C, n, l_p, l_q, k, 0, 0, 0, P, Q, K / KB, NB / nb, KB, nb)) );
}
}
}
}
}
}
}
}
unsigned long long l_end = libxsmm_timer_tick();
double l_total = libxsmm_timer_duration(l_start, l_end);
printf("%fs for sparse (asm)\n", l_total);
printf("%f GFLOPS for sparse (asm)\n",
((double)((double)REPS * (double)N * (double)P * (double)Q * (double)C * (double)R * (double)S *(double)K) * 2.0) /
(l_total * 1.0e9));
/* clean up */
libxsmm_free(l_A);
libxsmm_free(l_B);
libxsmm_free(l_C);
libxsmm_free(l_C_gold);
for (blk_idx = 0; blk_idx < RSnum_blocks; ++blk_idx) {
libxsmm_free(b_values[blk_idx]);
libxsmm_free(b_colptr[blk_idx]);
libxsmm_free(b_rowidx[blk_idx]);
}
libxsmm_free(b_values);
libxsmm_free(b_colptr);
libxsmm_free(b_rowidx);
return 0;
}
| bsd-3-clause |
danielsiebra/projeto_e_profissional | app/controllers/[scope]/registrations_controller.rb | 1404 | class [scope]::RegistrationsController < Devise::RegistrationsController
# before_action :configure_sign_up_params, only: [:create]
# before_action :configure_account_update_params, only: [:update]
# GET /resource/sign_up
# def new
# super
# end
# POST /resource
# def create
# super
# end
# GET /resource/edit
# def edit
# super
# end
# PUT /resource
# def update
# super
# end
# DELETE /resource
# def destroy
# super
# end
# GET /resource/cancel
# Forces the session data which is usually expired after sign
# in to be expired now. This is useful if the user wants to
# cancel oauth signing in/up in the middle of the process,
# removing all OAuth session data.
# def cancel
# super
# end
# protected
# If you have extra params to permit, append them to the sanitizer.
# def configure_sign_up_params
# devise_parameter_sanitizer.permit(:sign_up, keys: [:attribute])
# end
# If you have extra params to permit, append them to the sanitizer.
# def configure_account_update_params
# devise_parameter_sanitizer.permit(:account_update, keys: [:attribute])
# end
# The path used after sign up.
# def after_sign_up_path_for(resource)
# super(resource)
# end
# The path used after sign up for inactive accounts.
# def after_inactive_sign_up_path_for(resource)
# super(resource)
# end
end
| bsd-3-clause |
LawnGnome/php-radius | tests/radius_cvt_string.phpt | 262 | --TEST--
radius_cvt_string()
--INI--
display_errors=1
error_reporting=22527
--SKIPIF--
<?php
if (!extension_loaded('radius')) echo 'SKIP: radius extension required';
?>
--FILE--
<?php
var_dump(radius_cvt_string('127.0.0.1'));
?>
--EXPECT--
string(9) "127.0.0.1"
| bsd-3-clause |
bereznev/yii2-blog | common/models/articles/Article.php | 5780 | <?php
namespace common\models\articles;
use common\models\behaviors\HiddenBehavior;
use common\models\scopes\ArticleScope;
use common\models\traits\CacheTrait;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\data\ActiveDataProvider;
use yii\helpers\ArrayHelper;
use yii\helpers\HtmlPurifier;
use common\models\User;
/**
* This is the model class for table "a_article".
*
* @property integer $id
* @property integer $user_id
* @property string $title
* @property string $description
* @property string $text
* @property integer $status
* @property integer $hidden
* @property integer $created_at
* @property integer $updated_at
*
* @property Category[] $categories
* @property User $user
*/
class Article extends \yii\db\ActiveRecord
{
use CacheTrait;
public $categoriesNames;
/**
* @inheritdoc
*/
public static function tableName()
{
return 'a_article';
}
/**
* @inheritdoc
*/
public static function find()
{
return new ArticleScope(get_called_class());
}
/**
* @inheritdoc
*/
public function behaviors()
{
return [
TimestampBehavior::className(),
HiddenBehavior::className(),
];
}
// values attribute 'status'
const STATUS_NEW = 5;
const STATUS_ON_MODERATION = 10;
const STATUS_DELETED = 15;
const STATUS_APPROVED = 20;
/**
* Available list of statuses attribute "status"
* or get status name by index
* @param null $index
* @return array|string
*/
public static function statuses($index = null)
{
$statuses = [
self::STATUS_NEW => 'New',
self::STATUS_ON_MODERATION => 'Moderation',
self::STATUS_DELETED => 'Deleted',
self::STATUS_APPROVED => 'Approved',
];
if ($index !== null) {
if (!empty($statuses[$index])) {
return $statuses[$index];
} else {
return 'error status';
}
} else {
return $statuses;
}
}
/**
* Relation many-to-many. Article-Categories
* @return $this
*/
public function getCategories()
{
return $this->hasMany(Category::className(), ['id' => 'category_id'])
->viaTable(ArticleCategory::tableName(), ['article_id' => 'id']);
}
/**
* Relation User
* @return $this
*/
public function getUser()
{
return $this->hasOne(User::className(), ['id' => 'user_id']);
}
// scenarios
const SCENARIO_MODERATION = 'scenario_moderation';
const SCENARIO_AUTHOR_UPDATE = 'scenario_author_update';
const SCENARIO_SEARCH = 'scenario_search';
/**
* @inheritdoc
*/
public function rules()
{
return [
[['user_id', 'title', 'description', 'text', 'hidden'], 'required', 'except' => self::SCENARIO_SEARCH],
[['user_id'], 'integer'],
['status', 'integer', 'on' => self::SCENARIO_MODERATION],
['status', 'in', 'range' => array_keys(self::statuses()), 'on' => self::SCENARIO_MODERATION],
[['title', 'description'], 'string', 'max' => 255],
['text', 'filter', 'filter' => function ($html) {
return HtmlPurifier::process($html);
}],
['categoriesNames', 'safe']
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'user_id' => 'User ID',
'title' => 'Title',
'description' => 'Description',
'text' => 'Text',
'status' => 'Status',
'hidden' => 'Hidden',
'created_at' => 'Created At',
'updated_at' => 'Updated At',
];
}
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params)
{
$query = self::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
if(!Yii::$app->getUser()->can('articleUpdate', $this)) {
$query->approvedOrMy();
}
$query->visibleOrMy();
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'id' => $this->id,
'user_id' => $this->user_id,
'status' => $this->status,
]);
$query->andFilterWhere(['like', 'title', $this->title])
->andFilterWhere(['like', 'description', $this->description])
->andFilterWhere(['like', 'text', $this->text]);
return $dataProvider;
}
/**
* Get access update article
* @return bool
*/
public function isEditAvailable()
{
return Yii::$app->user->can('articleUpdateOwner', $this) || Yii::$app->user->can('articleUpdate', $this);
}
/**
* @inheritdoc
*/
public function afterFind()
{
$categoriesArticle = $this->categories;
if ($categoriesArticle) {
$this->categoriesNames = array_flip(ArrayHelper::map($categoriesArticle, 'id', 'name'));
}
parent::afterFind();
}
/**
* @inheritdoc
*/
public function afterSave($insert, $changedAttributes)
{
$articleCategories = ArticleCategory::getCache(ArticleCategory::find()
->where(['article_id' => $this->id])
->indexBy('category_id'), false);
$transaction = Yii::$app->db->beginTransaction();
try {
ArticleCategory::deleteAll([
'category_id' => array_diff_key($articleCategories, $this->categoriesNames),
'article_id' => $this->id
]);
$addedCategories = array_diff_key($this->categoriesNames, $articleCategories);
$insertData = [];
foreach ($addedCategories as $addedCategoryId) {
$insertData[] = [
'article_id' => $this->id,
'category_id' => $addedCategoryId,
];
}
if (!empty($insertData)) {
Yii::$app->db->createCommand()
->batchInsert(ArticleCategory::tableName(), array_keys($insertData[0]), $insertData)
->execute();
}
ArticleCategory::onInvalidateCache();
$transaction->commit();
} catch (\Exception $e) {
$transaction->rollBack();
throw $e;
}
parent::afterSave($insert, $changedAttributes);
}
}
| bsd-3-clause |
zostera/django-modeltrans | modeltrans/fields.py | 12105 | from django.core.exceptions import ImproperlyConfigured
from django.db.models import F, fields
from django.db.models.functions import Cast, Coalesce
from django.utils.translation import gettext_lazy as _
from .conf import get_default_language, get_fallback_chain, get_modeltrans_setting
from .utils import (
FallbackTransform,
build_localized_fieldname,
get_instance_field_value,
get_language,
)
try:
# django==3.1 moved JSONField into django.db.models
from django.db.models import JSONField
from django.db.models.fields.json import KeyTextTransform
except ImportError:
from django.contrib.postgres.fields import JSONField
from django.contrib.postgres.fields.jsonb import KeyTextTransform
SUPPORTED_FIELDS = (fields.CharField, fields.TextField)
DEFAULT_LANGUAGE = get_default_language()
def translated_field_factory(original_field, language=None, *args, **kwargs):
if not isinstance(original_field, SUPPORTED_FIELDS):
raise ImproperlyConfigured(
"{} is not supported by django-modeltrans.".format(original_field.__class__.__name__)
)
class Specific(TranslatedVirtualField, original_field.__class__):
pass
Specific.__name__ = "Translated{}".format(original_field.__class__.__name__)
return Specific(original_field, language, *args, **kwargs)
class TranslatedVirtualField:
"""
A field representing a single field translated to a specific language.
Arguments:
original_field: The original field to be translated
language: The language to translate to, or `None` to track the current active Django language.
"""
# Implementation inspired by HStoreVirtualMixin from:
# https://github.com/djangonauts/django-hstore/blob/master/django_hstore/virtual.py
def __init__(self, original_field, language=None, *args, **kwargs):
# TODO: this feels like a big hack.
self.__dict__.update(original_field.__dict__)
self.original_field = original_field
self.language = language
self.blank = kwargs["blank"]
self.null = kwargs["null"]
self.concrete = False
self._help_text = kwargs.pop("help_text", None)
@property
def original_name(self):
return self.original_field.name
@property
def help_text(self):
if self._help_text is not None:
return self._help_text
if get_modeltrans_setting("MODELTRANS_ADD_FIELD_HELP_TEXT") and self.language is None:
return _("current language: {}").format(get_language())
def contribute_to_class(self, cls, name):
self.model = cls
self.attname = name
self.name = name
self.column = None
# Use a translated verbose name:
translated_field_name = _(self.original_field.verbose_name)
if self.language is not None:
translated_field_name += " ({})".format(self.language.upper())
self.verbose_name = translated_field_name
setattr(cls, name, self)
cls._meta.add_field(self, private=True)
def db_type(self, connection):
return None
def get_instance_fallback_chain(self, instance, language):
"""
Return the fallback chain for the instance.
Most of the time, it is just the configured fallback chain, but if the per-record-fallback feature
is used, the value of the field is added (if not None).
"""
default = get_fallback_chain(language)
i18n_field = instance._meta.get_field("i18n")
if i18n_field.fallback_language_field:
record_fallback_language = get_instance_field_value(
instance, i18n_field.fallback_language_field
)
if record_fallback_language:
return (record_fallback_language, *default)
return default
def __get__(self, instance, instance_type=None):
# This method is apparently called with instance=None from django.
# django-hstor raises AttributeError here, but that doesn't solve our problem.
if instance is None:
return
if "i18n" in instance.get_deferred_fields():
raise ValueError(
"Getting translated values on a model fetched with defer('i18n') is not supported."
)
language = self.get_language()
original_value = getattr(instance, self.original_name)
if language == DEFAULT_LANGUAGE and original_value:
return original_value
# Make sure we test for containment in a dict, not in None
if instance.i18n is None:
instance.i18n = {}
field_name = build_localized_fieldname(self.original_name, language)
# Just return the value if this is an explicit field (<name>_<lang>)
if self.language is not None:
return instance.i18n.get(field_name)
# This is the _i18n version of the field, and the current language is not available,
# so we walk the fallback chain:
for fallback_language in (language,) + self.get_instance_fallback_chain(instance, language):
if fallback_language == DEFAULT_LANGUAGE:
if original_value:
return original_value
else:
continue
field_name = build_localized_fieldname(self.original_name, fallback_language)
if field_name in instance.i18n and instance.i18n[field_name]:
return instance.i18n.get(field_name)
# finally, return the original field if all else fails.
return getattr(instance, self.original_name)
def __set__(self, instance, value):
if instance.i18n is None:
instance.i18n = {}
language = self.get_language()
if language == DEFAULT_LANGUAGE:
setattr(instance, self.original_name, value)
else:
field_name = build_localized_fieldname(self.original_name, language)
# if value is None, remove field from `i18n`.
if value is None:
instance.i18n.pop(field_name, None)
else:
instance.i18n[field_name] = value
def get_field_name(self):
"""
Returns the field name for the current virtual field.
The field name is ``<original_field_name>_<language>`` in case of a specific
translation or ``<original_field_name>_i18n`` for the currently active language.
"""
if self.language is None:
lang = "i18n"
else:
lang = self.get_language()
return build_localized_fieldname(self.original_name, lang)
def get_language(self):
"""
Returns the language for this field.
In case of an explicit language (title_en), it returns "en", in case of
`title_i18n`, it returns the currently active Django language.
"""
return self.language if self.language is not None else get_language()
def output_field(self):
"""
The type of field used to Cast/Coalesce to.
Mainly because a max_length argument is required for CharField
until this PR is merged: https://github.com/django/django/pull/8758
"""
Field = self.original_field.__class__
if isinstance(self.original_field, fields.CharField):
return Field(max_length=self.original_field.max_length)
return Field()
def _localized_lookup(self, language, bare_lookup):
if language == DEFAULT_LANGUAGE:
return bare_lookup.replace(self.name, self.original_name)
# When accessing a table directly, the i18_lookup will be just "i18n", while following relations
# they are in the lookup first.
i18n_lookup = bare_lookup.replace(self.name, "i18n")
# To support per-row fallback languages, an F-expression is passed as language parameter.
if isinstance(language, F):
# abuse build_localized_fieldname without language to get "<field>_"
field_prefix = build_localized_fieldname(self.original_name, "")
return FallbackTransform(field_prefix, language, i18n_lookup)
else:
return KeyTextTransform(
build_localized_fieldname(self.original_name, language), i18n_lookup
)
def as_expression(self, bare_lookup, fallback=True):
"""
Compose an expression to get the value for this virtual field in a query.
"""
language = self.get_language()
if language == DEFAULT_LANGUAGE:
return F(self._localized_lookup(language, bare_lookup))
if not fallback:
i18n_lookup = self._localized_lookup(language, bare_lookup)
return Cast(i18n_lookup, self.output_field())
fallback_chain = get_fallback_chain(language)
# First, add the current language to the list of lookups
lookups = [self._localized_lookup(language, bare_lookup)]
# Optionnally add the lookup for the per-row fallback language
i18n_field = self.model._meta.get_field("i18n")
if i18n_field.fallback_language_field:
lookups.append(
self._localized_lookup(F(i18n_field.fallback_language_field), bare_lookup)
)
# and now, add the list of fallback languages to the lookup list
for fallback_language in fallback_chain:
lookups.append(self._localized_lookup(fallback_language, bare_lookup))
return Coalesce(*lookups, output_field=self.output_field())
class TranslationField(JSONField):
"""
This model field is used to store the translations in the translated model.
Arguments:
fields (iterable): List of model field names to make translatable.
required_languages (iterable or dict): List of languages required for the model.
If a dict is supplied, the keys must be translated field names with the value
containing a list of required languages for that specific field.
virtual_fields (bool): If `False`, do not add virtual fields to access
translated values with.
Set to `True` during migration from django-modeltranslation to prevent
collisions with it's database fields while having the `i18n` field available.
fallback_language_field: If not None, this should be the name of the field containing a
language code to use as the first language in any fallback chain.
For example: if you have a model instance with 'nl' as language_code, and set
fallback_language_field='language_code', 'nl' will always be tried after the current
language before any other language.
"""
description = "Translation storage for a model"
def __init__(
self,
fields=None,
required_languages=None,
virtual_fields=True,
fallback_language_field=None,
*args,
**kwargs,
):
self.fields = fields or ()
self.required_languages = required_languages or ()
self.virtual_fields = virtual_fields
self.fallback_language_field = fallback_language_field
kwargs["editable"] = False
kwargs["null"] = True
super().__init__(*args, **kwargs)
def deconstruct(self):
name, path, args, kwargs = super().deconstruct()
del kwargs["editable"]
del kwargs["null"]
kwargs["fields"] = self.fields
kwargs["required_languages"] = self.required_languages
kwargs["virtual_fields"] = self.virtual_fields
return name, path, args, kwargs
def get_translated_fields(self):
"""Return a generator for all translated fields."""
for field in self.model._meta.get_fields():
if isinstance(field, TranslatedVirtualField):
yield field
def contribute_to_class(self, cls, name):
if name != "i18n":
raise ImproperlyConfigured('{} must have name "i18n"'.format(self.__class__.__name__))
super().contribute_to_class(cls, name)
| bsd-3-clause |
NCIP/cabio | software/cabio-database/scripts/sql_loader/no_longer_used/constraints/zstg_gene2go.disable.sql | 622 | /*L
Copyright SAIC
Distributed under the OSI-approved BSD 3-Clause License.
See http://ncip.github.com/cabio/LICENSE.txt for details.
L*/
alter table ZSTG_GENE2GO disable constraint SYS_C0029509;
alter table ZSTG_GENE2GO disable constraint SYS_C0029510;
alter table ZSTG_GENE2GO disable constraint SYS_C0029511;
alter table ZSTG_GENE2GO disable constraint SYS_C0029512;
alter table ZSTG_GENE2GO disable constraint SYS_C0029513;
alter table ZSTG_GENE2GO disable constraint SYS_C0029514;
alter table ZSTG_GENE2GO disable constraint SYS_C0029515;
alter table ZSTG_GENE2GO disable constraint SYS_C0029516;
--EXIT;
| bsd-3-clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.