code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "mojo/public/cpp/bindings/lib/bindings_serialization.h" #include "mojo/public/cpp/bindings/lib/bindings_internal.h" #include "mojo/public/cpp/bindings/lib/bounds_checker.h" #include "mojo/public/cpp/bindings/lib/validation_errors.h" #include "mojo/public/cpp/environment/logging.h" namespace mojo { namespace internal { namespace { const size_t kAlignment = 8; template<typename T> T AlignImpl(T t) { return t + (kAlignment - (t % kAlignment)) % kAlignment; } } // namespace size_t Align(size_t size) { return AlignImpl(size); } char* AlignPointer(char* ptr) { return reinterpret_cast<char*>(AlignImpl(reinterpret_cast<uintptr_t>(ptr))); } bool IsAligned(const void* ptr) { return !(reinterpret_cast<uintptr_t>(ptr) % kAlignment); } void EncodePointer(const void* ptr, uint64_t* offset) { if (!ptr) { *offset = 0; return; } const char* p_obj = reinterpret_cast<const char*>(ptr); const char* p_slot = reinterpret_cast<const char*>(offset); MOJO_DCHECK(p_obj > p_slot); *offset = static_cast<uint64_t>(p_obj - p_slot); } const void* DecodePointerRaw(const uint64_t* offset) { if (!*offset) return NULL; return reinterpret_cast<const char*>(offset) + *offset; } bool ValidateEncodedPointer(const uint64_t* offset) { // Cast to uintptr_t so overflow behavior is well defined. return reinterpret_cast<uintptr_t>(offset) + *offset >= reinterpret_cast<uintptr_t>(offset); } void EncodeHandle(Handle* handle, std::vector<Handle>* handles) { if (handle->is_valid()) { handles->push_back(*handle); handle->set_value(static_cast<MojoHandle>(handles->size() - 1)); } else { handle->set_value(kEncodedInvalidHandleValue); } } void DecodeHandle(Handle* handle, std::vector<Handle>* handles) { if (handle->value() == kEncodedInvalidHandleValue) { *handle = Handle(); return; } MOJO_DCHECK(handle->value() < handles->size()); // Just leave holes in the vector so we don't screw up other indices. *handle = FetchAndReset(&handles->at(handle->value())); } bool ValidateStructHeader(const void* data, uint32_t min_num_bytes, uint32_t min_num_fields, BoundsChecker* bounds_checker) { MOJO_DCHECK(min_num_bytes >= sizeof(StructHeader)); if (!IsAligned(data)) { ReportValidationError(VALIDATION_ERROR_MISALIGNED_OBJECT); return false; } if (!bounds_checker->IsValidRange(data, sizeof(StructHeader))) { ReportValidationError(VALIDATION_ERROR_ILLEGAL_MEMORY_RANGE); return false; } const StructHeader* header = static_cast<const StructHeader*>(data); // TODO(yzshen): Currently our binding code cannot handle structs of smaller // size or with fewer fields than the version that it sees. That needs to be // changed in order to provide backward compatibility. if (header->num_bytes < min_num_bytes || header->num_fields < min_num_fields) { ReportValidationError(VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER); return false; } if (!bounds_checker->ClaimMemory(data, header->num_bytes)) { ReportValidationError(VALIDATION_ERROR_ILLEGAL_MEMORY_RANGE); return false; } return true; } } // namespace internal } // namespace mojo
7kbird/chrome
mojo/public/cpp/bindings/lib/bindings_serialization.cc
C++
bsd-3-clause
3,424
using Orchard.ContentManagement.MetaData; using Orchard.Core.Contents.Extensions; using Orchard.Data.Migration; namespace Orchard.CustomForms { public class Migrations : DataMigrationImpl { public int Create() { ContentDefinitionManager.AlterTypeDefinition("CustomForm", cfg => cfg .WithPart("CommonPart") .WithPart("TitlePart") .WithPart("AutoroutePart", builder => builder .WithSetting("AutorouteSettings.AllowCustomPattern", "true") .WithSetting("AutorouteSettings.AutomaticAdjustmentOnEdit", "false") .WithSetting("AutorouteSettings.PatternDefinitions", "[{Name:'Title', Pattern: '{Content.Slug}', Description: 'my-form'}]") .WithSetting("AutorouteSettings.DefaultPatternIndex", "0")) .WithPart("MenuPart") .WithPart("CustomFormPart") .DisplayedAs("Custom Form") .Draftable() ); SchemaBuilder.CreateTable("CustomFormPartRecord", table => table.ContentPartVersionRecord() .Column<string>("ContentType", c => c.WithLength(255)) .Column<bool>("CustomMessage") .Column<string>("Message", c => c.Unlimited()) .Column<bool>("Redirect") .Column<string>("RedirectUrl", c => c.Unlimited()) .Column<bool>("SaveContentItem") ); return 1; } public int UpdateFrom1() { ContentDefinitionManager.AlterTypeDefinition("CustomFormWidget", cfg => cfg .WithPart("WidgetPart") .WithPart("CommonPart") .WithPart("IdentityPart") .WithPart("CustomFormPart") .WithSetting("Stereotype", "Widget") ); return 2; } public void Uninstall() { ContentDefinitionManager.DeleteTypeDefinition("CustomForm"); } } }
leonhaft/LearnOrchard
src/Orchard.Web/Modules/Orchard.CustomForms/Migrations.cs
C#
bsd-3-clause
2,131
/**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2008-2010 Ricardo Quesada http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "CCLabelTTF.h" #include "CCDirector.h" #include "shaders/CCGLProgram.h" #include "shaders/CCShaderCache.h" #include "CCApplication.h" NS_CC_BEGIN #if CC_USE_LA88_LABELS #define SHADER_PROGRAM kCCShader_PositionTextureColor #else #define SHADER_PROGRAM kCCShader_PositionTextureA8Color #endif // //CCLabelTTF // CCLabelTTF::CCLabelTTF() : m_hAlignment(kCCTextAlignmentCenter) , m_vAlignment(kCCVerticalTextAlignmentTop) , m_pFontName(NULL) , m_fFontSize(0.0) , m_string("") , m_shadowEnabled(false) , m_strokeEnabled(false) , m_textFillColor(ccWHITE) { } CCLabelTTF::~CCLabelTTF() { CC_SAFE_DELETE(m_pFontName); } CCLabelTTF * CCLabelTTF::create() { CCLabelTTF * pRet = new CCLabelTTF(); if (pRet && pRet->init()) { pRet->autorelease(); } else { CC_SAFE_DELETE(pRet); } return pRet; } CCLabelTTF * CCLabelTTF::create(const char *string, const char *fontName, float fontSize) { return CCLabelTTF::create(string, fontName, fontSize, CCSizeZero, kCCTextAlignmentCenter, kCCVerticalTextAlignmentTop); } CCLabelTTF * CCLabelTTF::create(const char *string, const char *fontName, float fontSize, const CCSize& dimensions, CCTextAlignment hAlignment) { return CCLabelTTF::create(string, fontName, fontSize, dimensions, hAlignment, kCCVerticalTextAlignmentTop); } CCLabelTTF* CCLabelTTF::create(const char *string, const char *fontName, float fontSize, const CCSize &dimensions, CCTextAlignment hAlignment, CCVerticalTextAlignment vAlignment) { CCLabelTTF *pRet = new CCLabelTTF(); if(pRet && pRet->initWithString(string, fontName, fontSize, dimensions, hAlignment, vAlignment)) { pRet->autorelease(); return pRet; } CC_SAFE_DELETE(pRet); return NULL; } CCLabelTTF * CCLabelTTF::createWithFontDefinition(const char *string, ccFontDefinition &textDefinition) { CCLabelTTF *pRet = new CCLabelTTF(); if(pRet && pRet->initWithStringAndTextDefinition(string, textDefinition)) { pRet->autorelease(); return pRet; } CC_SAFE_DELETE(pRet); return NULL; } bool CCLabelTTF::init() { return this->initWithString("", "Helvetica", 12); } bool CCLabelTTF::initWithString(const char *label, const char *fontName, float fontSize, const CCSize& dimensions, CCTextAlignment alignment) { return this->initWithString(label, fontName, fontSize, dimensions, alignment, kCCVerticalTextAlignmentTop); } bool CCLabelTTF::initWithString(const char *label, const char *fontName, float fontSize) { return this->initWithString(label, fontName, fontSize, CCSizeZero, kCCTextAlignmentLeft, kCCVerticalTextAlignmentTop); } bool CCLabelTTF::initWithString(const char *string, const char *fontName, float fontSize, const cocos2d::CCSize &dimensions, CCTextAlignment hAlignment, CCVerticalTextAlignment vAlignment) { if (CCSprite::init()) { // shader program this->setShaderProgram(CCShaderCache::sharedShaderCache()->programForKey(SHADER_PROGRAM)); m_tDimensions = CCSizeMake(dimensions.width, dimensions.height); m_hAlignment = hAlignment; m_vAlignment = vAlignment; m_pFontName = new std::string(fontName); m_fFontSize = fontSize; this->setString(string); return true; } return false; } bool CCLabelTTF::initWithStringAndTextDefinition(const char *string, ccFontDefinition &textDefinition) { if (CCSprite::init()) { // shader program this->setShaderProgram(CCShaderCache::sharedShaderCache()->programForKey(SHADER_PROGRAM)); // prepare everythin needed to render the label _updateWithTextDefinition(textDefinition, false); // set the string this->setString(string); // return true; } else { return false; } } void CCLabelTTF::setString(const char *string) { CCAssert(string != NULL, "Invalid string"); if (m_string.compare(string)) { m_string = string; this->updateTexture(); } } const char* CCLabelTTF::getString(void) { return m_string.c_str(); } const char* CCLabelTTF::description() { return CCString::createWithFormat("<CCLabelTTF | FontName = %s, FontSize = %.1f>", m_pFontName->c_str(), m_fFontSize)->getCString(); } CCTextAlignment CCLabelTTF::getHorizontalAlignment() { return m_hAlignment; } void CCLabelTTF::setHorizontalAlignment(CCTextAlignment alignment) { if (alignment != m_hAlignment) { m_hAlignment = alignment; // Force update if (m_string.size() > 0) { this->updateTexture(); } } } CCVerticalTextAlignment CCLabelTTF::getVerticalAlignment() { return m_vAlignment; } void CCLabelTTF::setVerticalAlignment(CCVerticalTextAlignment verticalAlignment) { if (verticalAlignment != m_vAlignment) { m_vAlignment = verticalAlignment; // Force update if (m_string.size() > 0) { this->updateTexture(); } } } CCSize CCLabelTTF::getDimensions() { return m_tDimensions; } void CCLabelTTF::setDimensions(const CCSize &dim) { if (dim.width != m_tDimensions.width || dim.height != m_tDimensions.height) { m_tDimensions = dim; // Force update if (m_string.size() > 0) { this->updateTexture(); } } } float CCLabelTTF::getFontSize() { return m_fFontSize; } void CCLabelTTF::setFontSize(float fontSize) { if (m_fFontSize != fontSize) { m_fFontSize = fontSize; // Force update if (m_string.size() > 0) { this->updateTexture(); } } } const char* CCLabelTTF::getFontName() { return m_pFontName->c_str(); } void CCLabelTTF::setFontName(const char *fontName) { if (m_pFontName->compare(fontName)) { delete m_pFontName; m_pFontName = new std::string(fontName); // Force update if (m_string.size() > 0) { this->updateTexture(); } } } // Helper bool CCLabelTTF::updateTexture() { CCTexture2D *tex; tex = new CCTexture2D(); if (!tex) return false; #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) ccFontDefinition texDef = _prepareTextDefinition(true); tex->initWithString( m_string.c_str(), &texDef ); #else tex->initWithString( m_string.c_str(), m_pFontName->c_str(), m_fFontSize * CC_CONTENT_SCALE_FACTOR(), CC_SIZE_POINTS_TO_PIXELS(m_tDimensions), m_hAlignment, m_vAlignment); #endif // set the texture this->setTexture(tex); // release it tex->release(); // set the size in the sprite CCRect rect =CCRectZero; rect.size = m_pobTexture->getContentSize(); this->setTextureRect(rect); //ok return true; } void CCLabelTTF::enableShadow(const CCSize &shadowOffset, float shadowOpacity, float shadowBlur, bool updateTexture) { #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) bool valueChanged = false; if (false == m_shadowEnabled) { m_shadowEnabled = true; valueChanged = true; } if ( (m_shadowOffset.width != shadowOffset.width) || (m_shadowOffset.height!=shadowOffset.height) ) { m_shadowOffset.width = shadowOffset.width; m_shadowOffset.height = shadowOffset.height; valueChanged = true; } if (m_shadowOpacity != shadowOpacity ) { m_shadowOpacity = shadowOpacity; valueChanged = true; } if (m_shadowBlur != shadowBlur) { m_shadowBlur = shadowBlur; valueChanged = true; } if ( valueChanged && updateTexture ) { this->updateTexture(); } #else CCLOGERROR("Currently only supported on iOS and Android!"); #endif } void CCLabelTTF::disableShadow(bool updateTexture) { #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) if (m_shadowEnabled) { m_shadowEnabled = false; if (updateTexture) this->updateTexture(); } #else CCLOGERROR("Currently only supported on iOS and Android!"); #endif } void CCLabelTTF::enableStroke(const ccColor3B &strokeColor, float strokeSize, bool updateTexture) { #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) bool valueChanged = false; if(m_strokeEnabled == false) { m_strokeEnabled = true; valueChanged = true; } if ( (m_strokeColor.r != strokeColor.r) || (m_strokeColor.g != strokeColor.g) || (m_strokeColor.b != strokeColor.b) ) { m_strokeColor = strokeColor; valueChanged = true; } if (m_strokeSize!=strokeSize) { m_strokeSize = strokeSize; valueChanged = true; } if ( valueChanged && updateTexture ) { this->updateTexture(); } #else CCLOGERROR("Currently only supported on iOS and Android!"); #endif } void CCLabelTTF::disableStroke(bool updateTexture) { #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) if (m_strokeEnabled) { m_strokeEnabled = false; if (updateTexture) this->updateTexture(); } #else CCLOGERROR("Currently only supported on iOS and Android!"); #endif } void CCLabelTTF::setFontFillColor(const ccColor3B &tintColor, bool updateTexture) { #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) if (m_textFillColor.r != tintColor.r || m_textFillColor.g != tintColor.g || m_textFillColor.b != tintColor.b) { m_textFillColor = tintColor; if (updateTexture) this->updateTexture(); } #else CCLOGERROR("Currently only supported on iOS and Android!"); #endif } void CCLabelTTF::setTextDefinition(ccFontDefinition *theDefinition) { if (theDefinition) { _updateWithTextDefinition(*theDefinition, true); } } ccFontDefinition *CCLabelTTF::getTextDefinition() { ccFontDefinition *tempDefinition = new ccFontDefinition; *tempDefinition = _prepareTextDefinition(false); return tempDefinition; } void CCLabelTTF::_updateWithTextDefinition(ccFontDefinition & textDefinition, bool mustUpdateTexture) { m_tDimensions = CCSizeMake(textDefinition.m_dimensions.width, textDefinition.m_dimensions.height); m_hAlignment = textDefinition.m_alignment; m_vAlignment = textDefinition.m_vertAlignment; m_pFontName = new std::string(textDefinition.m_fontName); m_fFontSize = textDefinition.m_fontSize; // shadow if ( textDefinition.m_shadow.m_shadowEnabled ) { enableShadow(textDefinition.m_shadow.m_shadowOffset, textDefinition.m_shadow.m_shadowOpacity, textDefinition.m_shadow.m_shadowBlur, false); } // stroke if ( textDefinition.m_stroke.m_strokeEnabled ) { enableStroke(textDefinition.m_stroke.m_strokeColor, textDefinition.m_stroke.m_strokeSize, false); } // fill color setFontFillColor(textDefinition.m_fontFillColor, false); if (mustUpdateTexture) updateTexture(); } ccFontDefinition CCLabelTTF::_prepareTextDefinition(bool adjustForResolution) { ccFontDefinition texDef; if (adjustForResolution) texDef.m_fontSize = m_fFontSize * CC_CONTENT_SCALE_FACTOR(); else texDef.m_fontSize = m_fFontSize; texDef.m_fontName = *m_pFontName; texDef.m_alignment = m_hAlignment; texDef.m_vertAlignment = m_vAlignment; if (adjustForResolution) texDef.m_dimensions = CC_SIZE_POINTS_TO_PIXELS(m_tDimensions); else texDef.m_dimensions = m_tDimensions; // stroke if ( m_strokeEnabled ) { texDef.m_stroke.m_strokeEnabled = true; texDef.m_stroke.m_strokeColor = m_strokeColor; if (adjustForResolution) texDef.m_stroke.m_strokeSize = m_strokeSize * CC_CONTENT_SCALE_FACTOR(); else texDef.m_stroke.m_strokeSize = m_strokeSize; } else { texDef.m_stroke.m_strokeEnabled = false; } // shadow if ( m_shadowEnabled ) { texDef.m_shadow.m_shadowEnabled = true; texDef.m_shadow.m_shadowBlur = m_shadowBlur; texDef.m_shadow.m_shadowOpacity = m_shadowOpacity; if (adjustForResolution) texDef.m_shadow.m_shadowOffset = CC_SIZE_POINTS_TO_PIXELS(m_shadowOffset); else texDef.m_shadow.m_shadowOffset = m_shadowOffset; } else { texDef.m_shadow.m_shadowEnabled = false; } // text tint texDef.m_fontFillColor = m_textFillColor; return texDef; } NS_CC_END
slightair/yamiHikariGame
yamiHikariGame/libs/cocos2dx/label_nodes/CCLabelTTF.cpp
C++
mit
15,254
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Diagnostics; using System.Runtime.InteropServices; namespace System.DirectoryServices.ActiveDirectory { public class GlobalCatalog : DomainController { // private variables private ActiveDirectorySchema _schema = null; private bool _disabled = false; #region constructors internal GlobalCatalog(DirectoryContext context, string globalCatalogName) : base(context, globalCatalogName) { } internal GlobalCatalog(DirectoryContext context, string globalCatalogName, DirectoryEntryManager directoryEntryMgr) : base(context, globalCatalogName, directoryEntryMgr) { } #endregion constructors #region public methods public static GlobalCatalog GetGlobalCatalog(DirectoryContext context) { string gcDnsName = null; bool isGlobalCatalog = false; DirectoryEntryManager directoryEntryMgr = null; // check that the context argument is not null if (context == null) throw new ArgumentNullException("context"); // target should be GC if (context.ContextType != DirectoryContextType.DirectoryServer) { throw new ArgumentException(SR.TargetShouldBeGC, "context"); } // target should be a server if (!(context.isServer())) { throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFound , context.Name), typeof(GlobalCatalog), context.Name); } // work with copy of the context context = new DirectoryContext(context); try { // Get dns name of the dc // by binding to root dse and getting the "dnsHostName" attribute // (also check that the "isGlobalCatalogReady" attribute is true) directoryEntryMgr = new DirectoryEntryManager(context); DirectoryEntry rootDSE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); if (!Utils.CheckCapability(rootDSE, Capability.ActiveDirectory)) { throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFound , context.Name), typeof(GlobalCatalog), context.Name); } gcDnsName = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.DnsHostName); isGlobalCatalog = (bool)Boolean.Parse((string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.IsGlobalCatalogReady)); if (!isGlobalCatalog) { throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFound , context.Name), typeof(GlobalCatalog), context.Name); } } catch (COMException e) { int errorCode = e.ErrorCode; if (errorCode == unchecked((int)0x8007203a)) { throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFound , context.Name), typeof(GlobalCatalog), context.Name); } else { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } return new GlobalCatalog(context, gcDnsName, directoryEntryMgr); } public static new GlobalCatalog FindOne(DirectoryContext context) { if (context == null) { throw new ArgumentNullException("context"); } if (context.ContextType != DirectoryContextType.Forest) { throw new ArgumentException(SR.TargetShouldBeForest, "context"); } return FindOneWithCredentialValidation(context, null, 0); } public static new GlobalCatalog FindOne(DirectoryContext context, string siteName) { if (context == null) { throw new ArgumentNullException("context"); } if (context.ContextType != DirectoryContextType.Forest) { throw new ArgumentException(SR.TargetShouldBeForest, "context"); } if (siteName == null) { throw new ArgumentNullException("siteName"); } return FindOneWithCredentialValidation(context, siteName, 0); } public static new GlobalCatalog FindOne(DirectoryContext context, LocatorOptions flag) { if (context == null) { throw new ArgumentNullException("context"); } if (context.ContextType != DirectoryContextType.Forest) { throw new ArgumentException(SR.TargetShouldBeForest, "context"); } return FindOneWithCredentialValidation(context, null, flag); } public static new GlobalCatalog FindOne(DirectoryContext context, string siteName, LocatorOptions flag) { if (context == null) { throw new ArgumentNullException("context"); } if (context.ContextType != DirectoryContextType.Forest) { throw new ArgumentException(SR.TargetShouldBeForest, "context"); } if (siteName == null) { throw new ArgumentNullException("siteName"); } return FindOneWithCredentialValidation(context, siteName, flag); } public static new GlobalCatalogCollection FindAll(DirectoryContext context) { if (context == null) { throw new ArgumentNullException("context"); } if (context.ContextType != DirectoryContextType.Forest) { throw new ArgumentException(SR.TargetShouldBeForest, "context"); } // work with copy of the context context = new DirectoryContext(context); return FindAllInternal(context, null); } public static new GlobalCatalogCollection FindAll(DirectoryContext context, string siteName) { if (context == null) { throw new ArgumentNullException("context"); } if (context.ContextType != DirectoryContextType.Forest) { throw new ArgumentException(SR.TargetShouldBeForest, "context"); } if (siteName == null) { throw new ArgumentNullException("siteName"); } // work with copy of the context context = new DirectoryContext(context); return FindAllInternal(context, siteName); } public override GlobalCatalog EnableGlobalCatalog() { CheckIfDisposed(); throw new InvalidOperationException(SR.CannotPerformOnGCObject); } public DomainController DisableGlobalCatalog() { CheckIfDisposed(); CheckIfDisabled(); // bind to the server object DirectoryEntry serverNtdsaEntry = directoryEntryMgr.GetCachedDirectoryEntry(NtdsaObjectName); // reset the NTDSDSA_OPT_IS_GC flag on the "options" property int options = 0; try { if (serverNtdsaEntry.Properties[PropertyManager.Options].Value != null) { options = (int)serverNtdsaEntry.Properties[PropertyManager.Options].Value; } serverNtdsaEntry.Properties[PropertyManager.Options].Value = options & (~1); serverNtdsaEntry.CommitChanges(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } // mark as disbaled _disabled = true; // return a domain controller object return new DomainController(context, Name); } public override bool IsGlobalCatalog() { CheckIfDisposed(); CheckIfDisabled(); // since this is a global catalog object, this should always return true return true; } public ReadOnlyActiveDirectorySchemaPropertyCollection FindAllProperties() { CheckIfDisposed(); CheckIfDisabled(); // create an ActiveDirectorySchema object if (_schema == null) { string schemaNC = null; try { schemaNC = directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.SchemaNamingContext); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } DirectoryContext schemaContext = Utils.GetNewDirectoryContext(Name, DirectoryContextType.DirectoryServer, context); _schema = new ActiveDirectorySchema(context, schemaNC); } // return the global catalog replicated properties return _schema.FindAllProperties(PropertyTypes.InGlobalCatalog); } public override DirectorySearcher GetDirectorySearcher() { CheckIfDisposed(); CheckIfDisabled(); return InternalGetDirectorySearcher(); } #endregion public methods #region private methods private void CheckIfDisabled() { if (_disabled) { throw new InvalidOperationException(SR.GCDisabled); } } internal static new GlobalCatalog FindOneWithCredentialValidation(DirectoryContext context, string siteName, LocatorOptions flag) { GlobalCatalog gc; bool retry = false; bool credsValidated = false; // work with copy of the context context = new DirectoryContext(context); // authenticate against this GC to validate the credentials gc = FindOneInternal(context, context.Name, siteName, flag); try { ValidateCredential(gc, context); credsValidated = true; } catch (COMException e) { if (e.ErrorCode == unchecked((int)0x8007203a)) { // server is down , so try again with force rediscovery if the flags did not already contain force rediscovery if ((flag & LocatorOptions.ForceRediscovery) == 0) { retry = true; } else { throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFoundInForest , context.Name), typeof(GlobalCatalog), null); } } else { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } finally { if (!credsValidated) { gc.Dispose(); } } if (retry) { credsValidated = false; gc = FindOneInternal(context, context.Name, siteName, flag | LocatorOptions.ForceRediscovery); try { ValidateCredential(gc, context); credsValidated = true; } catch (COMException e) { if (e.ErrorCode == unchecked((int)0x8007203a)) { // server is down throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFoundInForest , context.Name), typeof(GlobalCatalog), null); } else { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } finally { if (!credsValidated) { gc.Dispose(); } } } return gc; } internal static new GlobalCatalog FindOneInternal(DirectoryContext context, string forestName, string siteName, LocatorOptions flag) { DomainControllerInfo domainControllerInfo; int errorCode = 0; if (siteName != null && siteName.Length == 0) { throw new ArgumentException(SR.EmptyStringParameter, "siteName"); } // check that the flags passed have only the valid bits set if (((long)flag & (~((long)LocatorOptions.AvoidSelf | (long)LocatorOptions.ForceRediscovery | (long)LocatorOptions.KdcRequired | (long)LocatorOptions.TimeServerRequired | (long)LocatorOptions.WriteableRequired))) != 0) { throw new ArgumentException(SR.InvalidFlags, "flag"); } if (forestName == null) { // get the dns name of the logged on forest DomainControllerInfo tempDomainControllerInfo; int error = Locator.DsGetDcNameWrapper(null, DirectoryContext.GetLoggedOnDomain(), null, (long)PrivateLocatorFlags.DirectoryServicesRequired, out tempDomainControllerInfo); if (error == NativeMethods.ERROR_NO_SUCH_DOMAIN) { // throw not found exception throw new ActiveDirectoryObjectNotFoundException(SR.ContextNotAssociatedWithDomain, typeof(GlobalCatalog), null); } else if (error != 0) { throw ExceptionHelper.GetExceptionFromErrorCode(errorCode); } Debug.Assert(tempDomainControllerInfo.DnsForestName != null); forestName = tempDomainControllerInfo.DnsForestName; } // call DsGetDcName errorCode = Locator.DsGetDcNameWrapper(null, forestName, siteName, (long)flag | (long)(PrivateLocatorFlags.GCRequired | PrivateLocatorFlags.DirectoryServicesRequired), out domainControllerInfo); if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN) { throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFoundInForest , forestName), typeof(GlobalCatalog), null); } // this can only occur when flag is being explicitly passed (since the flags that we pass internally are valid) if (errorCode == NativeMethods.ERROR_INVALID_FLAGS) { throw new ArgumentException(SR.InvalidFlags, "flag"); } else if (errorCode != 0) { throw ExceptionHelper.GetExceptionFromErrorCode(errorCode); } // create a GlobalCatalog object // the name is returned in the form "\\servername", so skip the "\\" Debug.Assert(domainControllerInfo.DomainControllerName.Length > 2); string globalCatalogName = domainControllerInfo.DomainControllerName.Substring(2); // create a new context object for the global catalog DirectoryContext gcContext = Utils.GetNewDirectoryContext(globalCatalogName, DirectoryContextType.DirectoryServer, context); return new GlobalCatalog(gcContext, globalCatalogName); } internal static GlobalCatalogCollection FindAllInternal(DirectoryContext context, string siteName) { ArrayList gcList = new ArrayList(); if (siteName != null && siteName.Length == 0) { throw new ArgumentException(SR.EmptyStringParameter, "siteName"); } foreach (string gcName in Utils.GetReplicaList(context, null /* not specific to any partition */, siteName, false /* isDefaultNC */, false /* isADAM */, true /* mustBeGC */)) { DirectoryContext gcContext = Utils.GetNewDirectoryContext(gcName, DirectoryContextType.DirectoryServer, context); gcList.Add(new GlobalCatalog(gcContext, gcName)); } return new GlobalCatalogCollection(gcList); } private DirectorySearcher InternalGetDirectorySearcher() { DirectoryEntry de = new DirectoryEntry("GC://" + Name); de.AuthenticationType = Utils.DefaultAuthType | AuthenticationTypes.ServerBind; de.Username = context.UserName; de.Password = context.Password; return new DirectorySearcher(de); } #endregion } }
nbarbettini/corefx
src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/GlobalCatalog.cs
C#
mit
17,313
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Course completion progress report * * @package report * @subpackage completion * @copyright 2009 Catalyst IT Ltd * @author Aaron Barnes <aaronb@catalyst.net.nz> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ require_once(__DIR__.'/../../config.php'); require_once("{$CFG->libdir}/completionlib.php"); /** * Configuration */ define('COMPLETION_REPORT_PAGE', 25); define('COMPLETION_REPORT_COL_TITLES', true); /* * Setup page, check permissions */ // Get course $courseid = required_param('course', PARAM_INT); $format = optional_param('format','',PARAM_ALPHA); $sort = optional_param('sort','',PARAM_ALPHA); $edituser = optional_param('edituser', 0, PARAM_INT); $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST); $context = context_course::instance($course->id); $url = new moodle_url('/report/completion/index.php', array('course'=>$course->id)); $PAGE->set_url($url); $PAGE->set_pagelayout('report'); $firstnamesort = ($sort == 'firstname'); $excel = ($format == 'excelcsv'); $csv = ($format == 'csv' || $excel); // Load CSV library if ($csv) { require_once("{$CFG->libdir}/csvlib.class.php"); } // Paging $start = optional_param('start', 0, PARAM_INT); $sifirst = optional_param('sifirst', 'all', PARAM_NOTAGS); $silast = optional_param('silast', 'all', PARAM_NOTAGS); // Whether to show extra user identity information $extrafields = get_extra_user_fields($context); $leftcols = 1 + count($extrafields); // Check permissions require_login($course); require_capability('report/completion:view', $context); // Get group mode $group = groups_get_course_group($course, true); // Supposed to verify group if ($group === 0 && $course->groupmode == SEPARATEGROUPS) { require_capability('moodle/site:accessallgroups',$context); } /** * Load data */ // Retrieve course_module data for all modules in the course $modinfo = get_fast_modinfo($course); // Get criteria for course $completion = new completion_info($course); if (!$completion->has_criteria()) { print_error('nocriteriaset', 'completion', $CFG->wwwroot.'/course/report.php?id='.$course->id); } // Get criteria and put in correct order $criteria = array(); foreach ($completion->get_criteria(COMPLETION_CRITERIA_TYPE_COURSE) as $criterion) { $criteria[] = $criterion; } foreach ($completion->get_criteria(COMPLETION_CRITERIA_TYPE_ACTIVITY) as $criterion) { $criteria[] = $criterion; } foreach ($completion->get_criteria() as $criterion) { if (!in_array($criterion->criteriatype, array( COMPLETION_CRITERIA_TYPE_COURSE, COMPLETION_CRITERIA_TYPE_ACTIVITY))) { $criteria[] = $criterion; } } // Can logged in user mark users as complete? // (if the logged in user has a role defined in the role criteria) $allow_marking = false; $allow_marking_criteria = null; if (!$csv) { // Get role criteria $rcriteria = $completion->get_criteria(COMPLETION_CRITERIA_TYPE_ROLE); if (!empty($rcriteria)) { foreach ($rcriteria as $rcriterion) { $users = get_role_users($rcriterion->role, $context, true); // If logged in user has this role, allow marking complete if ($users && in_array($USER->id, array_keys($users))) { $allow_marking = true; $allow_marking_criteria = $rcriterion->id; break; } } } } /* * Setup page header */ if ($csv) { $shortname = format_string($course->shortname, true, array('context' => $context)); $shortname = preg_replace('/[^a-z0-9-]/', '_',core_text::strtolower(strip_tags($shortname))); $export = new csv_export_writer(); $export->set_filename('completion-'.$shortname); } else { // Navigation and header $strcompletion = get_string('coursecompletion'); $PAGE->set_title($strcompletion); $PAGE->set_heading($course->fullname); echo $OUTPUT->header(); // Handle groups (if enabled) groups_print_course_menu($course, $CFG->wwwroot.'/report/completion/index.php?course='.$course->id); } if ($sifirst !== 'all') { set_user_preference('ifirst', $sifirst); } if ($silast !== 'all') { set_user_preference('ilast', $silast); } if (!empty($USER->preference['ifirst'])) { $sifirst = $USER->preference['ifirst']; } else { $sifirst = 'all'; } if (!empty($USER->preference['ilast'])) { $silast = $USER->preference['ilast']; } else { $silast = 'all'; } // Generate where clause $where = array(); $where_params = array(); if ($sifirst !== 'all') { $where[] = $DB->sql_like('u.firstname', ':sifirst', false); $where_params['sifirst'] = $sifirst.'%'; } if ($silast !== 'all') { $where[] = $DB->sql_like('u.lastname', ':silast', false); $where_params['silast'] = $silast.'%'; } // Get user match count $total = $completion->get_num_tracked_users(implode(' AND ', $where), $where_params, $group); // Total user count $grandtotal = $completion->get_num_tracked_users('', array(), $group); // If no users in this course what-so-ever if (!$grandtotal) { echo $OUTPUT->container(get_string('err_nousers', 'completion'), 'errorbox errorboxcontent'); echo $OUTPUT->footer(); exit; } // Get user data $progress = array(); if ($total) { $progress = $completion->get_progress_all( implode(' AND ', $where), $where_params, $group, $firstnamesort ? 'u.firstname ASC' : 'u.lastname ASC', $csv ? 0 : COMPLETION_REPORT_PAGE, $csv ? 0 : $start, $context ); } // Build link for paging $link = $CFG->wwwroot.'/report/completion/index.php?course='.$course->id; if (strlen($sort)) { $link .= '&amp;sort='.$sort; } $link .= '&amp;start='; $pagingbar = ''; // Initials bar. $prefixfirst = 'sifirst'; $prefixlast = 'silast'; $pagingbar .= $OUTPUT->initials_bar($sifirst, 'firstinitial', get_string('firstname'), $prefixfirst, $url); $pagingbar .= $OUTPUT->initials_bar($silast, 'lastinitial', get_string('lastname'), $prefixlast, $url); // Do we need a paging bar? if ($total > COMPLETION_REPORT_PAGE) { // Paging bar $pagingbar .= '<div class="paging">'; $pagingbar .= get_string('page').': '; $sistrings = array(); if ($sifirst != 'all') { $sistrings[] = "sifirst={$sifirst}"; } if ($silast != 'all') { $sistrings[] = "silast={$silast}"; } $sistring = !empty($sistrings) ? '&amp;'.implode('&amp;', $sistrings) : ''; // Display previous link if ($start > 0) { $pstart = max($start - COMPLETION_REPORT_PAGE, 0); $pagingbar .= "(<a class=\"previous\" href=\"{$link}{$pstart}{$sistring}\">".get_string('previous').'</a>)&nbsp;'; } // Create page links $curstart = 0; $curpage = 0; while ($curstart < $total) { $curpage++; if ($curstart == $start) { $pagingbar .= '&nbsp;'.$curpage.'&nbsp;'; } else { $pagingbar .= "&nbsp;<a href=\"{$link}{$curstart}{$sistring}\">$curpage</a>&nbsp;"; } $curstart += COMPLETION_REPORT_PAGE; } // Display next link $nstart = $start + COMPLETION_REPORT_PAGE; if ($nstart < $total) { $pagingbar .= "&nbsp;(<a class=\"next\" href=\"{$link}{$nstart}{$sistring}\">".get_string('next').'</a>)'; } $pagingbar .= '</div>'; } /* * Draw table header */ // Start of table if (!$csv) { print '<br class="clearer"/>'; // ugh $total_header = ($total == $grandtotal) ? $total : "{$total}/{$grandtotal}"; echo $OUTPUT->heading(get_string('allparticipants').": {$total_header}", 3); print $pagingbar; if (!$total) { echo $OUTPUT->heading(get_string('nothingtodisplay'), 2); echo $OUTPUT->footer(); exit; } print '<table id="completion-progress" class="table table-bordered generaltable flexible boxaligncenter completionreport" style="text-align: left" cellpadding="5" border="1">'; // Print criteria group names print PHP_EOL.'<thead><tr style="vertical-align: top">'; echo '<th scope="row" class="rowheader" colspan="' . $leftcols . '">' . get_string('criteriagroup', 'completion') . '</th>'; $current_group = false; $col_count = 0; for ($i = 0; $i <= count($criteria); $i++) { if (isset($criteria[$i])) { $criterion = $criteria[$i]; if ($current_group && $criterion->criteriatype === $current_group->criteriatype) { ++$col_count; continue; } } // Print header cell if ($col_count) { print '<th scope="col" colspan="'.$col_count.'" class="colheader criteriagroup">'.$current_group->get_type_title().'</th>'; } if (isset($criteria[$i])) { // Move to next criteria type $current_group = $criterion; $col_count = 1; } } // Overall course completion status print '<th style="text-align: center;">'.get_string('course').'</th>'; print '</tr>'; // Print aggregation methods print PHP_EOL.'<tr style="vertical-align: top">'; echo '<th scope="row" class="rowheader" colspan="' . $leftcols . '">' . get_string('aggregationmethod', 'completion').'</th>'; $current_group = false; $col_count = 0; for ($i = 0; $i <= count($criteria); $i++) { if (isset($criteria[$i])) { $criterion = $criteria[$i]; if ($current_group && $criterion->criteriatype === $current_group->criteriatype) { ++$col_count; continue; } } // Print header cell if ($col_count) { $has_agg = array( COMPLETION_CRITERIA_TYPE_COURSE, COMPLETION_CRITERIA_TYPE_ACTIVITY, COMPLETION_CRITERIA_TYPE_ROLE, ); if (in_array($current_group->criteriatype, $has_agg)) { // Try load a aggregation method $method = $completion->get_aggregation_method($current_group->criteriatype); $method = $method == 1 ? get_string('all') : get_string('any'); } else { $method = '-'; } print '<th scope="col" colspan="'.$col_count.'" class="colheader aggheader">'.$method.'</th>'; } if (isset($criteria[$i])) { // Move to next criteria type $current_group = $criterion; $col_count = 1; } } // Overall course aggregation method print '<th scope="col" class="colheader aggheader aggcriteriacourse">'; // Get course aggregation $method = $completion->get_aggregation_method(); print $method == 1 ? get_string('all') : get_string('any'); print '</th>'; print '</tr>'; // Print criteria titles if (COMPLETION_REPORT_COL_TITLES) { print PHP_EOL.'<tr>'; echo '<th scope="row" class="rowheader" colspan="' . $leftcols . '">' . get_string('criteria', 'completion') . '</th>'; foreach ($criteria as $criterion) { // Get criteria details $details = $criterion->get_title_detailed(); print '<th scope="col" class="colheader criterianame">'; print '<div class="rotated-text-container"><span class="rotated-text">'.$details.'</span></div>'; print '</th>'; } // Overall course completion status print '<th scope="col" class="colheader criterianame">'; print '<div class="rotated-text-container"><span class="rotated-text">'.get_string('coursecomplete', 'completion').'</span></div>'; print '</th></tr>'; } // Print user heading and icons print '<tr>'; // User heading / sort option print '<th scope="col" class="completion-sortchoice" style="clear: both;">'; $sistring = "&amp;silast={$silast}&amp;sifirst={$sifirst}"; if ($firstnamesort) { print get_string('firstname')." / <a href=\"./index.php?course={$course->id}{$sistring}\">". get_string('lastname').'</a>'; } else { print "<a href=\"./index.php?course={$course->id}&amp;sort=firstname{$sistring}\">". get_string('firstname').'</a> / '. get_string('lastname'); } print '</th>'; // Print user identity columns foreach ($extrafields as $field) { echo '<th scope="col" class="completion-identifyfield">' . get_user_field_name($field) . '</th>'; } /// /// Print criteria icons /// foreach ($criteria as $criterion) { // Generate icon details $iconlink = ''; $iconalt = ''; // Required $iconattributes = array('class' => 'icon'); switch ($criterion->criteriatype) { case COMPLETION_CRITERIA_TYPE_ACTIVITY: // Display icon $iconlink = $CFG->wwwroot.'/mod/'.$criterion->module.'/view.php?id='.$criterion->moduleinstance; $iconattributes['title'] = $modinfo->cms[$criterion->moduleinstance]->get_formatted_name(); $iconalt = get_string('modulename', $criterion->module); break; case COMPLETION_CRITERIA_TYPE_COURSE: // Load course $crs = $DB->get_record('course', array('id' => $criterion->courseinstance)); // Display icon $iconlink = $CFG->wwwroot.'/course/view.php?id='.$criterion->courseinstance; $iconattributes['title'] = format_string($crs->fullname, true, array('context' => context_course::instance($crs->id, MUST_EXIST))); $iconalt = format_string($crs->shortname, true, array('context' => context_course::instance($crs->id))); break; case COMPLETION_CRITERIA_TYPE_ROLE: // Load role $role = $DB->get_record('role', array('id' => $criterion->role)); // Display icon $iconalt = $role->name; break; } // Create icon alt if not supplied if (!$iconalt) { $iconalt = $criterion->get_title(); } // Print icon and cell print '<th class="criteriaicon">'; print ($iconlink ? '<a href="'.$iconlink.'" title="'.$iconattributes['title'].'">' : ''); print $OUTPUT->render($criterion->get_icon($iconalt, $iconattributes)); print ($iconlink ? '</a>' : ''); print '</th>'; } // Overall course completion status print '<th class="criteriaicon">'; print $OUTPUT->pix_icon('i/course', get_string('coursecomplete', 'completion')); print '</th>'; print '</tr></thead>'; echo '<tbody>'; } else { // The CSV headers $row = array(); $row[] = get_string('id', 'report_completion'); $row[] = get_string('name', 'report_completion'); foreach ($extrafields as $field) { $row[] = get_user_field_name($field); } // Add activity headers foreach ($criteria as $criterion) { // Handle activity completion differently if ($criterion->criteriatype == COMPLETION_CRITERIA_TYPE_ACTIVITY) { // Load activity $mod = $criterion->get_mod_instance(); $row[] = $formattedname = format_string($mod->name, true, array('context' => context_module::instance($criterion->moduleinstance))); $row[] = $formattedname . ' - ' . get_string('completiondate', 'report_completion'); } else { // Handle all other criteria $row[] = strip_tags($criterion->get_title_detailed()); } } $row[] = get_string('coursecomplete', 'completion'); $export->add_data($row); } /// /// Display a row for each user /// foreach ($progress as $user) { // User name if ($csv) { $row = array(); $row[] = $user->id; $row[] = fullname($user); foreach ($extrafields as $field) { $row[] = $user->{$field}; } } else { print PHP_EOL.'<tr id="user-'.$user->id.'">'; if (completion_can_view_data($user->id, $course)) { $userurl = new moodle_url('/blocks/completionstatus/details.php', array('course' => $course->id, 'user' => $user->id)); } else { $userurl = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $course->id)); } print '<th scope="row"><a href="'.$userurl->out().'">'.fullname($user).'</a></th>'; foreach ($extrafields as $field) { echo '<td>'.s($user->{$field}).'</td>'; } } // Progress for each course completion criteria foreach ($criteria as $criterion) { $criteria_completion = $completion->get_user_completion($user->id, $criterion); $is_complete = $criteria_completion->is_complete(); // Handle activity completion differently if ($criterion->criteriatype == COMPLETION_CRITERIA_TYPE_ACTIVITY) { // Load activity $activity = $modinfo->cms[$criterion->moduleinstance]; // Get progress information and state if (array_key_exists($activity->id, $user->progress)) { $state = $user->progress[$activity->id]->completionstate; } else if ($is_complete) { $state = COMPLETION_COMPLETE; } else { $state = COMPLETION_INCOMPLETE; } if ($is_complete) { $date = userdate($criteria_completion->timecompleted, get_string('strftimedatetimeshort', 'langconfig')); } else { $date = ''; } // Work out how it corresponds to an icon switch($state) { case COMPLETION_INCOMPLETE : $completiontype = 'n'; break; case COMPLETION_COMPLETE : $completiontype = 'y'; break; case COMPLETION_COMPLETE_PASS : $completiontype = 'pass'; break; case COMPLETION_COMPLETE_FAIL : $completiontype = 'fail'; break; } $auto = $activity->completion == COMPLETION_TRACKING_AUTOMATIC; $completionicon = 'completion-'.($auto ? 'auto' : 'manual').'-'.$completiontype; $describe = get_string('completion-'.$completiontype, 'completion'); $a = new StdClass(); $a->state = $describe; $a->date = $date; $a->user = fullname($user); $a->activity = $activity->get_formatted_name(); $fulldescribe = get_string('progress-title', 'completion', $a); if ($csv) { $row[] = $describe; $row[] = $date; } else { print '<td class="completion-progresscell">'; print $OUTPUT->pix_icon('i/' . $completionicon, $fulldescribe); print '</td>'; } continue; } // Handle all other criteria $completiontype = $is_complete ? 'y' : 'n'; $completionicon = 'completion-auto-'.$completiontype; $describe = get_string('completion-'.$completiontype, 'completion'); $a = new stdClass(); $a->state = $describe; if ($is_complete) { $a->date = userdate($criteria_completion->timecompleted, get_string('strftimedatetimeshort', 'langconfig')); } else { $a->date = ''; } $a->user = fullname($user); $a->activity = strip_tags($criterion->get_title()); $fulldescribe = get_string('progress-title', 'completion', $a); if ($csv) { $row[] = $a->date; } else { print '<td class="completion-progresscell">'; if ($allow_marking_criteria === $criterion->id) { $describe = get_string('completion-'.$completiontype, 'completion'); $toggleurl = new moodle_url( '/course/togglecompletion.php', array( 'user' => $user->id, 'course' => $course->id, 'rolec' => $allow_marking_criteria, 'sesskey' => sesskey() ) ); print '<a href="'.$toggleurl->out().'" title="'.s(get_string('clicktomarkusercomplete', 'report_completion')).'">' . $OUTPUT->pix_icon('i/completion-manual-' . ($is_complete ? 'y' : 'n'), $describe) . '</a></td>'; } else { print $OUTPUT->pix_icon('i/' . $completionicon, $fulldescribe) . '</td>'; } print '</td>'; } } // Handle overall course completion // Load course completion $params = array( 'userid' => $user->id, 'course' => $course->id ); $ccompletion = new completion_completion($params); $completiontype = $ccompletion->is_complete() ? 'y' : 'n'; $describe = get_string('completion-'.$completiontype, 'completion'); $a = new StdClass; if ($ccompletion->is_complete()) { $a->date = userdate($ccompletion->timecompleted, get_string('strftimedatetimeshort', 'langconfig')); } else { $a->date = ''; } $a->state = $describe; $a->user = fullname($user); $a->activity = strip_tags(get_string('coursecomplete', 'completion')); $fulldescribe = get_string('progress-title', 'completion', $a); if ($csv) { $row[] = $a->date; } else { print '<td class="completion-progresscell">'; // Display course completion status icon print $OUTPUT->pix_icon('i/completion-auto-' . $completiontype, $fulldescribe); print '</td>'; } if ($csv) { $export->add_data($row); } else { print '</tr>'; } } if ($csv) { $export->download_file(); } else { echo '</tbody>'; } print '</table>'; print $pagingbar; $csvurl = new moodle_url('/report/completion/index.php', array('course' => $course->id, 'format' => 'csv')); $excelurl = new moodle_url('/report/completion/index.php', array('course' => $course->id, 'format' => 'excelcsv')); print '<ul class="export-actions">'; print '<li><a href="'.$csvurl->out().'">'.get_string('csvdownload','completion').'</a></li>'; print '<li><a href="'.$excelurl->out().'">'.get_string('excelcsvdownload','completion').'</a></li>'; print '</ul>'; echo $OUTPUT->footer($course); // Trigger a report viewed event. $event = \report_completion\event\report_viewed::create(array('context' => $context)); $event->trigger();
AmrataRamchandani/moodle
report/completion/index.php
PHP
gpl-3.0
23,390
/// -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- /* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <AP_Math/AP_Math.h> #include <AP_HAL/AP_HAL.h> #include "AP_Compass_LSM303D.h" extern const AP_HAL::HAL& hal; #if CONFIG_HAL_BOARD == HAL_BOARD_LINUX #include <AP_HAL_Linux/GPIO.h> #if CONFIG_HAL_BOARD_SUBTYPE == HAL_BOARD_SUBTYPE_LINUX_RASPILOT #define LSM303D_DRDY_M_PIN RPI_GPIO_27 #endif #endif #ifndef LSM303D_DRDY_M_PIN #define LSM303D_DRDY_M_PIN -1 #endif /* SPI protocol address bits */ #define DIR_READ (1<<7) #define DIR_WRITE (0<<7) #define ADDR_INCREMENT (1<<6) /* register addresses: A: accel, M: mag, T: temp */ #define ADDR_WHO_AM_I 0x0F #define WHO_I_AM 0x49 #define ADDR_OUT_TEMP_L 0x05 #define ADDR_OUT_TEMP_H 0x06 #define ADDR_STATUS_M 0x07 #define ADDR_OUT_X_L_M 0x08 #define ADDR_OUT_X_H_M 0x09 #define ADDR_OUT_Y_L_M 0x0A #define ADDR_OUT_Y_H_M 0x0B #define ADDR_OUT_Z_L_M 0x0C #define ADDR_OUT_Z_H_M 0x0D #define ADDR_INT_CTRL_M 0x12 #define ADDR_INT_SRC_M 0x13 #define ADDR_REFERENCE_X 0x1c #define ADDR_REFERENCE_Y 0x1d #define ADDR_REFERENCE_Z 0x1e #define ADDR_STATUS_A 0x27 #define ADDR_OUT_X_L_A 0x28 #define ADDR_OUT_X_H_A 0x29 #define ADDR_OUT_Y_L_A 0x2A #define ADDR_OUT_Y_H_A 0x2B #define ADDR_OUT_Z_L_A 0x2C #define ADDR_OUT_Z_H_A 0x2D #define ADDR_CTRL_REG0 0x1F #define ADDR_CTRL_REG1 0x20 #define ADDR_CTRL_REG2 0x21 #define ADDR_CTRL_REG3 0x22 #define ADDR_CTRL_REG4 0x23 #define ADDR_CTRL_REG5 0x24 #define ADDR_CTRL_REG6 0x25 #define ADDR_CTRL_REG7 0x26 #define ADDR_FIFO_CTRL 0x2e #define ADDR_FIFO_SRC 0x2f #define ADDR_IG_CFG1 0x30 #define ADDR_IG_SRC1 0x31 #define ADDR_IG_THS1 0x32 #define ADDR_IG_DUR1 0x33 #define ADDR_IG_CFG2 0x34 #define ADDR_IG_SRC2 0x35 #define ADDR_IG_THS2 0x36 #define ADDR_IG_DUR2 0x37 #define ADDR_CLICK_CFG 0x38 #define ADDR_CLICK_SRC 0x39 #define ADDR_CLICK_THS 0x3a #define ADDR_TIME_LIMIT 0x3b #define ADDR_TIME_LATENCY 0x3c #define ADDR_TIME_WINDOW 0x3d #define ADDR_ACT_THS 0x3e #define ADDR_ACT_DUR 0x3f #define REG1_RATE_BITS_A ((1<<7) | (1<<6) | (1<<5) | (1<<4)) #define REG1_POWERDOWN_A ((0<<7) | (0<<6) | (0<<5) | (0<<4)) #define REG1_RATE_3_125HZ_A ((0<<7) | (0<<6) | (0<<5) | (1<<4)) #define REG1_RATE_6_25HZ_A ((0<<7) | (0<<6) | (1<<5) | (0<<4)) #define REG1_RATE_12_5HZ_A ((0<<7) | (0<<6) | (1<<5) | (1<<4)) #define REG1_RATE_25HZ_A ((0<<7) | (1<<6) | (0<<5) | (0<<4)) #define REG1_RATE_50HZ_A ((0<<7) | (1<<6) | (0<<5) | (1<<4)) #define REG1_RATE_100HZ_A ((0<<7) | (1<<6) | (1<<5) | (0<<4)) #define REG1_RATE_200HZ_A ((0<<7) | (1<<6) | (1<<5) | (1<<4)) #define REG1_RATE_400HZ_A ((1<<7) | (0<<6) | (0<<5) | (0<<4)) #define REG1_RATE_800HZ_A ((1<<7) | (0<<6) | (0<<5) | (1<<4)) #define REG1_RATE_1600HZ_A ((1<<7) | (0<<6) | (1<<5) | (0<<4)) #define REG1_BDU_UPDATE (1<<3) #define REG1_Z_ENABLE_A (1<<2) #define REG1_Y_ENABLE_A (1<<1) #define REG1_X_ENABLE_A (1<<0) #define REG2_ANTIALIAS_FILTER_BW_BITS_A ((1<<7) | (1<<6)) #define REG2_AA_FILTER_BW_773HZ_A ((0<<7) | (0<<6)) #define REG2_AA_FILTER_BW_194HZ_A ((0<<7) | (1<<6)) #define REG2_AA_FILTER_BW_362HZ_A ((1<<7) | (0<<6)) #define REG2_AA_FILTER_BW_50HZ_A ((1<<7) | (1<<6)) #define REG2_FULL_SCALE_BITS_A ((1<<5) | (1<<4) | (1<<3)) #define REG2_FULL_SCALE_2G_A ((0<<5) | (0<<4) | (0<<3)) #define REG2_FULL_SCALE_4G_A ((0<<5) | (0<<4) | (1<<3)) #define REG2_FULL_SCALE_6G_A ((0<<5) | (1<<4) | (0<<3)) #define REG2_FULL_SCALE_8G_A ((0<<5) | (1<<4) | (1<<3)) #define REG2_FULL_SCALE_16G_A ((1<<5) | (0<<4) | (0<<3)) #define REG5_ENABLE_T (1<<7) #define REG5_RES_HIGH_M ((1<<6) | (1<<5)) #define REG5_RES_LOW_M ((0<<6) | (0<<5)) #define REG5_RATE_BITS_M ((1<<4) | (1<<3) | (1<<2)) #define REG5_RATE_3_125HZ_M ((0<<4) | (0<<3) | (0<<2)) #define REG5_RATE_6_25HZ_M ((0<<4) | (0<<3) | (1<<2)) #define REG5_RATE_12_5HZ_M ((0<<4) | (1<<3) | (0<<2)) #define REG5_RATE_25HZ_M ((0<<4) | (1<<3) | (1<<2)) #define REG5_RATE_50HZ_M ((1<<4) | (0<<3) | (0<<2)) #define REG5_RATE_100HZ_M ((1<<4) | (0<<3) | (1<<2)) #define REG5_RATE_DO_NOT_USE_M ((1<<4) | (1<<3) | (0<<2)) #define REG6_FULL_SCALE_BITS_M ((1<<6) | (1<<5)) #define REG6_FULL_SCALE_2GA_M ((0<<6) | (0<<5)) #define REG6_FULL_SCALE_4GA_M ((0<<6) | (1<<5)) #define REG6_FULL_SCALE_8GA_M ((1<<6) | (0<<5)) #define REG6_FULL_SCALE_12GA_M ((1<<6) | (1<<5)) #define REG7_CONT_MODE_M ((0<<1) | (0<<0)) #define INT_CTRL_M 0x12 #define INT_SRC_M 0x13 /* default values for this device */ #define LSM303D_ACCEL_DEFAULT_RANGE_G 8 #define LSM303D_ACCEL_DEFAULT_RATE 800 #define LSM303D_ACCEL_DEFAULT_ONCHIP_FILTER_FREQ 50 #define LSM303D_ACCEL_DEFAULT_DRIVER_FILTER_FREQ 30 #define LSM303D_MAG_DEFAULT_RANGE_GA 2 #define LSM303D_MAG_DEFAULT_RATE 100 #define LSM303D_DEBUG 0 #if LSM303D_DEBUG #include <stdio.h> #define error(...) fprintf(stderr, __VA_ARGS__) #define debug(...) hal.console->printf(__VA_ARGS__) #define ASSERT(x) assert(x) #else #define error(...) #define debug(...) #define ASSERT(x) #endif // constructor AP_Compass_LSM303D::AP_Compass_LSM303D(Compass &compass): AP_Compass_Backend(compass) {} // detect the sensor AP_Compass_Backend *AP_Compass_LSM303D::detect_spi(Compass &compass) { AP_Compass_LSM303D *sensor = new AP_Compass_LSM303D(compass); if (sensor == NULL) { return NULL; } if (!sensor->init()) { delete sensor; return NULL; } return sensor; } uint8_t AP_Compass_LSM303D::_register_read(uint8_t reg) { uint8_t addr = reg | 0x80; // Set most significant bit uint8_t tx[2]; uint8_t rx[2]; tx[0] = addr; tx[1] = 0; _spi->transaction(tx, rx, 2); return rx[1]; } void AP_Compass_LSM303D::_register_write(uint8_t reg, uint8_t val) { uint8_t tx[2]; uint8_t rx[2]; tx[0] = reg; tx[1] = val; _spi->transaction(tx, rx, 2); } void AP_Compass_LSM303D::_register_modify(uint8_t reg, uint8_t clearbits, uint8_t setbits) { uint8_t val; val = _register_read(reg); val &= ~clearbits; val |= setbits; _register_write(reg, val); } /** * Return true if the LSM303D has new data available for both the mag and * the accels. */ bool AP_Compass_LSM303D::_data_ready() { return (_drdy_pin_m->read()) != 0; } // Read Sensor data bool AP_Compass_LSM303D::_read_raw() { if (_register_read(ADDR_CTRL_REG7) != _reg7_expected) { hal.console->println_P( PSTR("LSM303D _read_data_transaction_accel: _reg7_expected unexpected")); // reset(); return false; } if (!_data_ready()) { return false; } struct PACKED { uint8_t cmd; uint8_t status; int16_t x; int16_t y; int16_t z; } raw_mag_report_tx; struct PACKED { uint8_t cmd; uint8_t status; int16_t x; int16_t y; int16_t z; } raw_mag_report_rx; /* fetch data from the sensor */ memset(&raw_mag_report_tx, 0, sizeof(raw_mag_report_tx)); memset(&raw_mag_report_rx, 0, sizeof(raw_mag_report_rx)); raw_mag_report_tx.cmd = ADDR_STATUS_M | DIR_READ | ADDR_INCREMENT; _spi->transaction((uint8_t *)&raw_mag_report_tx, (uint8_t *)&raw_mag_report_rx, sizeof(raw_mag_report_tx)); _mag_x = raw_mag_report_rx.x; _mag_y = raw_mag_report_rx.y; _mag_z = raw_mag_report_rx.z; if (is_zero(_mag_x) && is_zero(_mag_y) && is_zero(_mag_z)) { return false; } return true; } // Public Methods ////////////////////////////////////////////////////////////// bool AP_Compass_LSM303D::init() { // TODO: support users without data ready pin if (LSM303D_DRDY_M_PIN < 0) return false; hal.scheduler->suspend_timer_procs(); _spi = hal.spi->device(AP_HAL::SPIDevice_LSM303D); _spi_sem = _spi->get_semaphore(); _drdy_pin_m = hal.gpio->channel(LSM303D_DRDY_M_PIN); _drdy_pin_m->mode(HAL_GPIO_INPUT); // Test WHOAMI uint8_t whoami = _register_read(ADDR_WHO_AM_I); if (whoami != WHO_I_AM) { hal.console->printf("LSM303D: unexpected WHOAMI 0x%x\n", (unsigned)whoami); hal.scheduler->panic(PSTR("LSM303D: bad WHOAMI")); } uint8_t tries = 0; do { // TODO: don't try to init 25 times bool success = _hardware_init(); if (success) { hal.scheduler->delay(5+2); if (!_spi_sem->take(100)) { hal.scheduler->panic(PSTR("LSM303D: Unable to get semaphore")); } if (_data_ready()) { _spi_sem->give(); break; } else { hal.console->println_P( PSTR("LSM303D startup failed: no data ready")); } _spi_sem->give(); } if (tries++ > 5) { hal.scheduler->panic(PSTR("PANIC: failed to boot LSM303D 5 times")); } } while (1); _scaling[0] = 1.0; _scaling[1] = 1.0; _scaling[2] = 1.0; /* register the compass instance in the frontend */ _compass_instance = register_compass(); set_dev_id(_compass_instance, get_dev_id()); #if CONFIG_HAL_BOARD == HAL_BOARD_LINUX && CONFIG_HAL_BOARD_SUBTYPE == HAL_BOARD_SUBTYPE_LINUX_RASPILOT set_external(_compass_instance, false); #endif hal.scheduler->register_timer_process(FUNCTOR_BIND_MEMBER(&AP_Compass_LSM303D::_update, void)); set_milligauss_ratio(_compass_instance, 1.0f); _spi_sem->give(); hal.scheduler->resume_timer_procs(); _initialised = true; return _initialised; } uint32_t AP_Compass_LSM303D::get_dev_id() { return AP_COMPASS_TYPE_LSM303D; } bool AP_Compass_LSM303D::_hardware_init(void) { if (!_spi_sem->take(100)) { hal.scheduler->panic(PSTR("LSM303D: Unable to get semaphore")); } // initially run the bus at low speed _spi->set_bus_speed(AP_HAL::SPIDeviceDriver::SPI_SPEED_LOW); // ensure the chip doesn't interpret any other bus traffic as I2C _disable_i2c(); /* enable mag */ _reg7_expected = REG7_CONT_MODE_M; _register_write(ADDR_CTRL_REG7, _reg7_expected); _register_write(ADDR_CTRL_REG5, REG5_RES_HIGH_M); _register_write(ADDR_CTRL_REG4, 0x04); // DRDY on MAG on INT2 _mag_set_range(LSM303D_MAG_DEFAULT_RANGE_GA); _mag_set_samplerate(LSM303D_MAG_DEFAULT_RATE); // TODO: Software filtering // now that we have initialised, we set the SPI bus speed to high _spi->set_bus_speed(AP_HAL::SPIDeviceDriver::SPI_SPEED_HIGH); _spi_sem->give(); return true; } void AP_Compass_LSM303D::_update() { if (hal.scheduler->micros() - _last_update_timestamp < 10000) { return; } if (!_spi_sem->take_nonblocking()) { return; } _collect_samples(); _last_update_timestamp = hal.scheduler->micros(); _spi_sem->give(); } void AP_Compass_LSM303D::_collect_samples() { if (!_initialised) { return; } if (!_read_raw()) { error("_read_raw() failed\n"); } else { Vector3f raw_field = Vector3f(_mag_x, _mag_y, _mag_z) * _mag_range_scale; uint32_t time_us = hal.scheduler->micros(); // rotate raw_field from sensor frame to body frame rotate_field(raw_field, _compass_instance); // publish raw_field (uncorrected point sample) for _scaling use publish_raw_field(raw_field, time_us, _compass_instance); // correct raw_field for known errors correct_field(raw_field, _compass_instance); // publish raw_field (corrected point sample) for EKF use publish_unfiltered_field(raw_field, time_us, _compass_instance); _mag_x_accum += raw_field.x; _mag_y_accum += raw_field.y; _mag_z_accum += raw_field.z; _accum_count++; if (_accum_count == 10) { _mag_x_accum /= 2; _mag_y_accum /= 2; _mag_z_accum /= 2; _accum_count = 5; } } } // Read Sensor data void AP_Compass_LSM303D::read() { if (!_initialised) { // someone has tried to enable a compass for the first time // mid-flight .... we can't do that yet (especially as we won't // have the right orientation!) return; } if (_accum_count == 0) { /* We're not ready to publish*/ return; } hal.scheduler->suspend_timer_procs(); Vector3f field(_mag_x_accum * _scaling[0], _mag_y_accum * _scaling[1], _mag_z_accum * _scaling[2]); field /= _accum_count; _accum_count = 0; _mag_x_accum = _mag_y_accum = _mag_z_accum = 0; hal.scheduler->resume_timer_procs(); publish_filtered_field(field, _compass_instance); } void AP_Compass_LSM303D::_disable_i2c(void) { // TODO: use the register names uint8_t a = _register_read(0x02); _register_write(0x02, (0x10 | a)); a = _register_read(0x02); _register_write(0x02, (0xF7 & a)); a = _register_read(0x15); _register_write(0x15, (0x80 | a)); a = _register_read(0x02); _register_write(0x02, (0xE7 & a)); } uint8_t AP_Compass_LSM303D::_mag_set_range(uint8_t max_ga) { uint8_t setbits = 0; uint8_t clearbits = REG6_FULL_SCALE_BITS_M; float new_scale_ga_digit = 0.0f; if (max_ga == 0) max_ga = 12; if (max_ga <= 2) { _mag_range_ga = 2; setbits |= REG6_FULL_SCALE_2GA_M; new_scale_ga_digit = 0.080f; } else if (max_ga <= 4) { _mag_range_ga = 4; setbits |= REG6_FULL_SCALE_4GA_M; new_scale_ga_digit = 0.160f; } else if (max_ga <= 8) { _mag_range_ga = 8; setbits |= REG6_FULL_SCALE_8GA_M; new_scale_ga_digit = 0.320f; } else if (max_ga <= 12) { _mag_range_ga = 12; setbits |= REG6_FULL_SCALE_12GA_M; new_scale_ga_digit = 0.479f; } else { return -1; } _mag_range_scale = new_scale_ga_digit; _register_modify(ADDR_CTRL_REG6, clearbits, setbits); return 0; } uint8_t AP_Compass_LSM303D::_mag_set_samplerate(uint16_t frequency) { uint8_t setbits = 0; uint8_t clearbits = REG5_RATE_BITS_M; if (frequency == 0) frequency = 100; if (frequency <= 25) { setbits |= REG5_RATE_25HZ_M; _mag_samplerate = 25; } else if (frequency <= 50) { setbits |= REG5_RATE_50HZ_M; _mag_samplerate = 50; } else if (frequency <= 100) { setbits |= REG5_RATE_100HZ_M; _mag_samplerate = 100; } else { return -1; } _register_modify(ADDR_CTRL_REG5, clearbits, setbits); return 0; }
wingboys/ardupilot
libraries/AP_Compass/AP_Compass_LSM303D.cpp
C++
gpl-3.0
15,994
<?php /** * SCSSPHP * * @copyright 2012-2018 Leaf Corcoran * * @license http://opensource.org/licenses/MIT MIT * * @link http://leafo.github.io/scssphp */ namespace Leafo\ScssPhp; use Leafo\ScssPhp\Block; use Leafo\ScssPhp\Compiler; use Leafo\ScssPhp\Exception\ParserException; use Leafo\ScssPhp\Node; use Leafo\ScssPhp\Type; /** * Parser * * @author Leaf Corcoran <leafot@gmail.com> */ class Parser { const SOURCE_INDEX = -1; const SOURCE_LINE = -2; const SOURCE_COLUMN = -3; /** * @var array */ protected static $precedence = [ '=' => 0, 'or' => 1, 'and' => 2, '==' => 3, '!=' => 3, '<=>' => 3, '<=' => 4, '>=' => 4, '<' => 4, '>' => 4, '+' => 5, '-' => 5, '*' => 6, '/' => 6, '%' => 6, ]; protected static $commentPattern; protected static $operatorPattern; protected static $whitePattern; private $sourceName; private $sourceIndex; private $sourcePositions; private $charset; private $count; private $env; private $inParens; private $eatWhiteDefault; private $buffer; private $utf8; private $encoding; private $patternModifiers; /** * Constructor * * @api * * @param string $sourceName * @param integer $sourceIndex * @param string $encoding */ public function __construct($sourceName, $sourceIndex = 0, $encoding = 'utf-8') { $this->sourceName = $sourceName ?: '(stdin)'; $this->sourceIndex = $sourceIndex; $this->charset = null; $this->utf8 = ! $encoding || strtolower($encoding) === 'utf-8'; $this->patternModifiers = $this->utf8 ? 'Aisu' : 'Ais'; if (empty(static::$operatorPattern)) { static::$operatorPattern = '([*\/%+-]|[!=]\=|\>\=?|\<\=\>|\<\=?|and|or)'; $commentSingle = '\/\/'; $commentMultiLeft = '\/\*'; $commentMultiRight = '\*\/'; static::$commentPattern = $commentMultiLeft . '.*?' . $commentMultiRight; static::$whitePattern = $this->utf8 ? '/' . $commentSingle . '[^\n]*\s*|(' . static::$commentPattern . ')\s*|\s+/AisuS' : '/' . $commentSingle . '[^\n]*\s*|(' . static::$commentPattern . ')\s*|\s+/AisS'; } } /** * Get source file name * * @api * * @return string */ public function getSourceName() { return $this->sourceName; } /** * Throw parser error * * @api * * @param string $msg * * @throws \Leafo\ScssPhp\Exception\ParserException */ public function throwParseError($msg = 'parse error') { list($line, /* $column */) = $this->getSourcePosition($this->count); $loc = empty($this->sourceName) ? "line: $line" : "$this->sourceName on line $line"; if ($this->peek("(.*?)(\n|$)", $m, $this->count)) { throw new ParserException("$msg: failed at `$m[1]` $loc"); } throw new ParserException("$msg: $loc"); } /** * Parser buffer * * @api * * @param string $buffer * * @return \Leafo\ScssPhp\Block */ public function parse($buffer) { // strip BOM (byte order marker) if (substr($buffer, 0, 3) === "\xef\xbb\xbf") { $buffer = substr($buffer, 3); } $this->buffer = rtrim($buffer, "\x00..\x1f"); $this->count = 0; $this->env = null; $this->inParens = false; $this->eatWhiteDefault = true; $this->saveEncoding(); $this->extractLineNumbers($buffer); $this->pushBlock(null); // root block $this->whitespace(); $this->pushBlock(null); $this->popBlock(); while ($this->parseChunk()) { ; } if ($this->count !== strlen($this->buffer)) { $this->throwParseError(); } if (! empty($this->env->parent)) { $this->throwParseError('unclosed block'); } if ($this->charset) { array_unshift($this->env->children, $this->charset); } $this->env->isRoot = true; $this->restoreEncoding(); return $this->env; } /** * Parse a value or value list * * @api * * @param string $buffer * @param string $out * * @return boolean */ public function parseValue($buffer, &$out) { $this->count = 0; $this->env = null; $this->inParens = false; $this->eatWhiteDefault = true; $this->buffer = (string) $buffer; $this->saveEncoding(); $list = $this->valueList($out); $this->restoreEncoding(); return $list; } /** * Parse a selector or selector list * * @api * * @param string $buffer * @param string $out * * @return boolean */ public function parseSelector($buffer, &$out) { $this->count = 0; $this->env = null; $this->inParens = false; $this->eatWhiteDefault = true; $this->buffer = (string) $buffer; $this->saveEncoding(); $selector = $this->selectors($out); $this->restoreEncoding(); return $selector; } /** * Parse a single chunk off the head of the buffer and append it to the * current parse environment. * * Returns false when the buffer is empty, or when there is an error. * * This function is called repeatedly until the entire document is * parsed. * * This parser is most similar to a recursive descent parser. Single * functions represent discrete grammatical rules for the language, and * they are able to capture the text that represents those rules. * * Consider the function Compiler::keyword(). (All parse functions are * structured the same.) * * The function takes a single reference argument. When calling the * function it will attempt to match a keyword on the head of the buffer. * If it is successful, it will place the keyword in the referenced * argument, advance the position in the buffer, and return true. If it * fails then it won't advance the buffer and it will return false. * * All of these parse functions are powered by Compiler::match(), which behaves * the same way, but takes a literal regular expression. Sometimes it is * more convenient to use match instead of creating a new function. * * Because of the format of the functions, to parse an entire string of * grammatical rules, you can chain them together using &&. * * But, if some of the rules in the chain succeed before one fails, then * the buffer position will be left at an invalid state. In order to * avoid this, Compiler::seek() is used to remember and set buffer positions. * * Before parsing a chain, use $s = $this->seek() to remember the current * position into $s. Then if a chain fails, use $this->seek($s) to * go back where we started. * * @return boolean */ protected function parseChunk() { $s = $this->seek(); // the directives if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] === '@') { if ($this->literal('@at-root') && ($this->selectors($selector) || true) && ($this->map($with) || true) && $this->literal('{') ) { $atRoot = $this->pushSpecialBlock(Type::T_AT_ROOT, $s); $atRoot->selector = $selector; $atRoot->with = $with; return true; } $this->seek($s); if ($this->literal('@media') && $this->mediaQueryList($mediaQueryList) && $this->literal('{')) { $media = $this->pushSpecialBlock(Type::T_MEDIA, $s); $media->queryList = $mediaQueryList[2]; return true; } $this->seek($s); if ($this->literal('@mixin') && $this->keyword($mixinName) && ($this->argumentDef($args) || true) && $this->literal('{') ) { $mixin = $this->pushSpecialBlock(Type::T_MIXIN, $s); $mixin->name = $mixinName; $mixin->args = $args; return true; } $this->seek($s); if ($this->literal('@include') && $this->keyword($mixinName) && ($this->literal('(') && ($this->argValues($argValues) || true) && $this->literal(')') || true) && ($this->end() || $this->literal('{') && $hasBlock = true) ) { $child = [Type::T_INCLUDE, $mixinName, isset($argValues) ? $argValues : null, null]; if (! empty($hasBlock)) { $include = $this->pushSpecialBlock(Type::T_INCLUDE, $s); $include->child = $child; } else { $this->append($child, $s); } return true; } $this->seek($s); if ($this->literal('@scssphp-import-once') && $this->valueList($importPath) && $this->end() ) { $this->append([Type::T_SCSSPHP_IMPORT_ONCE, $importPath], $s); return true; } $this->seek($s); if ($this->literal('@import') && $this->valueList($importPath) && $this->end() ) { $this->append([Type::T_IMPORT, $importPath], $s); return true; } $this->seek($s); if ($this->literal('@import') && $this->url($importPath) && $this->end() ) { $this->append([Type::T_IMPORT, $importPath], $s); return true; } $this->seek($s); if ($this->literal('@extend') && $this->selectors($selectors) && $this->end() ) { // check for '!flag' $optional = $this->stripOptionalFlag($selectors); $this->append([Type::T_EXTEND, $selectors, $optional], $s); return true; } $this->seek($s); if ($this->literal('@function') && $this->keyword($fnName) && $this->argumentDef($args) && $this->literal('{') ) { $func = $this->pushSpecialBlock(Type::T_FUNCTION, $s); $func->name = $fnName; $func->args = $args; return true; } $this->seek($s); if ($this->literal('@break') && $this->end()) { $this->append([Type::T_BREAK], $s); return true; } $this->seek($s); if ($this->literal('@continue') && $this->end()) { $this->append([Type::T_CONTINUE], $s); return true; } $this->seek($s); if ($this->literal('@return') && ($this->valueList($retVal) || true) && $this->end()) { $this->append([Type::T_RETURN, isset($retVal) ? $retVal : [Type::T_NULL]], $s); return true; } $this->seek($s); if ($this->literal('@each') && $this->genericList($varNames, 'variable', ',', false) && $this->literal('in') && $this->valueList($list) && $this->literal('{') ) { $each = $this->pushSpecialBlock(Type::T_EACH, $s); foreach ($varNames[2] as $varName) { $each->vars[] = $varName[1]; } $each->list = $list; return true; } $this->seek($s); if ($this->literal('@while') && $this->expression($cond) && $this->literal('{') ) { $while = $this->pushSpecialBlock(Type::T_WHILE, $s); $while->cond = $cond; return true; } $this->seek($s); if ($this->literal('@for') && $this->variable($varName) && $this->literal('from') && $this->expression($start) && ($this->literal('through') || ($forUntil = true && $this->literal('to'))) && $this->expression($end) && $this->literal('{') ) { $for = $this->pushSpecialBlock(Type::T_FOR, $s); $for->var = $varName[1]; $for->start = $start; $for->end = $end; $for->until = isset($forUntil); return true; } $this->seek($s); if ($this->literal('@if') && $this->valueList($cond) && $this->literal('{')) { $if = $this->pushSpecialBlock(Type::T_IF, $s); $if->cond = $cond; $if->cases = []; return true; } $this->seek($s); if ($this->literal('@debug') && $this->valueList($value) && $this->end() ) { $this->append([Type::T_DEBUG, $value], $s); return true; } $this->seek($s); if ($this->literal('@warn') && $this->valueList($value) && $this->end() ) { $this->append([Type::T_WARN, $value], $s); return true; } $this->seek($s); if ($this->literal('@error') && $this->valueList($value) && $this->end() ) { $this->append([Type::T_ERROR, $value], $s); return true; } $this->seek($s); if ($this->literal('@content') && $this->end()) { $this->append([Type::T_MIXIN_CONTENT], $s); return true; } $this->seek($s); $last = $this->last(); if (isset($last) && $last[0] === Type::T_IF) { list(, $if) = $last; if ($this->literal('@else')) { if ($this->literal('{')) { $else = $this->pushSpecialBlock(Type::T_ELSE, $s); } elseif ($this->literal('if') && $this->valueList($cond) && $this->literal('{')) { $else = $this->pushSpecialBlock(Type::T_ELSEIF, $s); $else->cond = $cond; } if (isset($else)) { $else->dontAppend = true; $if->cases[] = $else; return true; } } $this->seek($s); } // only retain the first @charset directive encountered if ($this->literal('@charset') && $this->valueList($charset) && $this->end() ) { if (! isset($this->charset)) { $statement = [Type::T_CHARSET, $charset]; list($line, $column) = $this->getSourcePosition($s); $statement[static::SOURCE_LINE] = $line; $statement[static::SOURCE_COLUMN] = $column; $statement[static::SOURCE_INDEX] = $this->sourceIndex; $this->charset = $statement; } return true; } $this->seek($s); // doesn't match built in directive, do generic one if ($this->literal('@', false) && $this->keyword($dirName) && ($this->variable($dirValue) || $this->openString('{', $dirValue) || true) && $this->literal('{') ) { if ($dirName === 'media') { $directive = $this->pushSpecialBlock(Type::T_MEDIA, $s); } else { $directive = $this->pushSpecialBlock(Type::T_DIRECTIVE, $s); $directive->name = $dirName; } if (isset($dirValue)) { $directive->value = $dirValue; } return true; } $this->seek($s); return false; } // property shortcut // captures most properties before having to parse a selector if ($this->keyword($name, false) && $this->literal(': ') && $this->valueList($value) && $this->end() ) { $name = [Type::T_STRING, '', [$name]]; $this->append([Type::T_ASSIGN, $name, $value], $s); return true; } $this->seek($s); // variable assigns if ($this->variable($name) && $this->literal(':') && $this->valueList($value) && $this->end() ) { // check for '!flag' $assignmentFlags = $this->stripAssignmentFlags($value); $this->append([Type::T_ASSIGN, $name, $value, $assignmentFlags], $s); return true; } $this->seek($s); // misc if ($this->literal('-->')) { return true; } // opening css block if ($this->selectors($selectors) && $this->literal('{')) { $this->pushBlock($selectors, $s); return true; } $this->seek($s); // property assign, or nested assign if ($this->propertyName($name) && $this->literal(':')) { $foundSomething = false; if ($this->valueList($value)) { $this->append([Type::T_ASSIGN, $name, $value], $s); $foundSomething = true; } if ($this->literal('{')) { $propBlock = $this->pushSpecialBlock(Type::T_NESTED_PROPERTY, $s); $propBlock->prefix = $name; $foundSomething = true; } elseif ($foundSomething) { $foundSomething = $this->end(); } if ($foundSomething) { return true; } } $this->seek($s); // closing a block if ($this->literal('}')) { $block = $this->popBlock(); if (isset($block->type) && $block->type === Type::T_INCLUDE) { $include = $block->child; unset($block->child); $include[3] = $block; $this->append($include, $s); } elseif (empty($block->dontAppend)) { $type = isset($block->type) ? $block->type : Type::T_BLOCK; $this->append([$type, $block], $s); } return true; } // extra stuff if ($this->literal(';') || $this->literal('<!--') ) { return true; } return false; } /** * Push block onto parse tree * * @param array $selectors * @param integer $pos * * @return \Leafo\ScssPhp\Block */ protected function pushBlock($selectors, $pos = 0) { list($line, $column) = $this->getSourcePosition($pos); $b = new Block; $b->sourceName = $this->sourceName; $b->sourceLine = $line; $b->sourceColumn = $column; $b->sourceIndex = $this->sourceIndex; $b->selectors = $selectors; $b->comments = []; $b->parent = $this->env; if (! $this->env) { $b->children = []; } elseif (empty($this->env->children)) { $this->env->children = $this->env->comments; $b->children = []; $this->env->comments = []; } else { $b->children = $this->env->comments; $this->env->comments = []; } $this->env = $b; return $b; } /** * Push special (named) block onto parse tree * * @param string $type * @param integer $pos * * @return \Leafo\ScssPhp\Block */ protected function pushSpecialBlock($type, $pos) { $block = $this->pushBlock(null, $pos); $block->type = $type; return $block; } /** * Pop scope and return last block * * @return \Leafo\ScssPhp\Block * * @throws \Exception */ protected function popBlock() { $block = $this->env; if (empty($block->parent)) { $this->throwParseError('unexpected }'); } $this->env = $block->parent; unset($block->parent); $comments = $block->comments; if (count($comments)) { $this->env->comments = $comments; unset($block->comments); } return $block; } /** * Peek input stream * * @param string $regex * @param array $out * @param integer $from * * @return integer */ protected function peek($regex, &$out, $from = null) { if (! isset($from)) { $from = $this->count; } $r = '/' . $regex . '/' . $this->patternModifiers; $result = preg_match($r, $this->buffer, $out, null, $from); return $result; } /** * Seek to position in input stream (or return current position in input stream) * * @param integer $where * * @return integer */ protected function seek($where = null) { if ($where === null) { return $this->count; } $this->count = $where; return true; } /** * Match string looking for either ending delim, escape, or string interpolation * * {@internal This is a workaround for preg_match's 250K string match limit. }} * * @param array $m Matches (passed by reference) * @param string $delim Delimeter * * @return boolean True if match; false otherwise */ protected function matchString(&$m, $delim) { $token = null; $end = strlen($this->buffer); // look for either ending delim, escape, or string interpolation foreach (['#{', '\\', $delim] as $lookahead) { $pos = strpos($this->buffer, $lookahead, $this->count); if ($pos !== false && $pos < $end) { $end = $pos; $token = $lookahead; } } if (! isset($token)) { return false; } $match = substr($this->buffer, $this->count, $end - $this->count); $m = [ $match . $token, $match, $token ]; $this->count = $end + strlen($token); return true; } /** * Try to match something on head of buffer * * @param string $regex * @param array $out * @param boolean $eatWhitespace * * @return boolean */ protected function match($regex, &$out, $eatWhitespace = null) { if (! isset($eatWhitespace)) { $eatWhitespace = $this->eatWhiteDefault; } $r = '/' . $regex . '/' . $this->patternModifiers; if (preg_match($r, $this->buffer, $out, null, $this->count)) { $this->count += strlen($out[0]); if ($eatWhitespace) { $this->whitespace(); } return true; } return false; } /** * Match literal string * * @param string $what * @param boolean $eatWhitespace * * @return boolean */ protected function literal($what, $eatWhitespace = null) { if (! isset($eatWhitespace)) { $eatWhitespace = $this->eatWhiteDefault; } $len = strlen($what); if (strcasecmp(substr($this->buffer, $this->count, $len), $what) === 0) { $this->count += $len; if ($eatWhitespace) { $this->whitespace(); } return true; } return false; } /** * Match some whitespace * * @return boolean */ protected function whitespace() { $gotWhite = false; while (preg_match(static::$whitePattern, $this->buffer, $m, null, $this->count)) { if (isset($m[1]) && empty($this->commentsSeen[$this->count])) { $this->appendComment([Type::T_COMMENT, $m[1]]); $this->commentsSeen[$this->count] = true; } $this->count += strlen($m[0]); $gotWhite = true; } return $gotWhite; } /** * Append comment to current block * * @param array $comment */ protected function appendComment($comment) { $comment[1] = substr(preg_replace(['/^\s+/m', '/^(.)/m'], ['', ' \1'], $comment[1]), 1); $this->env->comments[] = $comment; } /** * Append statement to current block * * @param array $statement * @param integer $pos */ protected function append($statement, $pos = null) { if ($pos !== null) { list($line, $column) = $this->getSourcePosition($pos); $statement[static::SOURCE_LINE] = $line; $statement[static::SOURCE_COLUMN] = $column; $statement[static::SOURCE_INDEX] = $this->sourceIndex; } $this->env->children[] = $statement; $comments = $this->env->comments; if (count($comments)) { $this->env->children = array_merge($this->env->children, $comments); $this->env->comments = []; } } /** * Returns last child was appended * * @return array|null */ protected function last() { $i = count($this->env->children) - 1; if (isset($this->env->children[$i])) { return $this->env->children[$i]; } } /** * Parse media query list * * @param array $out * * @return boolean */ protected function mediaQueryList(&$out) { return $this->genericList($out, 'mediaQuery', ',', false); } /** * Parse media query * * @param array $out * * @return boolean */ protected function mediaQuery(&$out) { $expressions = null; $parts = []; if (($this->literal('only') && ($only = true) || $this->literal('not') && ($not = true) || true) && $this->mixedKeyword($mediaType) ) { $prop = [Type::T_MEDIA_TYPE]; if (isset($only)) { $prop[] = [Type::T_KEYWORD, 'only']; } if (isset($not)) { $prop[] = [Type::T_KEYWORD, 'not']; } $media = [Type::T_LIST, '', []]; foreach ((array) $mediaType as $type) { if (is_array($type)) { $media[2][] = $type; } else { $media[2][] = [Type::T_KEYWORD, $type]; } } $prop[] = $media; $parts[] = $prop; } if (empty($parts) || $this->literal('and')) { $this->genericList($expressions, 'mediaExpression', 'and', false); if (is_array($expressions)) { $parts = array_merge($parts, $expressions[2]); } } $out = $parts; return true; } /** * Parse media expression * * @param array $out * * @return boolean */ protected function mediaExpression(&$out) { $s = $this->seek(); $value = null; if ($this->literal('(') && $this->expression($feature) && ($this->literal(':') && $this->expression($value) || true) && $this->literal(')') ) { $out = [Type::T_MEDIA_EXPRESSION, $feature]; if ($value) { $out[] = $value; } return true; } $this->seek($s); return false; } /** * Parse argument values * * @param array $out * * @return boolean */ protected function argValues(&$out) { if ($this->genericList($list, 'argValue', ',', false)) { $out = $list[2]; return true; } return false; } /** * Parse argument value * * @param array $out * * @return boolean */ protected function argValue(&$out) { $s = $this->seek(); $keyword = null; if (! $this->variable($keyword) || ! $this->literal(':')) { $this->seek($s); $keyword = null; } if ($this->genericList($value, 'expression')) { $out = [$keyword, $value, false]; $s = $this->seek(); if ($this->literal('...')) { $out[2] = true; } else { $this->seek($s); } return true; } return false; } /** * Parse comma separated value list * * @param string $out * * @return boolean */ protected function valueList(&$out) { return $this->genericList($out, 'spaceList', ','); } /** * Parse space separated value list * * @param array $out * * @return boolean */ protected function spaceList(&$out) { return $this->genericList($out, 'expression'); } /** * Parse generic list * * @param array $out * @param callable $parseItem * @param string $delim * @param boolean $flatten * * @return boolean */ protected function genericList(&$out, $parseItem, $delim = '', $flatten = true) { $s = $this->seek(); $items = []; while ($this->$parseItem($value)) { $items[] = $value; if ($delim) { if (! $this->literal($delim)) { break; } } } if (count($items) === 0) { $this->seek($s); return false; } if ($flatten && count($items) === 1) { $out = $items[0]; } else { $out = [Type::T_LIST, $delim, $items]; } return true; } /** * Parse expression * * @param array $out * * @return boolean */ protected function expression(&$out) { $s = $this->seek(); if ($this->literal('(')) { if ($this->literal(')')) { $out = [Type::T_LIST, '', []]; return true; } if ($this->valueList($out) && $this->literal(')') && $out[0] === Type::T_LIST) { return true; } $this->seek($s); if ($this->map($out)) { return true; } $this->seek($s); } if ($this->value($lhs)) { $out = $this->expHelper($lhs, 0); return true; } return false; } /** * Parse left-hand side of subexpression * * @param array $lhs * @param integer $minP * * @return array */ protected function expHelper($lhs, $minP) { $operators = static::$operatorPattern; $ss = $this->seek(); $whiteBefore = isset($this->buffer[$this->count - 1]) && ctype_space($this->buffer[$this->count - 1]); while ($this->match($operators, $m, false) && static::$precedence[$m[1]] >= $minP) { $whiteAfter = isset($this->buffer[$this->count]) && ctype_space($this->buffer[$this->count]); $varAfter = isset($this->buffer[$this->count]) && $this->buffer[$this->count] === '$'; $this->whitespace(); $op = $m[1]; // don't turn negative numbers into expressions if ($op === '-' && $whiteBefore && ! $whiteAfter && ! $varAfter) { break; } if (! $this->value($rhs)) { break; } // peek and see if rhs belongs to next operator if ($this->peek($operators, $next) && static::$precedence[$next[1]] > static::$precedence[$op]) { $rhs = $this->expHelper($rhs, static::$precedence[$next[1]]); } $lhs = [Type::T_EXPRESSION, $op, $lhs, $rhs, $this->inParens, $whiteBefore, $whiteAfter]; $ss = $this->seek(); $whiteBefore = isset($this->buffer[$this->count - 1]) && ctype_space($this->buffer[$this->count - 1]); } $this->seek($ss); return $lhs; } /** * Parse value * * @param array $out * * @return boolean */ protected function value(&$out) { $s = $this->seek(); if ($this->literal('not', false) && $this->whitespace() && $this->value($inner)) { $out = [Type::T_UNARY, 'not', $inner, $this->inParens]; return true; } $this->seek($s); if ($this->literal('not', false) && $this->parenValue($inner)) { $out = [Type::T_UNARY, 'not', $inner, $this->inParens]; return true; } $this->seek($s); if ($this->literal('+') && $this->value($inner)) { $out = [Type::T_UNARY, '+', $inner, $this->inParens]; return true; } $this->seek($s); // negation if ($this->literal('-', false) && ($this->variable($inner) || $this->unit($inner) || $this->parenValue($inner)) ) { $out = [Type::T_UNARY, '-', $inner, $this->inParens]; return true; } $this->seek($s); if ($this->parenValue($out) || $this->interpolation($out) || $this->variable($out) || $this->color($out) || $this->unit($out) || $this->string($out) || $this->func($out) || $this->progid($out) ) { return true; } if ($this->keyword($keyword)) { if ($keyword === 'null') { $out = [Type::T_NULL]; } else { $out = [Type::T_KEYWORD, $keyword]; } return true; } return false; } /** * Parse parenthesized value * * @param array $out * * @return boolean */ protected function parenValue(&$out) { $s = $this->seek(); $inParens = $this->inParens; if ($this->literal('(')) { if ($this->literal(')')) { $out = [Type::T_LIST, '', []]; return true; } $this->inParens = true; if ($this->expression($exp) && $this->literal(')')) { $out = $exp; $this->inParens = $inParens; return true; } } $this->inParens = $inParens; $this->seek($s); return false; } /** * Parse "progid:" * * @param array $out * * @return boolean */ protected function progid(&$out) { $s = $this->seek(); if ($this->literal('progid:', false) && $this->openString('(', $fn) && $this->literal('(') ) { $this->openString(')', $args, '('); if ($this->literal(')')) { $out = [Type::T_STRING, '', [ 'progid:', $fn, '(', $args, ')' ]]; return true; } } $this->seek($s); return false; } /** * Parse function call * * @param array $out * * @return boolean */ protected function func(&$func) { $s = $this->seek(); if ($this->keyword($name, false) && $this->literal('(') ) { if ($name === 'alpha' && $this->argumentList($args)) { $func = [Type::T_FUNCTION, $name, [Type::T_STRING, '', $args]]; return true; } if ($name !== 'expression' && ! preg_match('/^(-[a-z]+-)?calc$/', $name)) { $ss = $this->seek(); if ($this->argValues($args) && $this->literal(')')) { $func = [Type::T_FUNCTION_CALL, $name, $args]; return true; } $this->seek($ss); } if (($this->openString(')', $str, '(') || true) && $this->literal(')') ) { $args = []; if (! empty($str)) { $args[] = [null, [Type::T_STRING, '', [$str]]]; } $func = [Type::T_FUNCTION_CALL, $name, $args]; return true; } } $this->seek($s); return false; } /** * Parse function call argument list * * @param array $out * * @return boolean */ protected function argumentList(&$out) { $s = $this->seek(); $this->literal('('); $args = []; while ($this->keyword($var)) { if ($this->literal('=') && $this->expression($exp)) { $args[] = [Type::T_STRING, '', [$var . '=']]; $arg = $exp; } else { break; } $args[] = $arg; if (! $this->literal(',')) { break; } $args[] = [Type::T_STRING, '', [', ']]; } if (! $this->literal(')') || ! count($args)) { $this->seek($s); return false; } $out = $args; return true; } /** * Parse mixin/function definition argument list * * @param array $out * * @return boolean */ protected function argumentDef(&$out) { $s = $this->seek(); $this->literal('('); $args = []; while ($this->variable($var)) { $arg = [$var[1], null, false]; $ss = $this->seek(); if ($this->literal(':') && $this->genericList($defaultVal, 'expression')) { $arg[1] = $defaultVal; } else { $this->seek($ss); } $ss = $this->seek(); if ($this->literal('...')) { $sss = $this->seek(); if (! $this->literal(')')) { $this->throwParseError('... has to be after the final argument'); } $arg[2] = true; $this->seek($sss); } else { $this->seek($ss); } $args[] = $arg; if (! $this->literal(',')) { break; } } if (! $this->literal(')')) { $this->seek($s); return false; } $out = $args; return true; } /** * Parse map * * @param array $out * * @return boolean */ protected function map(&$out) { $s = $this->seek(); if (! $this->literal('(')) { return false; } $keys = []; $values = []; while ($this->genericList($key, 'expression') && $this->literal(':') && $this->genericList($value, 'expression') ) { $keys[] = $key; $values[] = $value; if (! $this->literal(',')) { break; } } if (! count($keys) || ! $this->literal(')')) { $this->seek($s); return false; } $out = [Type::T_MAP, $keys, $values]; return true; } /** * Parse color * * @param array $out * * @return boolean */ protected function color(&$out) { $color = [Type::T_COLOR]; if ($this->match('(#([0-9a-f]{6})|#([0-9a-f]{3}))', $m)) { if (isset($m[3])) { $num = hexdec($m[3]); foreach ([3, 2, 1] as $i) { $t = $num & 0xf; $color[$i] = $t << 4 | $t; $num >>= 4; } } else { $num = hexdec($m[2]); foreach ([3, 2, 1] as $i) { $color[$i] = $num & 0xff; $num >>= 8; } } $out = $color; return true; } return false; } /** * Parse number with unit * * @param array $out * * @return boolean */ protected function unit(&$unit) { if ($this->match('([0-9]*(\.)?[0-9]+)([%a-zA-Z]+)?', $m)) { $unit = new Node\Number($m[1], empty($m[3]) ? '' : $m[3]); return true; } return false; } /** * Parse string * * @param array $out * * @return boolean */ protected function string(&$out) { $s = $this->seek(); if ($this->literal('"', false)) { $delim = '"'; } elseif ($this->literal("'", false)) { $delim = "'"; } else { return false; } $content = []; $oldWhite = $this->eatWhiteDefault; $this->eatWhiteDefault = false; $hasInterpolation = false; while ($this->matchString($m, $delim)) { if ($m[1] !== '') { $content[] = $m[1]; } if ($m[2] === '#{') { $this->count -= strlen($m[2]); if ($this->interpolation($inter, false)) { $content[] = $inter; $hasInterpolation = true; } else { $this->count += strlen($m[2]); $content[] = '#{'; // ignore it } } elseif ($m[2] === '\\') { if ($this->literal('"', false)) { $content[] = $m[2] . '"'; } elseif ($this->literal("'", false)) { $content[] = $m[2] . "'"; } else { $content[] = $m[2]; } } else { $this->count -= strlen($delim); break; // delim } } $this->eatWhiteDefault = $oldWhite; if ($this->literal($delim)) { if ($hasInterpolation) { $delim = '"'; foreach ($content as &$string) { if ($string === "\\'") { $string = "'"; } elseif ($string === '\\"') { $string = '"'; } } } $out = [Type::T_STRING, $delim, $content]; return true; } $this->seek($s); return false; } /** * Parse keyword or interpolation * * @param array $out * * @return boolean */ protected function mixedKeyword(&$out) { $parts = []; $oldWhite = $this->eatWhiteDefault; $this->eatWhiteDefault = false; for (;;) { if ($this->keyword($key)) { $parts[] = $key; continue; } if ($this->interpolation($inter)) { $parts[] = $inter; continue; } break; } $this->eatWhiteDefault = $oldWhite; if (count($parts) === 0) { return false; } if ($this->eatWhiteDefault) { $this->whitespace(); } $out = $parts; return true; } /** * Parse an unbounded string stopped by $end * * @param string $end * @param array $out * @param string $nestingOpen * * @return boolean */ protected function openString($end, &$out, $nestingOpen = null) { $oldWhite = $this->eatWhiteDefault; $this->eatWhiteDefault = false; $patt = '(.*?)([\'"]|#\{|' . $this->pregQuote($end) . '|' . static::$commentPattern . ')'; $nestingLevel = 0; $content = []; while ($this->match($patt, $m, false)) { if (isset($m[1]) && $m[1] !== '') { $content[] = $m[1]; if ($nestingOpen) { $nestingLevel += substr_count($m[1], $nestingOpen); } } $tok = $m[2]; $this->count-= strlen($tok); if ($tok === $end && ! $nestingLevel--) { break; } if (($tok === "'" || $tok === '"') && $this->string($str)) { $content[] = $str; continue; } if ($tok === '#{' && $this->interpolation($inter)) { $content[] = $inter; continue; } $content[] = $tok; $this->count+= strlen($tok); } $this->eatWhiteDefault = $oldWhite; if (count($content) === 0) { return false; } // trim the end if (is_string(end($content))) { $content[count($content) - 1] = rtrim(end($content)); } $out = [Type::T_STRING, '', $content]; return true; } /** * Parser interpolation * * @param array $out * @param boolean $lookWhite save information about whitespace before and after * * @return boolean */ protected function interpolation(&$out, $lookWhite = true) { $oldWhite = $this->eatWhiteDefault; $this->eatWhiteDefault = true; $s = $this->seek(); if ($this->literal('#{') && $this->valueList($value) && $this->literal('}', false)) { if ($lookWhite) { $left = preg_match('/\s/', $this->buffer[$s - 1]) ? ' ' : ''; $right = preg_match('/\s/', $this->buffer[$this->count]) ? ' ': ''; } else { $left = $right = false; } $out = [Type::T_INTERPOLATE, $value, $left, $right]; $this->eatWhiteDefault = $oldWhite; if ($this->eatWhiteDefault) { $this->whitespace(); } return true; } $this->seek($s); $this->eatWhiteDefault = $oldWhite; return false; } /** * Parse property name (as an array of parts or a string) * * @param array $out * * @return boolean */ protected function propertyName(&$out) { $parts = []; $oldWhite = $this->eatWhiteDefault; $this->eatWhiteDefault = false; for (;;) { if ($this->interpolation($inter)) { $parts[] = $inter; continue; } if ($this->keyword($text)) { $parts[] = $text; continue; } if (count($parts) === 0 && $this->match('[:.#]', $m, false)) { // css hacks $parts[] = $m[0]; continue; } break; } $this->eatWhiteDefault = $oldWhite; if (count($parts) === 0) { return false; } // match comment hack if (preg_match( static::$whitePattern, $this->buffer, $m, null, $this->count )) { if (! empty($m[0])) { $parts[] = $m[0]; $this->count += strlen($m[0]); } } $this->whitespace(); // get any extra whitespace $out = [Type::T_STRING, '', $parts]; return true; } /** * Parse comma separated selector list * * @param array $out * * @return boolean */ protected function selectors(&$out) { $s = $this->seek(); $selectors = []; while ($this->selector($sel)) { $selectors[] = $sel; if (! $this->literal(',')) { break; } while ($this->literal(',')) { ; // ignore extra } } if (count($selectors) === 0) { $this->seek($s); return false; } $out = $selectors; return true; } /** * Parse whitespace separated selector list * * @param array $out * * @return boolean */ protected function selector(&$out) { $selector = []; for (;;) { if ($this->match('[>+~]+', $m)) { $selector[] = [$m[0]]; continue; } if ($this->selectorSingle($part)) { $selector[] = $part; $this->match('\s+', $m); continue; } if ($this->match('\/[^\/]+\/', $m)) { $selector[] = [$m[0]]; continue; } break; } if (count($selector) === 0) { return false; } $out = $selector; return true; } /** * Parse the parts that make up a selector * * {@internal * div[yes=no]#something.hello.world:nth-child(-2n+1)%placeholder * }} * * @param array $out * * @return boolean */ protected function selectorSingle(&$out) { $oldWhite = $this->eatWhiteDefault; $this->eatWhiteDefault = false; $parts = []; if ($this->literal('*', false)) { $parts[] = '*'; } for (;;) { // see if we can stop early if ($this->match('\s*[{,]', $m)) { $this->count--; break; } $s = $this->seek(); // self if ($this->literal('&', false)) { $parts[] = Compiler::$selfSelector; continue; } if ($this->literal('.', false)) { $parts[] = '.'; continue; } if ($this->literal('|', false)) { $parts[] = '|'; continue; } if ($this->match('\\\\\S', $m)) { $parts[] = $m[0]; continue; } // for keyframes if ($this->unit($unit)) { $parts[] = $unit; continue; } if ($this->keyword($name)) { $parts[] = $name; continue; } if ($this->interpolation($inter)) { $parts[] = $inter; continue; } if ($this->literal('%', false) && $this->placeholder($placeholder)) { $parts[] = '%'; $parts[] = $placeholder; continue; } if ($this->literal('#', false)) { $parts[] = '#'; continue; } // a pseudo selector if ($this->match('::?', $m) && $this->mixedKeyword($nameParts)) { $parts[] = $m[0]; foreach ($nameParts as $sub) { $parts[] = $sub; } $ss = $this->seek(); if ($this->literal('(') && ($this->openString(')', $str, '(') || true) && $this->literal(')') ) { $parts[] = '('; if (! empty($str)) { $parts[] = $str; } $parts[] = ')'; } else { $this->seek($ss); } continue; } $this->seek($s); // attribute selector if ($this->literal('[') && ($this->openString(']', $str, '[') || true) && $this->literal(']') ) { $parts[] = '['; if (! empty($str)) { $parts[] = $str; } $parts[] = ']'; continue; } $this->seek($s); break; } $this->eatWhiteDefault = $oldWhite; if (count($parts) === 0) { return false; } $out = $parts; return true; } /** * Parse a variable * * @param array $out * * @return boolean */ protected function variable(&$out) { $s = $this->seek(); if ($this->literal('$', false) && $this->keyword($name)) { $out = [Type::T_VARIABLE, $name]; return true; } $this->seek($s); return false; } /** * Parse a keyword * * @param string $word * @param boolean $eatWhitespace * * @return boolean */ protected function keyword(&$word, $eatWhitespace = null) { if ($this->match( $this->utf8 ? '(([\pL\w_\-\*!"\']|[\\\\].)([\pL\w\-_"\']|[\\\\].)*)' : '(([\w_\-\*!"\']|[\\\\].)([\w\-_"\']|[\\\\].)*)', $m, $eatWhitespace )) { $word = $m[1]; return true; } return false; } /** * Parse a placeholder * * @param string $placeholder * * @return boolean */ protected function placeholder(&$placeholder) { if ($this->match( $this->utf8 ? '([\pL\w\-_]+|#[{][$][\pL\w\-_]+[}])' : '([\w\-_]+|#[{][$][\w\-_]+[}])', $m )) { $placeholder = $m[1]; return true; } return false; } /** * Parse a url * * @param array $out * * @return boolean */ protected function url(&$out) { if ($this->match('(url\(\s*(["\']?)([^)]+)\2\s*\))', $m)) { $out = [Type::T_STRING, '', ['url(' . $m[2] . $m[3] . $m[2] . ')']]; return true; } return false; } /** * Consume an end of statement delimiter * * @return boolean */ protected function end() { if ($this->literal(';')) { return true; } if ($this->count === strlen($this->buffer) || $this->buffer[$this->count] === '}') { // if there is end of file or a closing block next then we don't need a ; return true; } return false; } /** * Strip assignment flag from the list * * @param array $value * * @return array */ protected function stripAssignmentFlags(&$value) { $flags = []; for ($token = &$value; $token[0] === Type::T_LIST && ($s = count($token[2])); $token = &$lastNode) { $lastNode = &$token[2][$s - 1]; while ($lastNode[0] === Type::T_KEYWORD && in_array($lastNode[1], ['!default', '!global'])) { array_pop($token[2]); $node = end($token[2]); $token = $this->flattenList($token); $flags[] = $lastNode[1]; $lastNode = $node; } } return $flags; } /** * Strip optional flag from selector list * * @param array $selectors * * @return string */ protected function stripOptionalFlag(&$selectors) { $optional = false; $selector = end($selectors); $part = end($selector); if ($part === ['!optional']) { array_pop($selectors[count($selectors) - 1]); $optional = true; } return $optional; } /** * Turn list of length 1 into value type * * @param array $value * * @return array */ protected function flattenList($value) { if ($value[0] === Type::T_LIST && count($value[2]) === 1) { return $this->flattenList($value[2][0]); } return $value; } /** * @deprecated * * {@internal * advance counter to next occurrence of $what * $until - don't include $what in advance * $allowNewline, if string, will be used as valid char set * }} */ protected function to($what, &$out, $until = false, $allowNewline = false) { if (is_string($allowNewline)) { $validChars = $allowNewline; } else { $validChars = $allowNewline ? '.' : "[^\n]"; } if (! $this->match('(' . $validChars . '*?)' . $this->pregQuote($what), $m, ! $until)) { return false; } if ($until) { $this->count -= strlen($what); // give back $what } $out = $m[1]; return true; } /** * @deprecated */ protected function show() { if ($this->peek("(.*?)(\n|$)", $m, $this->count)) { return $m[1]; } return ''; } /** * Quote regular expression * * @param string $what * * @return string */ private function pregQuote($what) { return preg_quote($what, '/'); } /** * Extract line numbers from buffer * * @param string $buffer */ private function extractLineNumbers($buffer) { $this->sourcePositions = [0 => 0]; $prev = 0; while (($pos = strpos($buffer, "\n", $prev)) !== false) { $this->sourcePositions[] = $pos; $prev = $pos + 1; } $this->sourcePositions[] = strlen($buffer); if (substr($buffer, -1) !== "\n") { $this->sourcePositions[] = strlen($buffer) + 1; } } /** * Get source line number and column (given character position in the buffer) * * @param integer $pos * * @return integer */ private function getSourcePosition($pos) { $low = 0; $high = count($this->sourcePositions); while ($low < $high) { $mid = (int) (($high + $low) / 2); if ($pos < $this->sourcePositions[$mid]) { $high = $mid - 1; continue; } if ($pos >= $this->sourcePositions[$mid + 1]) { $low = $mid + 1; continue; } return [$mid + 1, $pos - $this->sourcePositions[$mid]]; } return [$low + 1, $pos - $this->sourcePositions[$low]]; } /** * Save internal encoding */ private function saveEncoding() { if (version_compare(PHP_VERSION, '7.2.0') >= 0) { return; } $iniDirective = 'mbstring' . '.func_overload'; // deprecated in PHP 7.2 if (ini_get($iniDirective) & 2) { $this->encoding = mb_internal_encoding(); mb_internal_encoding('iso-8859-1'); } } /** * Restore internal encoding */ private function restoreEncoding() { if ($this->encoding) { mb_internal_encoding($this->encoding); } } }
Felix-Ho/opencart
upload/system/storage/vendor/leafo/scssphp/src/Parser.php
PHP
gpl-3.0
60,401
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "dex_file.h" #include <fcntl.h> #include <limits.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/file.h> #include <sys/stat.h> #include "base/logging.h" #include "base/stringprintf.h" #include "class_linker.h" #include "dex_file-inl.h" #include "dex_file_verifier.h" #include "globals.h" #include "leb128.h" #include "mirror/art_field-inl.h" #include "mirror/art_method-inl.h" #include "mirror/string.h" #include "os.h" #include "safe_map.h" #include "thread.h" #include "UniquePtr.h" #include "utf.h" #include "utils.h" #include "well_known_classes.h" #include "zip_archive.h" namespace art { const byte DexFile::kDexMagic[] = { 'd', 'e', 'x', '\n' }; const byte DexFile::kDexMagicVersion[] = { '0', '3', '5', '\0' }; DexFile::ClassPathEntry DexFile::FindInClassPath(const char* descriptor, const ClassPath& class_path) { for (size_t i = 0; i != class_path.size(); ++i) { const DexFile* dex_file = class_path[i]; const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor); if (dex_class_def != NULL) { return ClassPathEntry(dex_file, dex_class_def); } } // TODO: remove reinterpret_cast when issue with -std=gnu++0x host issue resolved return ClassPathEntry(reinterpret_cast<const DexFile*>(NULL), reinterpret_cast<const DexFile::ClassDef*>(NULL)); } int OpenAndReadMagic(const std::string& filename, uint32_t* magic) { CHECK(magic != NULL); int fd = open(filename.c_str(), O_RDONLY, 0); if (fd == -1) { PLOG(WARNING) << "Unable to open '" << filename << "'"; return -1; } int n = TEMP_FAILURE_RETRY(read(fd, magic, sizeof(*magic))); if (n != sizeof(*magic)) { PLOG(ERROR) << "Failed to find magic in '" << filename << "'"; return -1; } if (lseek(fd, 0, SEEK_SET) != 0) { PLOG(ERROR) << "Failed to seek to beginning of file '" << filename << "'"; return -1; } return fd; } bool DexFile::GetChecksum(const std::string& filename, uint32_t* checksum) { CHECK(checksum != NULL); uint32_t magic; int fd = OpenAndReadMagic(filename, &magic); if (fd == -1) { return false; } if (IsZipMagic(magic)) { UniquePtr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd)); if (zip_archive.get() == NULL) { return false; } UniquePtr<ZipEntry> zip_entry(zip_archive->Find(kClassesDex)); if (zip_entry.get() == NULL) { LOG(ERROR) << "Zip archive '" << filename << "' doesn't contain " << kClassesDex; return false; } *checksum = zip_entry->GetCrc32(); return true; } if (IsDexMagic(magic)) { UniquePtr<const DexFile> dex_file(DexFile::OpenFile(fd, filename, false)); if (dex_file.get() == NULL) { return false; } *checksum = dex_file->GetHeader().checksum_; return true; } LOG(ERROR) << "Expected valid zip or dex file: " << filename; return false; } const DexFile* DexFile::Open(const std::string& filename, const std::string& location) { uint32_t magic; int fd = OpenAndReadMagic(filename, &magic); if (fd == -1) { return NULL; } if (IsZipMagic(magic)) { return DexFile::OpenZip(fd, location); } if (IsDexMagic(magic)) { return DexFile::OpenFile(fd, location, true); } LOG(ERROR) << "Expected valid zip or dex file: " << filename; return NULL; } int DexFile::GetPermissions() const { if (mem_map_.get() == NULL) { return 0; } else { return mem_map_->GetProtect(); } } bool DexFile::IsReadOnly() const { return GetPermissions() == PROT_READ; } bool DexFile::EnableWrite() const { CHECK(IsReadOnly()); if (mem_map_.get() == NULL) { return false; } else { return mem_map_->Protect(PROT_READ | PROT_WRITE); } } bool DexFile::DisableWrite() const { CHECK(!IsReadOnly()); if (mem_map_.get() == NULL) { return false; } else { return mem_map_->Protect(PROT_READ); } } const DexFile* DexFile::OpenFile(int fd, const std::string& location, bool verify) { CHECK(!location.empty()); struct stat sbuf; memset(&sbuf, 0, sizeof(sbuf)); if (fstat(fd, &sbuf) == -1) { PLOG(ERROR) << "fstat \"" << location << "\" failed"; close(fd); return NULL; } if (S_ISDIR(sbuf.st_mode)) { LOG(ERROR) << "attempt to mmap directory \"" << location << "\""; return NULL; } size_t length = sbuf.st_size; UniquePtr<MemMap> map(MemMap::MapFile(length, PROT_READ, MAP_PRIVATE, fd, 0)); if (map.get() == NULL) { LOG(ERROR) << "mmap \"" << location << "\" failed"; close(fd); return NULL; } close(fd); if (map->Size() < sizeof(DexFile::Header)) { LOG(ERROR) << "Failed to open dex file '" << location << "' that is too short to have a header"; return NULL; } const Header* dex_header = reinterpret_cast<const Header*>(map->Begin()); const DexFile* dex_file = OpenMemory(location, dex_header->checksum_, map.release()); if (dex_file == NULL) { LOG(ERROR) << "Failed to open dex file '" << location << "' from memory"; return NULL; } if (verify && !DexFileVerifier::Verify(dex_file, dex_file->Begin(), dex_file->Size())) { LOG(ERROR) << "Failed to verify dex file '" << location << "'"; return NULL; } return dex_file; } const char* DexFile::kClassesDex = "classes.dex"; const DexFile* DexFile::OpenZip(int fd, const std::string& location) { UniquePtr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd)); if (zip_archive.get() == NULL) { LOG(ERROR) << "Failed to open " << location << " when looking for classes.dex"; return NULL; } return DexFile::Open(*zip_archive.get(), location); } const DexFile* DexFile::OpenMemory(const std::string& location, uint32_t location_checksum, MemMap* mem_map) { return OpenMemory(mem_map->Begin(), mem_map->Size(), location, location_checksum, mem_map); } const DexFile* DexFile::Open(const ZipArchive& zip_archive, const std::string& location) { CHECK(!location.empty()); UniquePtr<ZipEntry> zip_entry(zip_archive.Find(kClassesDex)); if (zip_entry.get() == NULL) { LOG(ERROR) << "Failed to find classes.dex within '" << location << "'"; return NULL; } UniquePtr<MemMap> map(zip_entry->ExtractToMemMap(kClassesDex)); if (map.get() == NULL) { LOG(ERROR) << "Failed to extract '" << kClassesDex << "' from '" << location << "'"; return NULL; } UniquePtr<const DexFile> dex_file(OpenMemory(location, zip_entry->GetCrc32(), map.release())); if (dex_file.get() == NULL) { LOG(ERROR) << "Failed to open dex file '" << location << "' from memory"; return NULL; } if (!DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size())) { LOG(ERROR) << "Failed to verify dex file '" << location << "'"; return NULL; } if (!dex_file->DisableWrite()) { LOG(ERROR) << "Failed to make dex file read only '" << location << "'"; return NULL; } CHECK(dex_file->IsReadOnly()) << location; return dex_file.release(); } const DexFile* DexFile::OpenMemory(const byte* base, size_t size, const std::string& location, uint32_t location_checksum, MemMap* mem_map) { CHECK_ALIGNED(base, 4); // various dex file structures must be word aligned UniquePtr<DexFile> dex_file(new DexFile(base, size, location, location_checksum, mem_map)); if (!dex_file->Init()) { return NULL; } else { return dex_file.release(); } } DexFile::~DexFile() { // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could // re-attach, but cleaning up these global references is not obviously useful. It's not as if // the global reference table is otherwise empty! } bool DexFile::Init() { InitMembers(); if (!CheckMagicAndVersion()) { return false; } return true; } void DexFile::InitMembers() { const byte* b = begin_; header_ = reinterpret_cast<const Header*>(b); const Header* h = header_; string_ids_ = reinterpret_cast<const StringId*>(b + h->string_ids_off_); type_ids_ = reinterpret_cast<const TypeId*>(b + h->type_ids_off_); field_ids_ = reinterpret_cast<const FieldId*>(b + h->field_ids_off_); method_ids_ = reinterpret_cast<const MethodId*>(b + h->method_ids_off_); proto_ids_ = reinterpret_cast<const ProtoId*>(b + h->proto_ids_off_); class_defs_ = reinterpret_cast<const ClassDef*>(b + h->class_defs_off_); class_defs_off_=h->class_defs_off_; data_off_=h->data_off_; data_size_=h->data_size_; } bool DexFile::CheckMagicAndVersion() const { CHECK(header_->magic_ != NULL) << GetLocation(); if (!IsMagicValid(header_->magic_)) { LOG(ERROR) << "Unrecognized magic number in " << GetLocation() << ":" << " " << header_->magic_[0] << " " << header_->magic_[1] << " " << header_->magic_[2] << " " << header_->magic_[3]; return false; } if (!IsVersionValid(header_->magic_)) { LOG(ERROR) << "Unrecognized version number in " << GetLocation() << ":" << " " << header_->magic_[4] << " " << header_->magic_[5] << " " << header_->magic_[6] << " " << header_->magic_[7]; return false; } return true; } bool DexFile::IsMagicValid(const byte* magic) { return (memcmp(magic, kDexMagic, sizeof(kDexMagic)) == 0); } bool DexFile::IsVersionValid(const byte* magic) { const byte* version = &magic[sizeof(kDexMagic)]; return (memcmp(version, kDexMagicVersion, sizeof(kDexMagicVersion)) == 0); } uint32_t DexFile::GetVersion() const { const char* version = reinterpret_cast<const char*>(&GetHeader().magic_[sizeof(kDexMagic)]); return atoi(version); } const DexFile::ClassDef* DexFile::FindClassDef(const char* descriptor) const { size_t num_class_defs = NumClassDefs(); if (num_class_defs == 0) { return NULL; } const StringId* string_id = FindStringId(descriptor); if (string_id == NULL) { return NULL; } const TypeId* type_id = FindTypeId(GetIndexForStringId(*string_id)); if (type_id == NULL) { return NULL; } uint16_t type_idx = GetIndexForTypeId(*type_id); for (size_t i = 0; i < num_class_defs; ++i) { const ClassDef& class_def = GetClassDef(i); if (class_def.class_idx_ == type_idx) { return &class_def; } } return NULL; } const DexFile::ClassDef* DexFile::FindClassDef(uint16_t type_idx) const { size_t num_class_defs = NumClassDefs(); for (size_t i = 0; i < num_class_defs; ++i) { const ClassDef& class_def = GetClassDef(i); if (class_def.class_idx_ == type_idx) { return &class_def; } } return NULL; } const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass, const DexFile::StringId& name, const DexFile::TypeId& type) const { // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx const uint16_t class_idx = GetIndexForTypeId(declaring_klass); const uint32_t name_idx = GetIndexForStringId(name); const uint16_t type_idx = GetIndexForTypeId(type); int32_t lo = 0; int32_t hi = NumFieldIds() - 1; while (hi >= lo) { int32_t mid = (hi + lo) / 2; const DexFile::FieldId& field = GetFieldId(mid); if (class_idx > field.class_idx_) { lo = mid + 1; } else if (class_idx < field.class_idx_) { hi = mid - 1; } else { if (name_idx > field.name_idx_) { lo = mid + 1; } else if (name_idx < field.name_idx_) { hi = mid - 1; } else { if (type_idx > field.type_idx_) { lo = mid + 1; } else if (type_idx < field.type_idx_) { hi = mid - 1; } else { return &field; } } } } return NULL; } const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass, const DexFile::StringId& name, const DexFile::ProtoId& signature) const { // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx const uint16_t class_idx = GetIndexForTypeId(declaring_klass); const uint32_t name_idx = GetIndexForStringId(name); const uint16_t proto_idx = GetIndexForProtoId(signature); int32_t lo = 0; int32_t hi = NumMethodIds() - 1; while (hi >= lo) { int32_t mid = (hi + lo) / 2; const DexFile::MethodId& method = GetMethodId(mid); if (class_idx > method.class_idx_) { lo = mid + 1; } else if (class_idx < method.class_idx_) { hi = mid - 1; } else { if (name_idx > method.name_idx_) { lo = mid + 1; } else if (name_idx < method.name_idx_) { hi = mid - 1; } else { if (proto_idx > method.proto_idx_) { lo = mid + 1; } else if (proto_idx < method.proto_idx_) { hi = mid - 1; } else { return &method; } } } } return NULL; } const DexFile::StringId* DexFile::FindStringId(const char* string) const { int32_t lo = 0; int32_t hi = NumStringIds() - 1; while (hi >= lo) { int32_t mid = (hi + lo) / 2; uint32_t length; const DexFile::StringId& str_id = GetStringId(mid); const char* str = GetStringDataAndLength(str_id, &length); int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str); if (compare > 0) { lo = mid + 1; } else if (compare < 0) { hi = mid - 1; } else { return &str_id; } } return NULL; } const DexFile::StringId* DexFile::FindStringId(const uint16_t* string) const { int32_t lo = 0; int32_t hi = NumStringIds() - 1; while (hi >= lo) { int32_t mid = (hi + lo) / 2; uint32_t length; const DexFile::StringId& str_id = GetStringId(mid); const char* str = GetStringDataAndLength(str_id, &length); int compare = CompareModifiedUtf8ToUtf16AsCodePointValues(str, string); if (compare > 0) { lo = mid + 1; } else if (compare < 0) { hi = mid - 1; } else { return &str_id; } } return NULL; } const DexFile::TypeId* DexFile::FindTypeId(uint32_t string_idx) const { int32_t lo = 0; int32_t hi = NumTypeIds() - 1; while (hi >= lo) { int32_t mid = (hi + lo) / 2; const TypeId& type_id = GetTypeId(mid); if (string_idx > type_id.descriptor_idx_) { lo = mid + 1; } else if (string_idx < type_id.descriptor_idx_) { hi = mid - 1; } else { return &type_id; } } return NULL; } const DexFile::ProtoId* DexFile::FindProtoId(uint16_t return_type_idx, const std::vector<uint16_t>& signature_type_idxs) const { int32_t lo = 0; int32_t hi = NumProtoIds() - 1; while (hi >= lo) { int32_t mid = (hi + lo) / 2; const DexFile::ProtoId& proto = GetProtoId(mid); int compare = return_type_idx - proto.return_type_idx_; if (compare == 0) { DexFileParameterIterator it(*this, proto); size_t i = 0; while (it.HasNext() && i < signature_type_idxs.size() && compare == 0) { compare = signature_type_idxs[i] - it.GetTypeIdx(); it.Next(); i++; } if (compare == 0) { if (it.HasNext()) { compare = -1; } else if (i < signature_type_idxs.size()) { compare = 1; } } } if (compare > 0) { lo = mid + 1; } else if (compare < 0) { hi = mid - 1; } else { return &proto; } } return NULL; } // Given a signature place the type ids into the given vector bool DexFile::CreateTypeList(uint16_t* return_type_idx, std::vector<uint16_t>* param_type_idxs, const std::string& signature) const { if (signature[0] != '(') { return false; } size_t offset = 1; size_t end = signature.size(); bool process_return = false; while (offset < end) { char c = signature[offset]; offset++; if (c == ')') { process_return = true; continue; } std::string descriptor; descriptor += c; while (c == '[') { // process array prefix if (offset >= end) { // expect some descriptor following [ return false; } c = signature[offset]; offset++; descriptor += c; } if (c == 'L') { // process type descriptors do { if (offset >= end) { // unexpected early termination of descriptor return false; } c = signature[offset]; offset++; descriptor += c; } while (c != ';'); } const DexFile::StringId* string_id = FindStringId(descriptor.c_str()); if (string_id == NULL) { return false; } const DexFile::TypeId* type_id = FindTypeId(GetIndexForStringId(*string_id)); if (type_id == NULL) { return false; } uint16_t type_idx = GetIndexForTypeId(*type_id); if (!process_return) { param_type_idxs->push_back(type_idx); } else { *return_type_idx = type_idx; return offset == end; // return true if the signature had reached a sensible end } } return false; // failed to correctly parse return type } // Materializes the method descriptor for a method prototype. Method // descriptors are not stored directly in the dex file. Instead, one // must assemble the descriptor from references in the prototype. std::string DexFile::CreateMethodSignature(uint32_t proto_idx, int32_t* unicode_length) const { const ProtoId& proto_id = GetProtoId(proto_idx); std::string descriptor; descriptor.push_back('('); const TypeList* type_list = GetProtoParameters(proto_id); size_t parameter_length = 0; if (type_list != NULL) { // A non-zero number of arguments. Append the type names. for (size_t i = 0; i < type_list->Size(); ++i) { const TypeItem& type_item = type_list->GetTypeItem(i); uint32_t type_idx = type_item.type_idx_; uint32_t type_length; const char* name = StringByTypeIdx(type_idx, &type_length); parameter_length += type_length; descriptor.append(name); } } descriptor.push_back(')'); uint32_t return_type_idx = proto_id.return_type_idx_; uint32_t return_type_length; const char* name = StringByTypeIdx(return_type_idx, &return_type_length); descriptor.append(name); if (unicode_length != NULL) { *unicode_length = parameter_length + return_type_length + 2; // 2 for ( and ) } return descriptor; } int32_t DexFile::GetLineNumFromPC(const mirror::ArtMethod* method, uint32_t rel_pc) const { // For native method, lineno should be -2 to indicate it is native. Note that // "line number == -2" is how libcore tells from StackTraceElement. if (method->GetCodeItemOffset() == 0) { return -2; } const CodeItem* code_item = GetCodeItem(method->GetCodeItemOffset()); DCHECK(code_item != NULL) << PrettyMethod(method) << " " << GetLocation(); // A method with no line number info should return -1 LineNumFromPcContext context(rel_pc, -1); DecodeDebugInfo(code_item, method->IsStatic(), method->GetDexMethodIndex(), LineNumForPcCb, NULL, &context); return context.line_num_; } int32_t DexFile::FindTryItem(const CodeItem &code_item, uint32_t address) { // Note: Signed type is important for max and min. int32_t min = 0; int32_t max = code_item.tries_size_ - 1; while (min <= max) { int32_t mid = min + ((max - min) / 2); const art::DexFile::TryItem* ti = GetTryItems(code_item, mid); uint32_t start = ti->start_addr_; uint32_t end = start + ti->insn_count_; if (address < start) { max = mid - 1; } else if (address >= end) { min = mid + 1; } else { // We have a winner! return mid; } } // No match. return -1; } int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, uint32_t address) { int32_t try_item = FindTryItem(code_item, address); if (try_item == -1) { return -1; } else { return DexFile::GetTryItems(code_item, try_item)->handler_off_; } } void DexFile::DecodeDebugInfo0(const CodeItem* code_item, bool is_static, uint32_t method_idx, DexDebugNewPositionCb position_cb, DexDebugNewLocalCb local_cb, void* context, const byte* stream, LocalInfo* local_in_reg) const { uint32_t line = DecodeUnsignedLeb128(&stream); uint32_t parameters_size = DecodeUnsignedLeb128(&stream); uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_; uint32_t address = 0; bool need_locals = (local_cb != NULL); if (!is_static) { if (need_locals) { const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx)); local_in_reg[arg_reg].name_ = "this"; local_in_reg[arg_reg].descriptor_ = descriptor; local_in_reg[arg_reg].signature_ = NULL; local_in_reg[arg_reg].start_address_ = 0; local_in_reg[arg_reg].is_live_ = true; } arg_reg++; } DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx))); for (uint32_t i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) { if (arg_reg >= code_item->registers_size_) { LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg << " >= " << code_item->registers_size_ << ") in " << GetLocation(); return; } uint32_t id = DecodeUnsignedLeb128P1(&stream); const char* descriptor = it.GetDescriptor(); if (need_locals && id != kDexNoIndex) { const char* name = StringDataByIdx(id); local_in_reg[arg_reg].name_ = name; local_in_reg[arg_reg].descriptor_ = descriptor; local_in_reg[arg_reg].signature_ = NULL; local_in_reg[arg_reg].start_address_ = address; local_in_reg[arg_reg].is_live_ = true; } switch (*descriptor) { case 'D': case 'J': arg_reg += 2; break; default: arg_reg += 1; break; } } if (it.HasNext()) { LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation(); return; } for (;;) { uint8_t opcode = *stream++; uint16_t reg; uint16_t name_idx; uint16_t descriptor_idx; uint16_t signature_idx = 0; switch (opcode) { case DBG_END_SEQUENCE: return; case DBG_ADVANCE_PC: address += DecodeUnsignedLeb128(&stream); break; case DBG_ADVANCE_LINE: line += DecodeSignedLeb128(&stream); break; case DBG_START_LOCAL: case DBG_START_LOCAL_EXTENDED: reg = DecodeUnsignedLeb128(&stream); if (reg > code_item->registers_size_) { LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > " << code_item->registers_size_ << ") in " << GetLocation(); return; } name_idx = DecodeUnsignedLeb128P1(&stream); descriptor_idx = DecodeUnsignedLeb128P1(&stream); if (opcode == DBG_START_LOCAL_EXTENDED) { signature_idx = DecodeUnsignedLeb128P1(&stream); } // Emit what was previously there, if anything if (need_locals) { InvokeLocalCbIfLive(context, reg, address, local_in_reg, local_cb); local_in_reg[reg].name_ = StringDataByIdx(name_idx); local_in_reg[reg].descriptor_ = StringByTypeIdx(descriptor_idx); if (opcode == DBG_START_LOCAL_EXTENDED) { local_in_reg[reg].signature_ = StringDataByIdx(signature_idx); } local_in_reg[reg].start_address_ = address; local_in_reg[reg].is_live_ = true; } break; case DBG_END_LOCAL: reg = DecodeUnsignedLeb128(&stream); if (reg > code_item->registers_size_) { LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > " << code_item->registers_size_ << ") in " << GetLocation(); return; } if (need_locals) { InvokeLocalCbIfLive(context, reg, address, local_in_reg, local_cb); local_in_reg[reg].is_live_ = false; } break; case DBG_RESTART_LOCAL: reg = DecodeUnsignedLeb128(&stream); if (reg > code_item->registers_size_) { LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > " << code_item->registers_size_ << ") in " << GetLocation(); return; } if (need_locals) { if (local_in_reg[reg].name_ == NULL || local_in_reg[reg].descriptor_ == NULL) { LOG(ERROR) << "invalid stream - no name or descriptor in " << GetLocation(); return; } // If the register is live, the "restart" is superfluous, // and we don't want to mess with the existing start address. if (!local_in_reg[reg].is_live_) { local_in_reg[reg].start_address_ = address; local_in_reg[reg].is_live_ = true; } } break; case DBG_SET_PROLOGUE_END: case DBG_SET_EPILOGUE_BEGIN: case DBG_SET_FILE: break; default: { int adjopcode = opcode - DBG_FIRST_SPECIAL; address += adjopcode / DBG_LINE_RANGE; line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE); if (position_cb != NULL) { if (position_cb(context, address, line)) { // early exit return; } } break; } } } } void DexFile::DecodeDebugInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx, DexDebugNewPositionCb position_cb, DexDebugNewLocalCb local_cb, void* context) const { const byte* stream = GetDebugInfoStream(code_item); UniquePtr<LocalInfo[]> local_in_reg(local_cb != NULL ? new LocalInfo[code_item->registers_size_] : NULL); if (stream != NULL) { DecodeDebugInfo0(code_item, is_static, method_idx, position_cb, local_cb, context, stream, &local_in_reg[0]); } for (int reg = 0; reg < code_item->registers_size_; reg++) { InvokeLocalCbIfLive(context, reg, code_item->insns_size_in_code_units_, &local_in_reg[0], local_cb); } } bool DexFile::LineNumForPcCb(void* raw_context, uint32_t address, uint32_t line_num) { LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(raw_context); // We know that this callback will be called in // ascending address order, so keep going until we find // a match or we've just gone past it. if (address > context->address_) { // The line number from the previous positions callback // wil be the final result. return true; } else { context->line_num_ = line_num; return address == context->address_; } } // Decodes the header section from the class data bytes. void ClassDataItemIterator::ReadClassDataHeader() { CHECK(ptr_pos_ != NULL); header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_); header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_); header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_); header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_); } void ClassDataItemIterator::ReadClassDataField() { field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_); field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_); if (last_idx_ != 0 && field_.field_idx_delta_ == 0) { LOG(WARNING) << "Duplicate field " << PrettyField(GetMemberIndex(), dex_file_) << " in " << dex_file_.GetLocation(); } } void ClassDataItemIterator::ReadClassDataMethod() { method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_); method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_); method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_); if (last_idx_ != 0 && method_.method_idx_delta_ == 0) { LOG(WARNING) << "Duplicate method " << PrettyMethod(GetMemberIndex(), dex_file_) << " in " << dex_file_.GetLocation(); } } // Read a signed integer. "zwidth" is the zero-based byte count. static int32_t ReadSignedInt(const byte* ptr, int zwidth) { int32_t val = 0; for (int i = zwidth; i >= 0; --i) { val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24); } val >>= (3 - zwidth) * 8; return val; } // Read an unsigned integer. "zwidth" is the zero-based byte count, // "fill_on_right" indicates which side we want to zero-fill from. static uint32_t ReadUnsignedInt(const byte* ptr, int zwidth, bool fill_on_right) { uint32_t val = 0; if (!fill_on_right) { for (int i = zwidth; i >= 0; --i) { val = (val >> 8) | (((uint32_t)*ptr++) << 24); } val >>= (3 - zwidth) * 8; } else { for (int i = zwidth; i >= 0; --i) { val = (val >> 8) | (((uint32_t)*ptr++) << 24); } } return val; } // Read a signed long. "zwidth" is the zero-based byte count. static int64_t ReadSignedLong(const byte* ptr, int zwidth) { int64_t val = 0; for (int i = zwidth; i >= 0; --i) { val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56); } val >>= (7 - zwidth) * 8; return val; } // Read an unsigned long. "zwidth" is the zero-based byte count, // "fill_on_right" indicates which side we want to zero-fill from. static uint64_t ReadUnsignedLong(const byte* ptr, int zwidth, bool fill_on_right) { uint64_t val = 0; if (!fill_on_right) { for (int i = zwidth; i >= 0; --i) { val = (val >> 8) | (((uint64_t)*ptr++) << 56); } val >>= (7 - zwidth) * 8; } else { for (int i = zwidth; i >= 0; --i) { val = (val >> 8) | (((uint64_t)*ptr++) << 56); } } return val; } EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(const DexFile& dex_file, mirror::DexCache* dex_cache, mirror::ClassLoader* class_loader, ClassLinker* linker, const DexFile::ClassDef& class_def) : dex_file_(dex_file), dex_cache_(dex_cache), class_loader_(class_loader), linker_(linker), array_size_(), pos_(-1), type_(kByte) { ptr_ = dex_file.GetEncodedStaticFieldValuesArray(class_def); if (ptr_ == NULL) { array_size_ = 0; } else { array_size_ = DecodeUnsignedLeb128(&ptr_); } if (array_size_ > 0) { Next(); } } void EncodedStaticFieldValueIterator::Next() { pos_++; if (pos_ >= array_size_) { return; } byte value_type = *ptr_++; byte value_arg = value_type >> kEncodedValueArgShift; size_t width = value_arg + 1; // assume and correct later type_ = static_cast<ValueType>(value_type & kEncodedValueTypeMask); switch (type_) { case kBoolean: jval_.i = (value_arg != 0) ? 1 : 0; width = 0; break; case kByte: jval_.i = ReadSignedInt(ptr_, value_arg); CHECK(IsInt(8, jval_.i)); break; case kShort: jval_.i = ReadSignedInt(ptr_, value_arg); CHECK(IsInt(16, jval_.i)); break; case kChar: jval_.i = ReadUnsignedInt(ptr_, value_arg, false); CHECK(IsUint(16, jval_.i)); break; case kInt: jval_.i = ReadSignedInt(ptr_, value_arg); break; case kLong: jval_.j = ReadSignedLong(ptr_, value_arg); break; case kFloat: jval_.i = ReadUnsignedInt(ptr_, value_arg, true); break; case kDouble: jval_.j = ReadUnsignedLong(ptr_, value_arg, true); break; case kString: case kType: jval_.i = ReadUnsignedInt(ptr_, value_arg, false); break; case kField: case kMethod: case kEnum: case kArray: case kAnnotation: UNIMPLEMENTED(FATAL) << ": type " << type_; break; case kNull: jval_.l = NULL; width = 0; break; default: LOG(FATAL) << "Unreached"; } ptr_ += width; } void EncodedStaticFieldValueIterator::ReadValueToField(mirror::ArtField* field) const { switch (type_) { case kBoolean: field->SetBoolean(field->GetDeclaringClass(), jval_.z); break; case kByte: field->SetByte(field->GetDeclaringClass(), jval_.b); break; case kShort: field->SetShort(field->GetDeclaringClass(), jval_.s); break; case kChar: field->SetChar(field->GetDeclaringClass(), jval_.c); break; case kInt: field->SetInt(field->GetDeclaringClass(), jval_.i); break; case kLong: field->SetLong(field->GetDeclaringClass(), jval_.j); break; case kFloat: field->SetFloat(field->GetDeclaringClass(), jval_.f); break; case kDouble: field->SetDouble(field->GetDeclaringClass(), jval_.d); break; case kNull: field->SetObject(field->GetDeclaringClass(), NULL); break; case kString: { mirror::String* resolved = linker_->ResolveString(dex_file_, jval_.i, dex_cache_); field->SetObject(field->GetDeclaringClass(), resolved); break; } case kType: { mirror::Class* resolved = linker_->ResolveType(dex_file_, jval_.i, dex_cache_, class_loader_); field->SetObject(field->GetDeclaringClass(), resolved); break; } default: UNIMPLEMENTED(FATAL) << ": type " << type_; } } CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) { handler_.address_ = -1; int32_t offset = -1; // Short-circuit the overwhelmingly common cases. switch (code_item.tries_size_) { case 0: break; case 1: { const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0); uint32_t start = tries->start_addr_; if (address >= start) { uint32_t end = start + tries->insn_count_; if (address < end) { offset = tries->handler_off_; } } break; } default: offset = DexFile::FindCatchHandlerOffset(code_item, address); } Init(code_item, offset); } CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, const DexFile::TryItem& try_item) { handler_.address_ = -1; Init(code_item, try_item.handler_off_); } void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item, int32_t offset) { if (offset >= 0) { Init(DexFile::GetCatchHandlerData(code_item, offset)); } else { // Not found, initialize as empty current_data_ = NULL; remaining_count_ = -1; catch_all_ = false; DCHECK(!HasNext()); } } void CatchHandlerIterator::Init(const byte* handler_data) { current_data_ = handler_data; remaining_count_ = DecodeSignedLeb128(&current_data_); // If remaining_count_ is non-positive, then it is the negative of // the number of catch types, and the catches are followed by a // catch-all handler. if (remaining_count_ <= 0) { catch_all_ = true; remaining_count_ = -remaining_count_; } else { catch_all_ = false; } Next(); } void CatchHandlerIterator::Next() { if (remaining_count_ > 0) { handler_.type_idx_ = DecodeUnsignedLeb128(&current_data_); handler_.address_ = DecodeUnsignedLeb128(&current_data_); remaining_count_--; return; } if (catch_all_) { handler_.type_idx_ = DexFile::kDexNoIndex16; handler_.address_ = DecodeUnsignedLeb128(&current_data_); catch_all_ = false; return; } // no more handler remaining_count_ = -1; } } // namespace art
RyanTech/DexHunter
art/runtime/dex_file.cc
C++
apache-2.0
36,454
require 'shellwords' require 'optparse' require 'rake/task_manager' require 'rake/file_list' require 'rake/thread_pool' require 'rake/thread_history_display' require 'rake/trace_output' require 'rake/win32' module Rake CommandLineOptionError = Class.new(StandardError) ## # Rake main application object. When invoking +rake+ from the # command line, a Rake::Application object is created and run. class Application include TaskManager include TraceOutput # The name of the application (typically 'rake') attr_reader :name # The original directory where rake was invoked. attr_reader :original_dir # Name of the actual rakefile used. attr_reader :rakefile # Number of columns on the terminal attr_accessor :terminal_columns # List of the top level task names (task names from the command line). attr_reader :top_level_tasks DEFAULT_RAKEFILES = [ 'rakefile', 'Rakefile', 'rakefile.rb', 'Rakefile.rb' ].freeze # Initialize a Rake::Application object. def initialize super @name = 'rake' @rakefiles = DEFAULT_RAKEFILES.dup @rakefile = nil @pending_imports = [] @imported = [] @loaders = {} @default_loader = Rake::DefaultLoader.new @original_dir = Dir.pwd @top_level_tasks = [] add_loader('rb', DefaultLoader.new) add_loader('rf', DefaultLoader.new) add_loader('rake', DefaultLoader.new) @tty_output = STDOUT.tty? @terminal_columns = ENV['RAKE_COLUMNS'].to_i end # Run the Rake application. The run method performs the following # three steps: # # * Initialize the command line options (+init+). # * Define the tasks (+load_rakefile+). # * Run the top level tasks (+top_level+). # # If you wish to build a custom rake command, you should call # +init+ on your application. Then define any tasks. Finally, # call +top_level+ to run your top level tasks. def run standard_exception_handling do init load_rakefile top_level end end # Initialize the command line parameters and app name. def init(app_name='rake') standard_exception_handling do @name = app_name args = handle_options collect_command_line_tasks(args) end end # Find the rakefile and then load it and any pending imports. def load_rakefile standard_exception_handling do raw_load_rakefile end end # Run the top level tasks of a Rake application. def top_level run_with_threads do if options.show_tasks display_tasks_and_comments elsif options.show_prereqs display_prerequisites else top_level_tasks.each { |task_name| invoke_task(task_name) } end end end # Run the given block with the thread startup and shutdown. def run_with_threads thread_pool.gather_history if options.job_stats == :history yield thread_pool.join if options.job_stats stats = thread_pool.statistics puts "Maximum active threads: #{stats[:max_active_threads]} + main" puts "Total threads in play: #{stats[:total_threads_in_play]} + main" end ThreadHistoryDisplay.new(thread_pool.history).show if options.job_stats == :history end # Add a loader to handle imported files ending in the extension # +ext+. def add_loader(ext, loader) ext = ".#{ext}" unless ext =~ /^\./ @loaders[ext] = loader end # Application options from the command line def options @options ||= OpenStruct.new end # Return the thread pool used for multithreaded processing. def thread_pool # :nodoc: @thread_pool ||= ThreadPool.new(options.thread_pool_size || Rake.suggested_thread_count-1) end # internal ---------------------------------------------------------------- # Invokes a task with arguments that are extracted from +task_string+ def invoke_task(task_string) # :nodoc: name, args = parse_task_string(task_string) t = self[name] t.invoke(*args) end def parse_task_string(string) # :nodoc: /^([^\[]+)(?:\[(.*)\])$/ =~ string.to_s name = $1 remaining_args = $2 return string, [] unless name return name, [] if remaining_args.empty? args = [] begin /((?:[^\\,]|\\.)*?)\s*(?:,\s*(.*))?$/ =~ remaining_args remaining_args = $2 args << $1.gsub(/\\(.)/, '\1') end while remaining_args return name, args end # Provide standard exception handling for the given block. def standard_exception_handling # :nodoc: yield rescue SystemExit # Exit silently with current status raise rescue OptionParser::InvalidOption => ex $stderr.puts ex.message exit(false) rescue Exception => ex # Exit with error message display_error_message(ex) exit_because_of_exception(ex) end # Exit the program because of an unhandled exception. # (may be overridden by subclasses) def exit_because_of_exception(ex) # :nodoc: exit(false) end # Display the error message that caused the exception. def display_error_message(ex) # :nodoc: trace "#{name} aborted!" display_exception_details(ex) trace "Tasks: #{ex.chain}" if has_chain?(ex) trace "(See full trace by running task with --trace)" unless options.backtrace end def display_exception_details(ex) # :nodoc: seen = Thread.current[:rake_display_exception_details_seen] ||= [] return if seen.include? ex seen << ex display_exception_message_details(ex) display_exception_backtrace(ex) display_exception_details(ex.cause) if has_cause?(ex) end def has_cause?(ex) # :nodoc: ex.respond_to?(:cause) && ex.cause end def display_exception_message_details(ex) # :nodoc: if ex.instance_of?(RuntimeError) trace ex.message else trace "#{ex.class.name}: #{ex.message}" end end def display_exception_backtrace(ex) # :nodoc: if options.backtrace trace ex.backtrace.join("\n") else trace Backtrace.collapse(ex.backtrace).join("\n") end end # Warn about deprecated usage. # # Example: # Rake.application.deprecate("import", "Rake.import", caller.first) # def deprecate(old_usage, new_usage, call_site) # :nodoc: unless options.ignore_deprecate $stderr.puts "WARNING: '#{old_usage}' is deprecated. " + "Please use '#{new_usage}' instead.\n" + " at #{call_site}" end end # Does the exception have a task invocation chain? def has_chain?(exception) # :nodoc: exception.respond_to?(:chain) && exception.chain end private :has_chain? # True if one of the files in RAKEFILES is in the current directory. # If a match is found, it is copied into @rakefile. def have_rakefile # :nodoc: @rakefiles.each do |fn| if File.exist?(fn) others = FileList.glob(fn, File::FNM_CASEFOLD) return others.size == 1 ? others.first : fn elsif fn == '' return fn end end return nil end # True if we are outputting to TTY, false otherwise def tty_output? # :nodoc: @tty_output end # Override the detected TTY output state (mostly for testing) def tty_output=(tty_output_state) # :nodoc: @tty_output = tty_output_state end # We will truncate output if we are outputting to a TTY or if we've been # given an explicit column width to honor def truncate_output? # :nodoc: tty_output? || @terminal_columns.nonzero? end # Display the tasks and comments. def display_tasks_and_comments # :nodoc: displayable_tasks = tasks.select { |t| (options.show_all_tasks || t.comment) && t.name =~ options.show_task_pattern } case options.show_tasks when :tasks width = displayable_tasks.map { |t| t.name_with_args.length }.max || 10 if truncate_output? max_column = terminal_width - name.size - width - 7 else max_column = nil end displayable_tasks.each do |t| printf("#{name} %-#{width}s # %s\n", t.name_with_args, max_column ? truncate(t.comment, max_column) : t.comment) end when :describe displayable_tasks.each do |t| puts "#{name} #{t.name_with_args}" comment = t.full_comment || "" comment.split("\n").each do |line| puts " #{line}" end puts end when :lines displayable_tasks.each do |t| t.locations.each do |loc| printf "#{name} %-30s %s\n", t.name_with_args, loc end end else fail "Unknown show task mode: '#{options.show_tasks}'" end end def terminal_width # :nodoc: if @terminal_columns.nonzero? result = @terminal_columns else result = unix? ? dynamic_width : 80 end (result < 10) ? 80 : result rescue 80 end # Calculate the dynamic width of the def dynamic_width # :nodoc: @dynamic_width ||= (dynamic_width_stty.nonzero? || dynamic_width_tput) end def dynamic_width_stty # :nodoc: %x{stty size 2>/dev/null}.split[1].to_i end def dynamic_width_tput # :nodoc: %x{tput cols 2>/dev/null}.to_i end def unix? # :nodoc: RbConfig::CONFIG['host_os'] =~ /(aix|darwin|linux|(net|free|open)bsd|cygwin|solaris|irix|hpux)/i end def windows? # :nodoc: Win32.windows? end def truncate(string, width) # :nodoc: if string.nil? "" elsif string.length <= width string else (string[0, width - 3] || "") + "..." end end # Display the tasks and prerequisites def display_prerequisites # :nodoc: tasks.each do |t| puts "#{name} #{t.name}" t.prerequisites.each { |pre| puts " #{pre}" } end end def trace(*strings) # :nodoc: options.trace_output ||= $stderr trace_on(options.trace_output, *strings) end def sort_options(options) # :nodoc: options.sort_by { |opt| opt.select { |o| o =~ /^-/ }.map { |o| o.downcase }.sort.reverse } end private :sort_options # A list of all the standard options used in rake, suitable for # passing to OptionParser. def standard_rake_options # :nodoc: sort_options( [ ['--all', '-A', "Show all tasks, even uncommented ones (in combination with -T or -D)", lambda { |value| options.show_all_tasks = value } ], ['--backtrace=[OUT]', "Enable full backtrace. OUT can be stderr (default) or stdout.", lambda { |value| options.backtrace = true select_trace_output(options, 'backtrace', value) } ], ['--build-all', '-B', "Build all prerequisites, including those which are up-to-date.", lambda { |value| options.build_all = true } ], ['--comments', "Show commented tasks only", lambda { |value| options.show_all_tasks = !value } ], ['--describe', '-D [PATTERN]', "Describe the tasks (matching optional PATTERN), then exit.", lambda { |value| select_tasks_to_show(options, :describe, value) } ], ['--dry-run', '-n', "Do a dry run without executing actions.", lambda { |value| Rake.verbose(true) Rake.nowrite(true) options.dryrun = true options.trace = true } ], ['--execute', '-e CODE', "Execute some Ruby code and exit.", lambda { |value| eval(value) exit } ], ['--execute-print', '-p CODE', "Execute some Ruby code, print the result, then exit.", lambda { |value| puts eval(value) exit } ], ['--execute-continue', '-E CODE', "Execute some Ruby code, " + "then continue with normal task processing.", lambda { |value| eval(value) } ], ['--jobs', '-j [NUMBER]', "Specifies the maximum number of tasks to execute in parallel. " + "(default is number of CPU cores + 4)", lambda { |value| if value.nil? || value == '' value = FIXNUM_MAX elsif value =~ /^\d+$/ value = value.to_i else value = Rake.suggested_thread_count end value = 1 if value < 1 options.thread_pool_size = value - 1 } ], ['--job-stats [LEVEL]', "Display job statistics. " + "LEVEL=history displays a complete job list", lambda { |value| if value =~ /^history/i options.job_stats = :history else options.job_stats = true end } ], ['--libdir', '-I LIBDIR', "Include LIBDIR in the search path for required modules.", lambda { |value| $:.push(value) } ], ['--multitask', '-m', "Treat all tasks as multitasks.", lambda { |value| options.always_multitask = true } ], ['--no-search', '--nosearch', '-N', "Do not search parent directories for the Rakefile.", lambda { |value| options.nosearch = true } ], ['--prereqs', '-P', "Display the tasks and dependencies, then exit.", lambda { |value| options.show_prereqs = true } ], ['--quiet', '-q', "Do not log messages to standard output.", lambda { |value| Rake.verbose(false) } ], ['--rakefile', '-f [FILENAME]', "Use FILENAME as the rakefile to search for.", lambda { |value| value ||= '' @rakefiles.clear @rakefiles << value } ], ['--rakelibdir', '--rakelib', '-R RAKELIBDIR', "Auto-import any .rake files in RAKELIBDIR. " + "(default is 'rakelib')", lambda { |value| options.rakelib = value.split(File::PATH_SEPARATOR) } ], ['--require', '-r MODULE', "Require MODULE before executing rakefile.", lambda { |value| begin require value rescue LoadError => ex begin rake_require value rescue LoadError raise ex end end } ], ['--rules', "Trace the rules resolution.", lambda { |value| options.trace_rules = true } ], ['--silent', '-s', "Like --quiet, but also suppresses the " + "'in directory' announcement.", lambda { |value| Rake.verbose(false) options.silent = true } ], ['--suppress-backtrace PATTERN', "Suppress backtrace lines matching regexp PATTERN. " + "Ignored if --trace is on.", lambda { |value| options.suppress_backtrace_pattern = Regexp.new(value) } ], ['--system', '-g', "Using system wide (global) rakefiles " + "(usually '~/.rake/*.rake').", lambda { |value| options.load_system = true } ], ['--no-system', '--nosystem', '-G', "Use standard project Rakefile search paths, " + "ignore system wide rakefiles.", lambda { |value| options.ignore_system = true } ], ['--tasks', '-T [PATTERN]', "Display the tasks (matching optional PATTERN) " + "with descriptions, then exit.", lambda { |value| select_tasks_to_show(options, :tasks, value) } ], ['--trace=[OUT]', '-t', "Turn on invoke/execute tracing, enable full backtrace. " + "OUT can be stderr (default) or stdout.", lambda { |value| options.trace = true options.backtrace = true select_trace_output(options, 'trace', value) Rake.verbose(true) } ], ['--verbose', '-v', "Log message to standard output.", lambda { |value| Rake.verbose(true) } ], ['--version', '-V', "Display the program version.", lambda { |value| puts "rake, version #{RAKEVERSION}" exit } ], ['--where', '-W [PATTERN]', "Describe the tasks (matching optional PATTERN), then exit.", lambda { |value| select_tasks_to_show(options, :lines, value) options.show_all_tasks = true } ], ['--no-deprecation-warnings', '-X', "Disable the deprecation warnings.", lambda { |value| options.ignore_deprecate = true } ], ]) end def select_tasks_to_show(options, show_tasks, value) # :nodoc: options.show_tasks = show_tasks options.show_task_pattern = Regexp.new(value || '') Rake::TaskManager.record_task_metadata = true end private :select_tasks_to_show def select_trace_output(options, trace_option, value) # :nodoc: value = value.strip unless value.nil? case value when 'stdout' options.trace_output = $stdout when 'stderr', nil options.trace_output = $stderr else fail CommandLineOptionError, "Unrecognized --#{trace_option} option '#{value}'" end end private :select_trace_output # Read and handle the command line options. Returns the command line # arguments that we didn't understand, which should (in theory) be just # task names and env vars. def handle_options # :nodoc: options.rakelib = ['rakelib'] options.trace_output = $stderr OptionParser.new do |opts| opts.banner = "#{Rake.application.name} [-f rakefile] {options} targets..." opts.separator "" opts.separator "Options are ..." opts.on_tail("-h", "--help", "-H", "Display this help message.") do puts opts exit end standard_rake_options.each { |args| opts.on(*args) } opts.environment('RAKEOPT') end.parse(ARGV) end # Similar to the regular Ruby +require+ command, but will check # for *.rake files in addition to *.rb files. def rake_require(file_name, paths=$LOAD_PATH, loaded=$") # :nodoc: fn = file_name + ".rake" return false if loaded.include?(fn) paths.each do |path| full_path = File.join(path, fn) if File.exist?(full_path) Rake.load_rakefile(full_path) loaded << fn return true end end fail LoadError, "Can't find #{file_name}" end def find_rakefile_location # :nodoc: here = Dir.pwd until (fn = have_rakefile) Dir.chdir("..") return nil if Dir.pwd == here || options.nosearch here = Dir.pwd end [fn, here] ensure Dir.chdir(Rake.original_dir) end def print_rakefile_directory(location) # :nodoc: $stderr.puts "(in #{Dir.pwd})" unless options.silent or original_dir == location end def raw_load_rakefile # :nodoc: rakefile, location = find_rakefile_location if (! options.ignore_system) && (options.load_system || rakefile.nil?) && system_dir && File.directory?(system_dir) print_rakefile_directory(location) glob("#{system_dir}/*.rake") do |name| add_import name end else fail "No Rakefile found (looking for: #{@rakefiles.join(', ')})" if rakefile.nil? @rakefile = rakefile Dir.chdir(location) print_rakefile_directory(location) Rake.load_rakefile(File.expand_path(@rakefile)) if @rakefile && @rakefile != '' options.rakelib.each do |rlib| glob("#{rlib}/*.rake") do |name| add_import name end end end load_imports end def glob(path, &block) # :nodoc: FileList.glob(path.gsub("\\", '/')).each(&block) end private :glob # The directory path containing the system wide rakefiles. def system_dir # :nodoc: @system_dir ||= begin if ENV['RAKE_SYSTEM'] ENV['RAKE_SYSTEM'] else standard_system_dir end end end # The standard directory containing system wide rake files. if Win32.windows? def standard_system_dir #:nodoc: Win32.win32_system_dir end else def standard_system_dir #:nodoc: File.join(File.expand_path('~'), '.rake') end end private :standard_system_dir # Collect the list of tasks on the command line. If no tasks are # given, return a list containing only the default task. # Environmental assignments are processed at this time as well. # # `args` is the list of arguments to peruse to get the list of tasks. # It should be the command line that was given to rake, less any # recognised command-line options, which OptionParser.parse will # have taken care of already. def collect_command_line_tasks(args) # :nodoc: @top_level_tasks = [] args.each do |arg| if arg =~ /^(\w+)=(.*)$/m ENV[$1] = $2 else @top_level_tasks << arg unless arg =~ /^-/ end end @top_level_tasks.push(default_task_name) if @top_level_tasks.empty? end # Default task name ("default"). # (May be overridden by subclasses) def default_task_name # :nodoc: "default" end # Add a file to the list of files to be imported. def add_import(fn) # :nodoc: @pending_imports << fn end # Load the pending list of imported files. def load_imports # :nodoc: while fn = @pending_imports.shift next if @imported.member?(fn) fn_task = lookup(fn) and fn_task.invoke ext = File.extname(fn) loader = @loaders[ext] || @default_loader loader.load(fn) if fn_task = lookup(fn) and fn_task.needed? fn_task.reenable fn_task.invoke loader.load(fn) end @imported << fn end end def rakefile_location(backtrace=caller) # :nodoc: backtrace.map { |t| t[/([^:]+):/, 1] } re = /^#{@rakefile}$/ re = /#{re.source}/i if windows? backtrace.find { |str| str =~ re } || '' end private FIXNUM_MAX = (2**(0.size * 8 - 2) - 1) # :nodoc: end end
jingyu91/jingyu91.github.io
vendor/cache/ruby/2.3.0/gems/rake-10.5.0/lib/rake/application.rb
Ruby
mit
23,699
import {Date, DateWrapper} from 'angular2/src/facade/lang'; import {Map} from 'angular2/src/facade/collection'; export class MeasureValues { constructor(public runIndex: number, public timeStamp: Date, public values: {[key: string]: any}) {} toJson() { return { 'timeStamp': DateWrapper.toJson(this.timeStamp), 'runIndex': this.runIndex, 'values': this.values }; } }
erictsangx/angular
modules/benchpress/src/measure_values.ts
TypeScript
mit
415
// Copyright (C) 2011-2014 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // // { dg-do compile } #include <map> struct Key { Key() { } Key(const Key&) { } template<typename T> Key(const T&) { } bool operator<(const Key&) const; }; #if __cplusplus < 201103L // libstdc++/47628 void f() { typedef std::multimap<Key, int> MMap; MMap mm; mm.insert(MMap::value_type()); MMap::iterator i = mm.begin(); mm.erase(i); } #endif
iains/darwin-gcc-4-9
libstdc++-v3/testsuite/23_containers/multimap/modifiers/erase/47628.cc
C++
gpl-2.0
1,145
using System; using System.Text; namespace Server.Ethics.Evil { public sealed class UnholySense : Power { public UnholySense() { this.m_Definition = new PowerDefinition( 0, "Unholy Sense", "Drewrok Velgo", ""); } public override void BeginInvoke(Player from) { Ethic opposition = Ethic.Hero; int enemyCount = 0; int maxRange = 18 + from.Power; Player primary = null; foreach (Player pl in opposition.Players) { Mobile mob = pl.Mobile; if (mob == null || mob.Map != from.Mobile.Map || !mob.Alive) continue; if (!mob.InRange(from.Mobile, Math.Max(18, maxRange - pl.Power))) continue; if (primary == null || pl.Power > primary.Power) primary = pl; ++enemyCount; } StringBuilder sb = new StringBuilder(); sb.Append("You sense "); sb.Append(enemyCount == 0 ? "no" : enemyCount.ToString()); sb.Append(enemyCount == 1 ? " enemy" : " enemies"); if (primary != null) { sb.Append(", and a strong presense"); switch ( from.Mobile.GetDirectionTo(primary.Mobile) ) { case Direction.West: sb.Append(" to the west."); break; case Direction.East: sb.Append(" to the east."); break; case Direction.North: sb.Append(" to the north."); break; case Direction.South: sb.Append(" to the south."); break; case Direction.Up: sb.Append(" to the north-west."); break; case Direction.Down: sb.Append(" to the south-east."); break; case Direction.Left: sb.Append(" to the south-west."); break; case Direction.Right: sb.Append(" to the north-east."); break; } } else { sb.Append('.'); } from.Mobile.LocalOverheadMessage(Server.Network.MessageType.Regular, 0x59, false, sb.ToString()); this.FinishInvoke(from); } } }
LeonG-ZA/JustUO-KR
Scripts/Services/Ethics/Evil/Powers/UnholySense.cs
C#
gpl-3.0
2,730
/** * Appcelerator Titanium Mobile * Copyright (c) 2010 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ package org.appcelerator.kroll; public class KrollPropertyChange { protected String name; protected Object oldValue, newValue; public KrollPropertyChange(String name, Object oldValue, Object newValue) { this.name = name; this.oldValue = oldValue; this.newValue = newValue; } public void fireEvent(KrollProxy proxy, KrollProxyListener listener) { if (listener != null) { listener.propertyChanged(name, oldValue, newValue, proxy); } } public String getName() { return name; } public Object getOldValue() { return oldValue; } public Object getNewValue() { return newValue; } }
arnaudsj/titanium_mobile
android/titanium/src/org/appcelerator/kroll/KrollPropertyChange.java
Java
apache-2.0
846
/* Copyright (c) 2011 by The Authors. * Published under the LGPL 2.1 license. * See /license-notice.txt for the full text of the license notice. * See /license.txt for the full text of the license. */ /** * Supplies a set of utility methods for building Geometry objects from lists * of Coordinates. * * Note that the factory constructor methods do <b>not</b> change the input * coordinates in any way. * * In particular, they are not rounded to the supplied <tt>PrecisionModel</tt>. * It is assumed that input Coordinates meet the given precision. */ /** * @requires jsts/geom/PrecisionModel.js */ /** * Constructs a GeometryFactory that generates Geometries having a floating * PrecisionModel and a spatial-reference ID of 0. * * @constructor */ jsts.geom.GeometryFactory = function(precisionModel) { this.precisionModel = precisionModel || new jsts.geom.PrecisionModel(); }; jsts.geom.GeometryFactory.prototype.precisionModel = null; jsts.geom.GeometryFactory.prototype.getPrecisionModel = function() { return this.precisionModel; }; /** * Creates a Point using the given Coordinate; a null Coordinate will create an * empty Geometry. * * @param {Coordinate} * coordinate Coordinate to base this Point on. * @return {Point} A new Point. */ jsts.geom.GeometryFactory.prototype.createPoint = function(coordinate) { var point = new jsts.geom.Point(coordinate, this); return point; }; /** * Creates a LineString using the given Coordinates; a null or empty array will * create an empty LineString. Consecutive points must not be equal. * * @param {Coordinate[]} * coordinates an array without null elements, or an empty array, or * null. * @return {LineString} A new LineString. */ jsts.geom.GeometryFactory.prototype.createLineString = function(coordinates) { var lineString = new jsts.geom.LineString(coordinates, this); return lineString; }; /** * Creates a LinearRing using the given Coordinates; a null or empty array will * create an empty LinearRing. The points must form a closed and simple * linestring. Consecutive points must not be equal. * * @param {Coordinate[]} * coordinates an array without null elements, or an empty array, or * null. * @return {LinearRing} A new LinearRing. */ jsts.geom.GeometryFactory.prototype.createLinearRing = function(coordinates) { var linearRing = new jsts.geom.LinearRing(coordinates, this); return linearRing; }; /** * Constructs a <code>Polygon</code> with the given exterior boundary and * interior boundaries. * * @param {LinearRing} * shell the outer boundary of the new <code>Polygon</code>, or * <code>null</code> or an empty <code>LinearRing</code> if the * empty geometry is to be created. * @param {LinearRing[]} * holes the inner boundaries of the new <code>Polygon</code>, or * <code>null</code> or empty <code>LinearRing</code> s if the * empty geometry is to be created. * @return {Polygon} A new Polygon. */ jsts.geom.GeometryFactory.prototype.createPolygon = function(shell, holes) { var polygon = new jsts.geom.Polygon(shell, holes, this); return polygon; }; jsts.geom.GeometryFactory.prototype.createMultiPoint = function(points) { if (points && points[0] instanceof jsts.geom.Coordinate) { var converted = []; var i; for (i = 0; i < points.length; i++) { converted.push(this.createPoint(points[i])); } points = converted; } return new jsts.geom.MultiPoint(points, this); }; jsts.geom.GeometryFactory.prototype.createMultiLineString = function( lineStrings) { return new jsts.geom.MultiLineString(lineStrings, this); }; jsts.geom.GeometryFactory.prototype.createMultiPolygon = function(polygons) { return new jsts.geom.MultiPolygon(polygons, this); }; /** * Build an appropriate <code>Geometry</code>, <code>MultiGeometry</code>, * or <code>GeometryCollection</code> to contain the <code>Geometry</code>s * in it. For example:<br> * * <ul> * <li> If <code>geomList</code> contains a single <code>Polygon</code>, * the <code>Polygon</code> is returned. * <li> If <code>geomList</code> contains several <code>Polygon</code>s, a * <code>MultiPolygon</code> is returned. * <li> If <code>geomList</code> contains some <code>Polygon</code>s and * some <code>LineString</code>s, a <code>GeometryCollection</code> is * returned. * <li> If <code>geomList</code> is empty, an empty * <code>GeometryCollection</code> is returned * </ul> * * Note that this method does not "flatten" Geometries in the input, and hence * if any MultiGeometries are contained in the input a GeometryCollection * containing them will be returned. * * @param geomList * the <code>Geometry</code>s to combine. * @return {Geometry} a <code>Geometry</code> of the "smallest", "most * type-specific" class that can contain the elements of * <code>geomList</code> . */ jsts.geom.GeometryFactory.prototype.buildGeometry = function(geomList) { /** * Determine some facts about the geometries in the list */ var geomClass = null; var isHeterogeneous = false; var hasGeometryCollection = false; for (var i = geomList.iterator(); i.hasNext();) { var geom = i.next(); var partClass = geom.CLASS_NAME; if (geomClass === null) { geomClass = partClass; } if (!(partClass === geomClass)) { isHeterogeneous = true; } if (geom.isGeometryCollectionBase()) hasGeometryCollection = true; } /** * Now construct an appropriate geometry to return */ // for the empty geometry, return an empty GeometryCollection if (geomClass === null) { return this.createGeometryCollection(null); } if (isHeterogeneous || hasGeometryCollection) { return this.createGeometryCollection(geomList.toArray()); } // at this point we know the collection is hetereogenous. // Determine the type of the result from the first Geometry in the list // this should always return a geometry, since otherwise an empty collection // would have already been returned var geom0 = geomList.get(0); var isCollection = geomList.size() > 1; if (isCollection) { if (geom0 instanceof jsts.geom.Polygon) { return this.createMultiPolygon(geomList.toArray()); } else if (geom0 instanceof jsts.geom.LineString) { return this.createMultiLineString(geomList.toArray()); } else if (geom0 instanceof jsts.geom.Point) { return this.createMultiPoint(geomList.toArray()); } jsts.util.Assert.shouldNeverReachHere('Unhandled class: ' + geom0); } return geom0; }; jsts.geom.GeometryFactory.prototype.createGeometryCollection = function( geometries) { return new jsts.geom.GeometryCollection(geometries, this); }; /** * Creates a {@link Geometry} with the same extent as the given envelope. The * Geometry returned is guaranteed to be valid. To provide this behaviour, the * following cases occur: * <p> * If the <code>Envelope</code> is: * <ul> * <li>null : returns an empty {@link Point} * <li>a point : returns a non-empty {@link Point} * <li>a line : returns a two-point {@link LineString} * <li>a rectangle : returns a {@link Polygon}> whose points are (minx, miny), * (minx, maxy), (maxx, maxy), (maxx, miny), (minx, miny). * </ul> * * @param {jsts.geom.Envelope} * envelope the <code>Envelope</code> to convert. * @return {jsts.geom.Geometry} an empty <code>Point</code> (for null * <code>Envelope</code>s), a <code>Point</code> (when min x = max * x and min y = max y) or a <code>Polygon</code> (in all other cases). */ jsts.geom.GeometryFactory.prototype.toGeometry = function(envelope) { // null envelope - return empty point geometry if (envelope.isNull()) { return this.createPoint(null); } // point? if (envelope.getMinX() === envelope.getMaxX() && envelope.getMinY() === envelope.getMaxY()) { return this.createPoint(new jsts.geom.Coordinate(envelope.getMinX(), envelope.getMinY())); } // vertical or horizontal line? if (envelope.getMinX() === envelope.getMaxX() || envelope.getMinY() === envelope.getMaxY()) { return this.createLineString([ new jsts.geom.Coordinate(envelope.getMinX(), envelope.getMinY()), new jsts.geom.Coordinate(envelope.getMaxX(), envelope.getMaxY())]); } // create a CW ring for the polygon return this.createPolygon(this.createLinearRing([ new jsts.geom.Coordinate(envelope.getMinX(), envelope.getMinY()), new jsts.geom.Coordinate(envelope.getMinX(), envelope.getMaxY()), new jsts.geom.Coordinate(envelope.getMaxX(), envelope.getMaxY()), new jsts.geom.Coordinate(envelope.getMaxX(), envelope.getMinY()), new jsts.geom.Coordinate(envelope.getMinX(), envelope.getMinY())]), null); };
mileswwatkins/ABiteBetweenUs
utilities/scripts/jsts/src/jsts/geom/GeometryFactory.js
JavaScript
apache-2.0
8,870
class Ipcalc < Formula homepage "http://jodies.de/ipcalc" url "http://jodies.de/ipcalc-archive/ipcalc-0.41.tar.gz" sha256 "dda9c571ce3369e5b6b06e92790434b54bec1f2b03f1c9df054c0988aa4e2e8a" def install bin.install "ipcalc" end test do system "#{bin}/ipcalc", "--nobinary", "192.168.0.1/24" end end
bendemaree/homebrew
Library/Formula/ipcalc.rb
Ruby
bsd-2-clause
321
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("cs_test")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("MSIT")] [assembly: AssemblyProduct("cs_test")] [assembly: AssemblyCopyright("Copyright © MSIT 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("74451adb-817c-45fa-af74-71fd22936907")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
chriszeng8/vowpal_wabbit
cs_test/Properties/AssemblyInfo.cs
C#
bsd-3-clause
1,434
/** * angular-strap * @version v2.1.6 - 2015-01-11 * @link http://mgcrea.github.io/angular-strap * @author Olivier Louvignes (olivier@mg-crea.com) * @license MIT License, http://www.opensource.org/licenses/MIT */ "use strict";angular.module("mgcrea.ngStrap.helpers.dateFormatter",[]).service("$dateFormatter",["$locale","dateFilter",function(t,e){function r(t){return/(h+)([:\.])?(m+)[ ]?(a?)/i.exec(t).slice(1)}this.getDefaultLocale=function(){return t.id},this.getDatetimeFormat=function(e){return t.DATETIME_FORMATS[e]||e},this.weekdaysShort=function(){return t.DATETIME_FORMATS.SHORTDAY},this.hoursFormat=function(t){return r(t)[0]},this.minutesFormat=function(t){return r(t)[2]},this.timeSeparator=function(t){return r(t)[1]},this.showAM=function(t){return!!r(t)[3]},this.formatDate=function(t,r){return e(t,r)}}]); //# sourceMappingURL=date-formatter.min.js.map
spawashe/poc-mango-cad
www/lib/bower_components/angular-strap/dist/modules/date-formatter.min.js
JavaScript
mit
873
/** * @author Richard Davey <rich@photonstorm.com> * @copyright 2016 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * An Image is a light-weight object you can use to display anything that doesn't need physics or animation. * It can still rotate, scale, crop and receive input events. This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics. * * @class Phaser.Image * @extends PIXI.Sprite * @extends Phaser.Component.Core * @extends Phaser.Component.Angle * @extends Phaser.Component.Animation * @extends Phaser.Component.AutoCull * @extends Phaser.Component.Bounds * @extends Phaser.Component.BringToTop * @extends Phaser.Component.Crop * @extends Phaser.Component.Destroy * @extends Phaser.Component.FixedToCamera * @extends Phaser.Component.InputEnabled * @extends Phaser.Component.LifeSpan * @extends Phaser.Component.LoadTexture * @extends Phaser.Component.Overlap * @extends Phaser.Component.Reset * @extends Phaser.Component.ScaleMinMax * @extends Phaser.Component.Smoothed * @constructor * @param {Phaser.Game} game - A reference to the currently running game. * @param {number} [x=0] - The x coordinate of the Image. The coordinate is relative to any parent container this Image may be in. * @param {number} [y=0] - The y coordinate of the Image. The coordinate is relative to any parent container this Image may be in. * @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} [key] - The texture used by the Image during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture, BitmapData or PIXI.Texture. * @param {string|number} [frame] - If this Image is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. */ Phaser.Image = function (game, x, y, key, frame) { x = x || 0; y = y || 0; key = key || null; frame = frame || null; /** * @property {number} type - The const type of this object. * @readonly */ this.type = Phaser.IMAGE; PIXI.Sprite.call(this, Phaser.Cache.DEFAULT); Phaser.Component.Core.init.call(this, game, x, y, key, frame); }; Phaser.Image.prototype = Object.create(PIXI.Sprite.prototype); Phaser.Image.prototype.constructor = Phaser.Image; Phaser.Component.Core.install.call(Phaser.Image.prototype, [ 'Angle', 'Animation', 'AutoCull', 'Bounds', 'BringToTop', 'Crop', 'Destroy', 'FixedToCamera', 'InputEnabled', 'LifeSpan', 'LoadTexture', 'Overlap', 'Reset', 'ScaleMinMax', 'Smoothed' ]); Phaser.Image.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; Phaser.Image.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; /** * Automatically called by World.preUpdate. * * @method Phaser.Image#preUpdate * @memberof Phaser.Image */ Phaser.Image.prototype.preUpdate = function() { if (!this.preUpdateInWorld()) { return false; } return this.preUpdateCore(); };
stoneman1/phaser
v2/src/gameobjects/Image.js
JavaScript
mit
3,099
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Generic exporter to take a stdClass and prepare it for return by webservice. * * @package core * @copyright 2015 Damyon Wiese * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ namespace core\external; defined('MOODLE_INTERNAL') || die(); require_once($CFG->libdir . '/externallib.php'); use stdClass; use renderer_base; use context; use context_system; use coding_exception; use external_single_structure; use external_multiple_structure; use external_value; use external_format_value; /** * Generic exporter to take a stdClass and prepare it for return by webservice, or as the context for a template. * * templatable classes implementing export_for_template, should always use a standard exporter if it exists. * External functions should always use a standard exporter if it exists. * * @copyright 2015 Damyon Wiese * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ abstract class exporter { /** @var array $related List of related objects used to avoid DB queries. */ protected $related = array(); /** @var stdClass|array The data of this exporter. */ protected $data = null; /** * Constructor - saves the persistent object, and the related objects. * * @param mixed $data - Either an stdClass or an array of values. * @param array $related - An optional list of pre-loaded objects related to this object. */ public function __construct($data, $related = array()) { $this->data = $data; // Cache the valid related objects. foreach (static::define_related() as $key => $classname) { $isarray = false; $nullallowed = false; // Allow ? to mean null is allowed. if (substr($classname, -1) === '?') { $classname = substr($classname, 0, -1); $nullallowed = true; } // Allow [] to mean an array of values. if (substr($classname, -2) === '[]') { $classname = substr($classname, 0, -2); $isarray = true; } $missingdataerr = 'Exporter class is missing required related data: (' . get_called_class() . ') '; $scalartypes = ['string', 'int', 'bool', 'float']; $scalarcheck = 'is_' . $classname; if ($nullallowed && (!array_key_exists($key, $related) || $related[$key] === null)) { $this->related[$key] = null; } else if ($isarray) { if (array_key_exists($key, $related) && is_array($related[$key])) { foreach ($related[$key] as $index => $value) { if (!$value instanceof $classname && !$scalarcheck($value)) { throw new coding_exception($missingdataerr . $key . ' => ' . $classname . '[]'); } } $this->related[$key] = $related[$key]; } else { throw new coding_exception($missingdataerr . $key . ' => ' . $classname . '[]'); } } else { if (array_key_exists($key, $related) && ((in_array($classname, $scalartypes) && $scalarcheck($related[$key])) || ($related[$key] instanceof $classname))) { $this->related[$key] = $related[$key]; } else { throw new coding_exception($missingdataerr . $key . ' => ' . $classname); } } } } /** * Function to export the renderer data in a format that is suitable for a * mustache template. This means raw records are generated as in to_record, * but all strings are correctly passed through external_format_text (or external_format_string). * * @param renderer_base $output Used to do a final render of any components that need to be rendered for export. * @return stdClass */ final public function export(renderer_base $output) { $data = new stdClass(); $properties = self::read_properties_definition(); $values = (array) $this->data; $othervalues = $this->get_other_values($output); if (array_intersect_key($values, $othervalues)) { // Attempt to replace a standard property. throw new coding_exception('Cannot override a standard property value.'); } $values += $othervalues; $record = (object) $values; foreach ($properties as $property => $definition) { if (isset($data->$property)) { // This happens when we have already defined the format properties. continue; } else if (!property_exists($record, $property) && array_key_exists('default', $definition)) { // We have a default value for this property. $record->$property = $definition['default']; } else if (!property_exists($record, $property) && !empty($definition['optional'])) { // Fine, this property can be omitted. continue; } else if (!property_exists($record, $property)) { // Whoops, we got something that wasn't defined. throw new coding_exception('Unexpected property ' . $property); } $data->$property = $record->$property; // If the field is PARAM_RAW and has a format field. if ($propertyformat = self::get_format_field($properties, $property)) { if (!property_exists($record, $propertyformat)) { // Whoops, we got something that wasn't defined. throw new coding_exception('Unexpected property ' . $propertyformat); } $formatparams = $this->get_format_parameters($property); $format = $record->$propertyformat; list($text, $format) = external_format_text($data->$property, $format, $formatparams['context'], $formatparams['component'], $formatparams['filearea'], $formatparams['itemid'], $formatparams['options']); $data->$property = $text; $data->$propertyformat = $format; } else if ($definition['type'] === PARAM_TEXT) { $formatparams = $this->get_format_parameters($property); if (!empty($definition['multiple'])) { foreach ($data->$property as $key => $value) { $data->{$property}[$key] = external_format_string($value, $formatparams['context'], $formatparams['striplinks'], $formatparams['options']); } } else { $data->$property = external_format_string($data->$property, $formatparams['context'], $formatparams['striplinks'], $formatparams['options']); } } } return $data; } /** * Get the format parameters. * * This method returns the parameters to use with the functions external_format_text(), and * external_format_string(). To override the default parameters, you can define a protected method * called 'get_format_parameters_for_<propertyName>'. For example, 'get_format_parameters_for_description', * if your property is 'description'. * * Your method must return an array containing any of the following keys: * - context: The context to use. Defaults to $this->related['context'] if defined, else throws an exception. * - component: The component to use with external_format_text(). Defaults to null. * - filearea: The filearea to use with external_format_text(). Defaults to null. * - itemid: The itemid to use with external_format_text(). Defaults to null. * - options: An array of options accepted by external_format_text() or external_format_string(). Defaults to []. * - striplinks: Whether to strip the links with external_format_string(). Defaults to true. * * @param string $property The property to get the parameters for. * @return array */ final protected function get_format_parameters($property) { $parameters = [ 'component' => null, 'filearea' => null, 'itemid' => null, 'options' => [], 'striplinks' => true, ]; $candidate = 'get_format_parameters_for_' . $property; if (method_exists($this, $candidate)) { $parameters = array_merge($parameters, $this->{$candidate}()); } if (!isset($parameters['context'])) { if (!isset($this->related['context']) || !($this->related['context'] instanceof context)) { throw new coding_exception("Unknown context to use for formatting the property '$property' in the " . "exporter '" . get_class($this) . "'. You either need to add 'context' to your related objects, " . "or create the method '$candidate' and return the context from there."); } $parameters['context'] = $this->related['context']; } else if (!($parameters['context'] instanceof context)) { throw new coding_exception("The context given to format the property '$property' in the exporter '" . get_class($this) . "' is invalid."); } return $parameters; } /** * Get the additional values to inject while exporting. * * These are additional generated values that are not passed in through $data * to the exporter. For a persistent exporter - these are generated values that * do not exist in the persistent class. For your convenience the format_text or * format_string functions do not need to be applied to PARAM_TEXT fields, * it will be done automatically during export. * * These values are only used when returning data via {@link self::export()}, * they are not used when generating any of the different external structures. * * Note: These must be defined in {@link self::define_other_properties()}. * * @param renderer_base $output The renderer. * @return array Keys are the property names, values are their values. */ protected function get_other_values(renderer_base $output) { return array(); } /** * Get the read properties definition of this exporter. Read properties combines the * default properties from the model (persistent or stdClass) with the properties defined * by {@link self::define_other_properties()}. * * @return array Keys are the property names, and value their definition. */ final public static function read_properties_definition() { $properties = static::properties_definition(); $customprops = static::define_other_properties(); $customprops = static::format_properties($customprops); $properties += $customprops; return $properties; } /** * Recursively formats a given property definition with the default fields required. * * @param array $properties List of properties to format * @return array Formatted array */ final public static function format_properties($properties) { foreach ($properties as $property => $definition) { // Ensures that null is set to its default. if (!isset($definition['null'])) { $properties[$property]['null'] = NULL_NOT_ALLOWED; } if (!isset($definition['description'])) { $properties[$property]['description'] = $property; } // If an array is provided, it may be a nested array that is unformatted so rinse and repeat. if (is_array($definition['type'])) { $properties[$property]['type'] = static::format_properties($definition['type']); } } return $properties; } /** * Get the properties definition of this exporter used for create, and update structures. * The read structures are returned by: {@link self::read_properties_definition()}. * * @return array Keys are the property names, and value their definition. */ final public static function properties_definition() { $properties = static::define_properties(); foreach ($properties as $property => $definition) { // Ensures that null is set to its default. if (!isset($definition['null'])) { $properties[$property]['null'] = NULL_NOT_ALLOWED; } if (!isset($definition['description'])) { $properties[$property]['description'] = $property; } } return $properties; } /** * Return the list of additional properties used only for display. * * Additional properties are only ever used for the read structure, and during * export of the persistent data. * * The format of the array returned by this method has to match the structure * defined in {@link \core\persistent::define_properties()}. The display properties * can however do some more fancy things. They can define 'multiple' => true to wrap * values in an external_multiple_structure automatically - or they can define the * type as a nested array of more properties in order to generate a nested * external_single_structure. * * You can specify an array of values by including a 'multiple' => true array value. This * will result in a nested external_multiple_structure. * E.g. * * 'arrayofbools' => array( * 'type' => PARAM_BOOL, * 'multiple' => true * ), * * You can return a nested array in the type field, which will result in a nested external_single_structure. * E.g. * 'competency' => array( * 'type' => competency_exporter::read_properties_definition() * ), * * Other properties can be specifically marked as optional, in which case they do not need * to be included in the export in {@link self::get_other_values()}. This is useful when exporting * a substructure which cannot be set as null due to webservices protocol constraints. * E.g. * 'competency' => array( * 'type' => competency_exporter::read_properties_definition(), * 'optional' => true * ), * * @return array */ protected static function define_other_properties() { return array(); } /** * Return the list of properties. * * The format of the array returned by this method has to match the structure * defined in {@link \core\persistent::define_properties()}. Howewer you can * add a new attribute "description" to describe the parameter for documenting the API. * * Note that the type PARAM_TEXT should ONLY be used for strings which need to * go through filters (multilang, etc...) and do not have a FORMAT_* associated * to them. Typically strings passed through to format_string(). * * Other filtered strings which use a FORMAT_* constant (hear used with format_text) * must be defined as PARAM_RAW. * * @return array */ protected static function define_properties() { return array(); } /** * Returns a list of objects that are related to this persistent. * * Only objects listed here can be cached in this object. * * The class name can be suffixed: * - with [] to indicate an array of values. * - with ? to indicate that 'null' is allowed. * * @return array of 'propertyname' => array('type' => classname, 'required' => true) */ protected static function define_related() { return array(); } /** * Get the context structure. * * @return external_single_structure */ final protected static function get_context_structure() { return array( 'contextid' => new external_value(PARAM_INT, 'The context id', VALUE_OPTIONAL), 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level', VALUE_OPTIONAL), 'instanceid' => new external_value(PARAM_INT, 'The Instance id', VALUE_OPTIONAL), ); } /** * Get the format field name. * * @param array $definitions List of properties definitions. * @param string $property The name of the property that may have a format field. * @return bool|string False, or the name of the format property. */ final protected static function get_format_field($definitions, $property) { $formatproperty = $property . 'format'; if (($definitions[$property]['type'] == PARAM_RAW || $definitions[$property]['type'] == PARAM_CLEANHTML) && isset($definitions[$formatproperty]) && $definitions[$formatproperty]['type'] == PARAM_INT) { return $formatproperty; } return false; } /** * Get the format structure. * * @param string $property The name of the property on which the format applies. * @param array $definition The definition of the format property. * @param int $required Constant VALUE_*. * @return external_format_value */ final protected static function get_format_structure($property, $definition, $required = VALUE_REQUIRED) { if (array_key_exists('default', $definition)) { $required = VALUE_DEFAULT; } return new external_format_value($property, $required); } /** * Returns the create structure. * * @return external_single_structure */ final public static function get_create_structure() { $properties = self::properties_definition(); $returns = array(); foreach ($properties as $property => $definition) { if ($property == 'id') { // The can not be set on create. continue; } else if (isset($returns[$property]) && substr($property, -6) === 'format') { // We've already treated the format. continue; } $required = VALUE_REQUIRED; $default = null; // We cannot use isset here because we want to detect nulls. if (array_key_exists('default', $definition)) { $required = VALUE_DEFAULT; $default = $definition['default']; } // Magically treat the contextid fields. if ($property == 'contextid') { if (isset($properties['context'])) { throw new coding_exception('There cannot be a context and a contextid column'); } $returns += self::get_context_structure(); } else { $returns[$property] = new external_value($definition['type'], $definition['description'], $required, $default, $definition['null']); // Magically treat the format properties. if ($formatproperty = self::get_format_field($properties, $property)) { if (isset($returns[$formatproperty])) { throw new coding_exception('The format for \'' . $property . '\' is already defined.'); } $returns[$formatproperty] = self::get_format_structure($property, $properties[$formatproperty], VALUE_REQUIRED); } } } return new external_single_structure($returns); } /** * Returns the read structure. * * @return external_single_structure */ final public static function get_read_structure() { $properties = self::read_properties_definition(); return self::get_read_structure_from_properties($properties); } /** * Returns the read structure from a set of properties (recursive). * * @param array $properties The properties. * @param int $required Whether is required. * @param mixed $default The default value. * @return external_single_structure */ final protected static function get_read_structure_from_properties($properties, $required = VALUE_REQUIRED, $default = null) { $returns = array(); foreach ($properties as $property => $definition) { if (isset($returns[$property]) && substr($property, -6) === 'format') { // We've already treated the format. continue; } $thisvalue = null; $type = $definition['type']; $proprequired = VALUE_REQUIRED; $propdefault = null; if (array_key_exists('default', $definition)) { $propdefault = $definition['default']; } if (array_key_exists('optional', $definition)) { // Mark as optional. Note that this should only apply to "reading" "other" properties. $proprequired = VALUE_OPTIONAL; } if (is_array($type)) { // This is a nested array of more properties. $thisvalue = self::get_read_structure_from_properties($type, $proprequired, $propdefault); } else { if ($definition['type'] == PARAM_TEXT || $definition['type'] == PARAM_CLEANHTML) { // PARAM_TEXT always becomes PARAM_RAW because filters may be applied. $type = PARAM_RAW; } $thisvalue = new external_value($type, $definition['description'], $proprequired, $propdefault, $definition['null']); } if (!empty($definition['multiple'])) { $returns[$property] = new external_multiple_structure($thisvalue, $definition['description'], $proprequired, $propdefault); } else { $returns[$property] = $thisvalue; // Magically treat the format properties (not possible for arrays). if ($formatproperty = self::get_format_field($properties, $property)) { if (isset($returns[$formatproperty])) { throw new coding_exception('The format for \'' . $property . '\' is already defined.'); } $returns[$formatproperty] = self::get_format_structure($property, $properties[$formatproperty]); } } } return new external_single_structure($returns, '', $required, $default); } /** * Returns the update structure. * * This structure can never be included at the top level for an external function signature * because it contains optional parameters. * * @return external_single_structure */ final public static function get_update_structure() { $properties = self::properties_definition(); $returns = array(); foreach ($properties as $property => $definition) { if (isset($returns[$property]) && substr($property, -6) === 'format') { // We've already treated the format. continue; } $default = null; $required = VALUE_OPTIONAL; if ($property == 'id') { $required = VALUE_REQUIRED; } // Magically treat the contextid fields. if ($property == 'contextid') { if (isset($properties['context'])) { throw new coding_exception('There cannot be a context and a contextid column'); } $returns += self::get_context_structure(); } else { $returns[$property] = new external_value($definition['type'], $definition['description'], $required, $default, $definition['null']); // Magically treat the format properties. if ($formatproperty = self::get_format_field($properties, $property)) { if (isset($returns[$formatproperty])) { throw new coding_exception('The format for \'' . $property . '\' is already defined.'); } $returns[$formatproperty] = self::get_format_structure($property, $properties[$formatproperty], VALUE_OPTIONAL); } } } return new external_single_structure($returns); } }
marcusgreen/moodle
lib/classes/external/exporter.php
PHP
gpl-3.0
25,453
class Foo { public void foo() { int i; } }
asedunov/intellij-community
java/java-tests/testData/inspection/defUse/UnusedVariable.java
Java
apache-2.0
50
// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build windows package windows_test import ( "fmt" "internal/syscall/windows" "os" "os/exec" "syscall" "testing" "unsafe" ) func TestRunAtLowIntegrity(t *testing.T) { if os.Getenv("GO_WANT_HELPER_PROCESS") == "1" { wil, err := getProcessIntegrityLevel() if err != nil { fmt.Fprintf(os.Stderr, "error: %s\n", err.Error()) os.Exit(9) return } fmt.Printf("%s", wil) os.Exit(0) return } cmd := exec.Command(os.Args[0], "-test.run=TestRunAtLowIntegrity", "--") cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"} token, err := getIntegrityLevelToken(sidWilLow) if err != nil { t.Fatal(err) } defer token.Close() cmd.SysProcAttr = &syscall.SysProcAttr{ Token: token, } out, err := cmd.CombinedOutput() if err != nil { t.Fatal(err) } if string(out) != sidWilLow { t.Fatalf("Child process did not run as low integrity level: %s", string(out)) } } const ( sidWilLow = `S-1-16-4096` ) func getProcessIntegrityLevel() (string, error) { procToken, err := syscall.OpenCurrentProcessToken() if err != nil { return "", err } defer procToken.Close() p, err := tokenGetInfo(procToken, syscall.TokenIntegrityLevel, 64) if err != nil { return "", err } tml := (*windows.TOKEN_MANDATORY_LABEL)(p) sid := (*syscall.SID)(unsafe.Pointer(tml.Label.Sid)) return sid.String() } func tokenGetInfo(t syscall.Token, class uint32, initSize int) (unsafe.Pointer, error) { n := uint32(initSize) for { b := make([]byte, n) e := syscall.GetTokenInformation(t, class, &b[0], uint32(len(b)), &n) if e == nil { return unsafe.Pointer(&b[0]), nil } if e != syscall.ERROR_INSUFFICIENT_BUFFER { return nil, e } if n <= uint32(len(b)) { return nil, e } } } func getIntegrityLevelToken(wns string) (syscall.Token, error) { var procToken, token syscall.Token proc, err := syscall.GetCurrentProcess() if err != nil { return 0, err } defer syscall.CloseHandle(proc) err = syscall.OpenProcessToken(proc, syscall.TOKEN_DUPLICATE| syscall.TOKEN_ADJUST_DEFAULT| syscall.TOKEN_QUERY| syscall.TOKEN_ASSIGN_PRIMARY, &procToken) if err != nil { return 0, err } defer procToken.Close() sid, err := syscall.StringToSid(wns) if err != nil { return 0, err } tml := &windows.TOKEN_MANDATORY_LABEL{} tml.Label.Attributes = windows.SE_GROUP_INTEGRITY tml.Label.Sid = sid err = windows.DuplicateTokenEx(procToken, 0, nil, windows.SecurityImpersonation, windows.TokenPrimary, &token) if err != nil { return 0, err } err = windows.SetTokenInformation(token, syscall.TokenIntegrityLevel, uintptr(unsafe.Pointer(tml)), tml.Size()) if err != nil { token.Close() return 0, err } return token, nil }
Cofyc/go
src/internal/syscall/windows/exec_windows_test.go
GO
bsd-3-clause
2,860
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.metadata; import com.facebook.presto.spi.type.Type; import java.util.Map; import java.util.Objects; import static com.google.common.base.Preconditions.checkNotNull; public class SpecializedFunctionKey { private final ParametricFunction function; private final Map<String, Type> boundTypeParameters; private final int arity; public SpecializedFunctionKey(ParametricFunction function, Map<String, Type> boundTypeParameters, int arity) { this.function = checkNotNull(function, "function is null"); this.boundTypeParameters = checkNotNull(boundTypeParameters, "boundTypeParameters is null"); this.arity = arity; } public ParametricFunction getFunction() { return function; } public Map<String, Type> getBoundTypeParameters() { return boundTypeParameters; } public int getArity() { return arity; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SpecializedFunctionKey that = (SpecializedFunctionKey) o; return Objects.equals(arity, that.arity) && Objects.equals(boundTypeParameters, that.boundTypeParameters) && Objects.equals(function.getSignature(), that.function.getSignature()); } @Override public int hashCode() { return Objects.hash(function.getSignature(), boundTypeParameters, arity); } }
kuzemchik/presto
presto-main/src/main/java/com/facebook/presto/metadata/SpecializedFunctionKey.java
Java
apache-2.0
2,138
/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package com.skia; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLDisplay; import javax.microedition.khronos.opengles.GL10; import android.content.Context; import android.opengl.EGL14; import android.opengl.GLSurfaceView; import android.os.Build; import android.util.Log; import android.view.MotionEvent; public class SkiaSampleView extends GLSurfaceView { private final SkiaSampleRenderer mSampleRenderer; private boolean mRequestedOpenGLAPI; // true == use (desktop) OpenGL. false == use OpenGL ES. private int mRequestedMSAASampleCount; public SkiaSampleView(Context ctx, String cmdLineFlags, boolean useOpenGL, int msaaSampleCount) { super(ctx); mSampleRenderer = new SkiaSampleRenderer(this, cmdLineFlags); mRequestedMSAASampleCount = msaaSampleCount; setEGLContextClientVersion(2); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) { setEGLConfigChooser(8, 8, 8, 8, 0, 8); } else { mRequestedOpenGLAPI = useOpenGL; setEGLConfigChooser(new SampleViewEGLConfigChooser()); } setRenderer(mSampleRenderer); setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY); } @Override public boolean onTouchEvent(MotionEvent event) { int count = event.getPointerCount(); for (int i = 0; i < count; i++) { final float x = event.getX(i); final float y = event.getY(i); final int owner = event.getPointerId(i); int action = event.getAction() & MotionEvent.ACTION_MASK; switch (action) { case MotionEvent.ACTION_POINTER_UP: action = MotionEvent.ACTION_UP; break; case MotionEvent.ACTION_POINTER_DOWN: action = MotionEvent.ACTION_DOWN; break; default: break; } final int finalAction = action; queueEvent(new Runnable() { @Override public void run() { mSampleRenderer.handleClick(owner, x, y, finalAction); } }); } return true; } public void inval() { queueEvent(new Runnable() { @Override public void run() { mSampleRenderer.postInval(); } }); } public void terminate() { queueEvent(new Runnable() { @Override public void run() { mSampleRenderer.term(); } }); } public void showOverview() { queueEvent(new Runnable() { @Override public void run() { mSampleRenderer.showOverview(); } }); } public void nextSample() { queueEvent(new Runnable() { @Override public void run() { mSampleRenderer.nextSample(); } }); } public void previousSample() { queueEvent(new Runnable() { @Override public void run() { mSampleRenderer.previousSample(); } }); } public void goToSample(final int position) { queueEvent(new Runnable() { @Override public void run() { mSampleRenderer.goToSample(position); } }); } public void toggleRenderingMode() { queueEvent(new Runnable() { @Override public void run() { mSampleRenderer.toggleRenderingMode(); } }); } public void toggleSlideshow() { queueEvent(new Runnable() { @Override public void run() { mSampleRenderer.toggleSlideshow(); } }); } public void toggleFPS() { queueEvent(new Runnable() { @Override public void run() { mSampleRenderer.toggleFPS(); } }); } public void toggleTiling() { queueEvent(new Runnable() { @Override public void run() { mSampleRenderer.toggleTiling(); } }); } public void toggleBBox() { queueEvent(new Runnable() { @Override public void run() { mSampleRenderer.toggleBBox(); } }); } public void saveToPDF() { queueEvent(new Runnable() { @Override public void run() { mSampleRenderer.saveToPDF(); } }); } public boolean getUsesOpenGLAPI() { return mRequestedOpenGLAPI; } public int getMSAASampleCount() { return mSampleRenderer.getMSAASampleCount(); } private class SampleViewEGLConfigChooser implements GLSurfaceView.EGLConfigChooser { @Override public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display) { int numConfigs = 0; int[] configSpec = null; int[] value = new int[1]; int[] validAPIs = new int[] { EGL14.EGL_OPENGL_API, EGL14.EGL_OPENGL_ES_API }; int initialAPI = mRequestedOpenGLAPI ? 0 : 1; for (int i = initialAPI; i < validAPIs.length && numConfigs == 0; i++) { int currentAPI = validAPIs[i]; EGL14.eglBindAPI(currentAPI); // setup the renderableType which will only be included in the // spec if we are attempting to get access to the OpenGL APIs. int renderableType = EGL14.EGL_OPENGL_BIT; if (currentAPI == EGL14.EGL_OPENGL_API) { renderableType = EGL14.EGL_OPENGL_ES2_BIT; } if (mRequestedMSAASampleCount > 0) { configSpec = new int[] { EGL10.EGL_RED_SIZE, 8, EGL10.EGL_GREEN_SIZE, 8, EGL10.EGL_BLUE_SIZE, 8, EGL10.EGL_ALPHA_SIZE, 8, EGL10.EGL_DEPTH_SIZE, 0, EGL10.EGL_STENCIL_SIZE, 8, EGL10.EGL_SAMPLE_BUFFERS, 1, EGL10.EGL_SAMPLES, mRequestedMSAASampleCount, EGL10.EGL_RENDERABLE_TYPE, renderableType, EGL10.EGL_NONE }; // EGL_RENDERABLE_TYPE is only needed when attempting to use // the OpenGL API (not ES) and causes many EGL drivers to fail // with a BAD_ATTRIBUTE error. if (!mRequestedOpenGLAPI) { configSpec[16] = EGL10.EGL_NONE; Log.i("Skia", "spec: " + configSpec); } if (!egl.eglChooseConfig(display, configSpec, null, 0, value)) { Log.i("Skia", "Could not get MSAA context count: " + mRequestedMSAASampleCount); } numConfigs = value[0]; } if (numConfigs <= 0) { // Try without multisampling. configSpec = new int[] { EGL10.EGL_RED_SIZE, 8, EGL10.EGL_GREEN_SIZE, 8, EGL10.EGL_BLUE_SIZE, 8, EGL10.EGL_ALPHA_SIZE, 8, EGL10.EGL_DEPTH_SIZE, 0, EGL10.EGL_STENCIL_SIZE, 8, EGL10.EGL_RENDERABLE_TYPE, renderableType, EGL10.EGL_NONE }; // EGL_RENDERABLE_TYPE is only needed when attempting to use // the OpenGL API (not ES) and causes many EGL drivers to fail // with a BAD_ATTRIBUTE error. if (!mRequestedOpenGLAPI) { configSpec[12] = EGL10.EGL_NONE; Log.i("Skia", "spec: " + configSpec); } if (!egl.eglChooseConfig(display, configSpec, null, 0, value)) { Log.i("Skia", "Could not get non-MSAA context count"); } numConfigs = value[0]; } } if (numConfigs <= 0) { throw new IllegalArgumentException("No configs match configSpec"); } // Get all matching configurations. EGLConfig[] configs = new EGLConfig[numConfigs]; if (!egl.eglChooseConfig(display, configSpec, configs, numConfigs, value)) { throw new IllegalArgumentException("Could not get config data"); } for (int i = 0; i < configs.length; ++i) { EGLConfig config = configs[i]; if (findConfigAttrib(egl, display, config , EGL10.EGL_RED_SIZE, 0) == 8 && findConfigAttrib(egl, display, config, EGL10.EGL_BLUE_SIZE, 0) == 8 && findConfigAttrib(egl, display, config, EGL10.EGL_GREEN_SIZE, 0) == 8 && findConfigAttrib(egl, display, config, EGL10.EGL_ALPHA_SIZE, 0) == 8 && findConfigAttrib(egl, display, config, EGL10.EGL_STENCIL_SIZE, 0) == 8) { return config; } } throw new IllegalArgumentException("Could not find suitable EGL config"); } private int findConfigAttrib(EGL10 egl, EGLDisplay display, EGLConfig config, int attribute, int defaultValue) { int[] value = new int[1]; if (egl.eglGetConfigAttrib(display, config, attribute, value)) { return value[0]; } return defaultValue; } } }
zero-rp/miniblink49
third_party/skia/platform_tools/android/app/src/com/skia/SkiaSampleView.java
Java
apache-2.0
10,208
package org.apache.maven.repository.metadata; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.artifact.ArtifactScopeEnum; /** * Resolves conflicts in the supplied dependency graph. * Different implementations will implement different conflict resolution policies. * * @author <a href="mailto:oleg@codehaus.org">Oleg Gusakov</a> */ public interface GraphConflictResolver { String ROLE = GraphConflictResolver.class.getName(); /** * Cleanses the supplied graph by leaving only one directed versioned edge\ * between any two nodes, if multiple exists. Uses scope relationships, defined * in <code>ArtifactScopeEnum</code> * * @param graph the "dirty" graph to be simplified via conflict resolution * @param scope scope for which the graph should be resolved * * @return resulting "clean" graph for the specified scope * * @since 3.0 */ MetadataGraph resolveConflicts( MetadataGraph graph, ArtifactScopeEnum scope ) throws GraphConflictResolutionException; }
apache/maven
maven-compat/src/main/java/org/apache/maven/repository/metadata/GraphConflictResolver.java
Java
apache-2.0
1,822
// FIXME: Tell people that this is a manifest file, real code should go into discrete files // FIXME: Tell people how Sprockets and CoffeeScript works // //= require jquery //= require jquery_ujs //= require_tree .
danielwanja/bulk_data_source_flex
testrailsapp/app/assets/javascripts/application.js
JavaScript
mit
215
/* Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package csi import ( "crypto/sha256" "errors" "fmt" "strings" "time" "github.com/golang/glog" "k8s.io/api/core/v1" storage "k8s.io/api/storage/v1alpha1" apierrs "k8s.io/apimachinery/pkg/api/errors" meta "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/kubernetes" "k8s.io/kubernetes/pkg/volume" ) type csiAttacher struct { plugin *csiPlugin k8s kubernetes.Interface waitSleepTime time.Duration } // volume.Attacher methods var _ volume.Attacher = &csiAttacher{} func (c *csiAttacher) Attach(spec *volume.Spec, nodeName types.NodeName) (string, error) { if spec == nil { glog.Error(log("attacher.Attach missing volume.Spec")) return "", errors.New("missing spec") } csiSource, err := getCSISourceFromSpec(spec) if err != nil { glog.Error(log("attacher.Attach failed to get CSI persistent source: %v", err)) return "", err } node := string(nodeName) pvName := spec.PersistentVolume.GetName() attachID := getAttachmentName(csiSource.VolumeHandle, csiSource.Driver, node) attachment := &storage.VolumeAttachment{ ObjectMeta: meta.ObjectMeta{ Name: attachID, }, Spec: storage.VolumeAttachmentSpec{ NodeName: node, Attacher: csiSource.Driver, Source: storage.VolumeAttachmentSource{ PersistentVolumeName: &pvName, }, }, Status: storage.VolumeAttachmentStatus{Attached: false}, } _, err = c.k8s.StorageV1alpha1().VolumeAttachments().Create(attachment) alreadyExist := false if err != nil { if !apierrs.IsAlreadyExists(err) { glog.Error(log("attacher.Attach failed: %v", err)) return "", err } alreadyExist = true } if alreadyExist { glog.V(4).Info(log("attachment [%v] for volume [%v] already exists (will not be recreated)", attachID, csiSource.VolumeHandle)) } else { glog.V(4).Info(log("attachment [%v] for volume [%v] created successfully", attachID, csiSource.VolumeHandle)) } // probe for attachment update here // NOTE: any error from waiting for attachment is logged only. This is because // the primariy intent of the enclosing method is to create VolumeAttachment. // DONOT return that error here as it is mitigated in attacher.WaitForAttach. volAttachmentOK := true if _, err := c.waitForVolumeAttachment(csiSource.VolumeHandle, attachID, csiTimeout); err != nil { volAttachmentOK = false glog.Error(log("attacher.Attach attempted to wait for attachment to be ready, but failed with: %v", err)) } glog.V(4).Info(log("attacher.Attach finished OK with VolumeAttachment verified=%t: attachment object [%s]", volAttachmentOK, attachID)) return attachID, nil } func (c *csiAttacher) WaitForAttach(spec *volume.Spec, attachID string, pod *v1.Pod, timeout time.Duration) (string, error) { source, err := getCSISourceFromSpec(spec) if err != nil { glog.Error(log("attacher.WaitForAttach failed to extract CSI volume source: %v", err)) return "", err } return c.waitForVolumeAttachment(source.VolumeHandle, attachID, timeout) } func (c *csiAttacher) waitForVolumeAttachment(volumeHandle, attachID string, timeout time.Duration) (string, error) { glog.V(4).Info(log("probing for updates from CSI driver for [attachment.ID=%v]", attachID)) ticker := time.NewTicker(c.waitSleepTime) defer ticker.Stop() timer := time.NewTimer(timeout) // TODO (vladimirvivien) investigate making this configurable defer timer.Stop() //TODO (vladimirvivien) instead of polling api-server, change to a api-server watch for { select { case <-ticker.C: glog.V(4).Info(log("probing VolumeAttachment [id=%v]", attachID)) attach, err := c.k8s.StorageV1alpha1().VolumeAttachments().Get(attachID, meta.GetOptions{}) if err != nil { glog.Error(log("attacher.WaitForAttach failed (will continue to try): %v", err)) continue } // if being deleted, fail fast if attach.GetDeletionTimestamp() != nil { glog.Error(log("VolumeAttachment [%s] has deletion timestamp, will not continue to wait for attachment", attachID)) return "", errors.New("volume attachment is being deleted") } // attachment OK if attach.Status.Attached { return attachID, nil } // driver reports attach error attachErr := attach.Status.AttachError if attachErr != nil { glog.Error(log("attachment for %v failed: %v", volumeHandle, attachErr.Message)) return "", errors.New(attachErr.Message) } case <-timer.C: glog.Error(log("attacher.WaitForAttach timeout after %v [volume=%v; attachment.ID=%v]", timeout, volumeHandle, attachID)) return "", fmt.Errorf("attachment timeout for volume %v", volumeHandle) } } } func (c *csiAttacher) VolumesAreAttached(specs []*volume.Spec, nodeName types.NodeName) (map[*volume.Spec]bool, error) { glog.V(4).Info(log("probing attachment status for %d volume(s) ", len(specs))) attached := make(map[*volume.Spec]bool) for _, spec := range specs { if spec == nil { glog.Error(log("attacher.VolumesAreAttached missing volume.Spec")) return nil, errors.New("missing spec") } source, err := getCSISourceFromSpec(spec) if err != nil { glog.Error(log("attacher.VolumesAreAttached failed: %v", err)) continue } attachID := getAttachmentName(source.VolumeHandle, source.Driver, string(nodeName)) glog.V(4).Info(log("probing attachment status for VolumeAttachment %v", attachID)) attach, err := c.k8s.StorageV1alpha1().VolumeAttachments().Get(attachID, meta.GetOptions{}) if err != nil { glog.Error(log("attacher.VolumesAreAttached failed for attach.ID=%v: %v", attachID, err)) continue } glog.V(4).Info(log("attacher.VolumesAreAttached attachment [%v] has status.attached=%t", attachID, attach.Status.Attached)) attached[spec] = attach.Status.Attached } return attached, nil } func (c *csiAttacher) GetDeviceMountPath(spec *volume.Spec) (string, error) { glog.V(4).Info(log("attacher.GetDeviceMountPath is not implemented")) return "", nil } func (c *csiAttacher) MountDevice(spec *volume.Spec, devicePath string, deviceMountPath string) error { glog.V(4).Info(log("attacher.MountDevice is not implemented")) return nil } var _ volume.Detacher = &csiAttacher{} func (c *csiAttacher) Detach(volumeName string, nodeName types.NodeName) error { // volumeName in format driverName<SEP>volumeHandle generated by plugin.GetVolumeName() if volumeName == "" { glog.Error(log("detacher.Detach missing value for parameter volumeName")) return errors.New("missing exepected parameter volumeName") } parts := strings.Split(volumeName, volNameSep) if len(parts) != 2 { glog.Error(log("detacher.Detach insufficient info encoded in volumeName")) return errors.New("volumeName missing expected data") } driverName := parts[0] volID := parts[1] attachID := getAttachmentName(volID, driverName, string(nodeName)) if err := c.k8s.StorageV1alpha1().VolumeAttachments().Delete(attachID, nil); err != nil { glog.Error(log("detacher.Detach failed to delete VolumeAttachment [%s]: %v", attachID, err)) return err } glog.V(4).Info(log("detacher deleted ok VolumeAttachment.ID=%s", attachID)) return c.waitForVolumeDetachment(volID, attachID) } func (c *csiAttacher) waitForVolumeDetachment(volumeHandle, attachID string) error { glog.V(4).Info(log("probing for updates from CSI driver for [attachment.ID=%v]", attachID)) ticker := time.NewTicker(c.waitSleepTime) defer ticker.Stop() timeout := c.waitSleepTime * 10 timer := time.NewTimer(timeout) // TODO (vladimirvivien) investigate making this configurable defer timer.Stop() //TODO (vladimirvivien) instead of polling api-server, change to a api-server watch for { select { case <-ticker.C: glog.V(4).Info(log("probing VolumeAttachment [id=%v]", attachID)) attach, err := c.k8s.StorageV1alpha1().VolumeAttachments().Get(attachID, meta.GetOptions{}) if err != nil { if apierrs.IsNotFound(err) { //object deleted or never existed, done glog.V(4).Info(log("VolumeAttachment object [%v] for volume [%v] not found, object deleted", attachID, volumeHandle)) return nil } glog.Error(log("detacher.WaitForDetach failed for volume [%s] (will continue to try): %v", volumeHandle, err)) continue } // driver reports attach error detachErr := attach.Status.DetachError if detachErr != nil { glog.Error(log("detachment for VolumeAttachment [%v] for volume [%s] failed: %v", attachID, volumeHandle, detachErr.Message)) return errors.New(detachErr.Message) } case <-timer.C: glog.Error(log("detacher.WaitForDetach timeout after %v [volume=%v; attachment.ID=%v]", timeout, volumeHandle, attachID)) return fmt.Errorf("detachment timed out for volume %v", volumeHandle) } } } func (c *csiAttacher) UnmountDevice(deviceMountPath string) error { glog.V(4).Info(log("detacher.UnmountDevice is not implemented")) return nil } // getAttachmentName returns csi-<sha252(volName,csiDriverName,NodeName> func getAttachmentName(volName, csiDriverName, nodeName string) string { result := sha256.Sum256([]byte(fmt.Sprintf("%s%s%s", volName, csiDriverName, nodeName))) return fmt.Sprintf("csi-%x", result) }
aleksandra-malinowska/autoscaler
vertical-pod-autoscaler/vendor/k8s.io/kubernetes/pkg/volume/csi/csi_attacher.go
GO
apache-2.0
9,693
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.nifi.cluster.coordination.flow; import org.apache.nifi.cluster.protocol.DataFlow; import org.apache.nifi.cluster.protocol.NodeIdentifier; /** * <p> * A FlowElection is responsible for examining multiple versions of a dataflow and determining which of * the versions is the "correct" version of the flow. * </p> */ public interface FlowElection { /** * Checks if the election has completed or not. * * @return <code>true</code> if the election has completed, <code>false</code> otherwise. */ boolean isElectionComplete(); /** * Returns <code>true</code> if a vote has already been counted for the given Node Identifier, <code>false</code> otherwise. * * @param nodeIdentifier the identifier of the node * @return <code>true</code> if a vote has already been counted for the given Node Identifier, <code>false</code> otherwise. */ boolean isVoteCounted(NodeIdentifier nodeIdentifier); /** * If the election has not yet completed, adds the given DataFlow to the list of candidates * (if it is not already in the running) and increments the number of votes for this DataFlow by 1. * If the election has completed, the given candidate is ignored, and the already-elected DataFlow * will be returned. If the election has not yet completed, a vote will be cast for the given * candidate and <code>null</code> will be returned, signifying that no candidate has yet been chosen. * * @param candidate the DataFlow to vote for and add to the pool of candidates if not already present * @param nodeIdentifier the identifier of the node casting the vote * * @return the elected {@link DataFlow}, or <code>null</code> if no DataFlow has yet been elected */ DataFlow castVote(DataFlow candidate, NodeIdentifier nodeIdentifier); /** * Returns the DataFlow that has been elected as the "correct" version of the flow, or <code>null</code> * if the election has not yet completed. * * @return the DataFlow that has been elected as the "correct" version of the flow, or <code>null</code> * if the election has not yet completed. */ DataFlow getElectedDataFlow(); /** * Returns a human-readable description of the status of the election * * @return a human-readable description of the status of the election */ String getStatusDescription(); }
WilliamNouet/nifi
nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/main/java/org/apache/nifi/cluster/coordination/flow/FlowElection.java
Java
apache-2.0
3,255
(function ($, Drupal) { /** * Toggle show/hide links for off canvas layout. */ Drupal.behaviors.omegaOffCanvasLayout = { attach: function (context) { $('#off-canvas').click(function(e) { if (!$(this).hasClass('is-visible')) { $(this).addClass('is-visible'); e.preventDefault(); e.stopPropagation(); } }); $('#off-canvas-hide').click(function(e) { $(this).parent().removeClass('is-visible'); e.preventDefault(); e.stopPropagation(); }); $('.l-page').click(function(e) { if($('#off-canvas').hasClass('is-visible') && $(e.target).closest('#off-canvas').length === 0) { $('#off-canvas').removeClass('is-visible'); e.stopPropagation(); } }); } }; })(jQuery, Drupal);
sgurlt/drupal-sandbox
www/sites/all/themes/omega/omega/layouts/off-canvas/assets/off-canvas.js
JavaScript
gpl-2.0
827
/// <reference path="MediaStream.d.ts" /> /// <reference path="RTCPeerConnection.d.ts" /> var config: RTCConfiguration = { iceServers: [{ urls: "stun.l.google.com:19302" }] }; var constraints: RTCMediaConstraints = { mandatory: { offerToReceiveAudio: true, offerToReceiveVideo: true } }; var peerConnection: RTCPeerConnection = new RTCPeerConnection(config, constraints); navigator.getUserMedia({ audio: true, video: true }, stream => { peerConnection.addStream(stream); }, error => { console.log('Error message: ' + error.message); console.log('Error name: ' + error.name); }); peerConnection.onaddstream = ev => console.log(ev.type); peerConnection.ondatachannel = ev => console.log(ev.type); peerConnection.oniceconnectionstatechange = ev => console.log(ev.type); peerConnection.onnegotiationneeded = ev => console.log(ev.type); peerConnection.onopen = ev => console.log(ev.type); peerConnection.onicecandidate = ev => console.log(ev.type); peerConnection.onremovestream = ev => console.log(ev.type); peerConnection.onstatechange = ev => console.log(ev.type); peerConnection.createOffer( offer => { peerConnection.setLocalDescription(offer, () => console.log("set local description"), error => console.log("Error setting local description: " + error)); }, error => console.log("Error creating offer: " + error)); var type: string = RTCSdpType[RTCSdpType.offer]; var offer: RTCSessionDescriptionInit = { type: type, sdp: "some sdp" }; var sessionDescription = new RTCSessionDescription(offer); peerConnection.setRemoteDescription(sessionDescription, () => { peerConnection.createAnswer( answer => { peerConnection.setLocalDescription(answer, () => console.log('Set local description'), error => console.log( "Error setting local description from created answer: " + error + "; answer.sdp=" + answer.sdp)); }, error => console.log("Error creating answer: " + error)); }, error => console.log('Error setting remote description: ' + error + "; offer.sdp=" + offer.sdp)); var webkitSessionDescription = new webkitRTCSessionDescription(offer); peerConnection.setRemoteDescription(webkitSessionDescription, () => { peerConnection.createAnswer( answer => { peerConnection.setLocalDescription(answer, () => console.log('Set local description'), error => console.log( "Error setting local description from created answer: " + error + "; answer.sdp=" + answer.sdp)); }, error => console.log("Error creating answer: " + error)); }, error => console.log('Error setting remote description: ' + error + "; offer.sdp=" + offer.sdp)); var mozSessionDescription = new mozRTCSessionDescription(offer); peerConnection.setRemoteDescription(mozSessionDescription, () => { peerConnection.createAnswer( answer => { peerConnection.setLocalDescription(answer, () => console.log('Set local description'), error => console.log( "Error setting local description from created answer: " + error + "; answer.sdp=" + answer.sdp)); }, error => console.log("Error creating answer: " + error)); }, error => console.log('Error setting remote description: ' + error + "; offer.sdp=" + offer.sdp)); var wkPeerConnection: webkitRTCPeerConnection = new webkitRTCPeerConnection(config, constraints);
ryan-codingintrigue/DefinitelyTyped
webrtc/RTCPeerConnection-tests.ts
TypeScript
mit
3,396
#!/usr/bin/env python2 # # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from test_framework.test_framework import ComparisonTestFramework from test_framework.util import * from test_framework.mininode import CTransaction, NetworkThread from test_framework.blocktools import create_coinbase, create_block from test_framework.comptool import TestInstance, TestManager from test_framework.script import CScript, OP_1NEGATE, OP_NOP2, OP_DROP from binascii import hexlify, unhexlify import cStringIO import time def cltv_invalidate(tx): '''Modify the signature in vin 0 of the tx to fail CLTV Prepends -1 CLTV DROP in the scriptSig itself. ''' tx.vin[0].scriptSig = CScript([OP_1NEGATE, OP_NOP2, OP_DROP] + list(CScript(tx.vin[0].scriptSig))) ''' This test is meant to exercise BIP65 (CHECKLOCKTIMEVERIFY) Connect to a single node. Mine 2 (version 3) blocks (save the coinbases for later). Generate 98 more version 3 blocks, verify the node accepts. Mine 749 version 4 blocks, verify the node accepts. Check that the new CLTV rules are not enforced on the 750th version 4 block. Check that the new CLTV rules are enforced on the 751st version 4 block. Mine 199 new version blocks. Mine 1 old-version block. Mine 1 new version block. Mine 1 old version block, see that the node rejects. ''' class BIP65Test(ComparisonTestFramework): def __init__(self): self.num_nodes = 1 def setup_network(self): # Must set the blockversion for this test self.nodes = start_nodes(1, self.options.tmpdir, extra_args=[['-debug', '-whitelist=127.0.0.1', '-blockversion=3']], binary=[self.options.testbinary]) def run_test(self): test = TestManager(self, self.options.tmpdir) test.add_all_connections(self.nodes) NetworkThread().start() # Start up network handling in another thread test.run() def create_transaction(self, node, coinbase, to_address, amount): from_txid = node.getblock(coinbase)['tx'][0] inputs = [{ "txid" : from_txid, "vout" : 0}] outputs = { to_address : amount } rawtx = node.createrawtransaction(inputs, outputs) signresult = node.signrawtransaction(rawtx) tx = CTransaction() f = cStringIO.StringIO(unhexlify(signresult['hex'])) tx.deserialize(f) return tx def get_tests(self): self.coinbase_blocks = self.nodes[0].setgenerate(True, 2) self.tip = int ("0x" + self.nodes[0].getbestblockhash() + "L", 0) self.nodeaddress = self.nodes[0].getnewaddress() self.last_block_time = time.time() ''' 98 more version 3 blocks ''' test_blocks = [] for i in xrange(98): block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1) block.nVersion = 3 block.rehash() block.solve() test_blocks.append([block, True]) self.last_block_time += 1 self.tip = block.sha256 yield TestInstance(test_blocks, sync_every_block=False) ''' Mine 749 version 4 blocks ''' test_blocks = [] for i in xrange(749): block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1) block.nVersion = 4 block.rehash() block.solve() test_blocks.append([block, True]) self.last_block_time += 1 self.tip = block.sha256 yield TestInstance(test_blocks, sync_every_block=False) ''' Check that the new CLTV rules are not enforced in the 750th version 3 block. ''' spendtx = self.create_transaction(self.nodes[0], self.coinbase_blocks[0], self.nodeaddress, 1.0) cltv_invalidate(spendtx) spendtx.rehash() block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1) block.nVersion = 4 block.vtx.append(spendtx) block.hashMerkleRoot = block.calc_merkle_root() block.rehash() block.solve() self.last_block_time += 1 self.tip = block.sha256 yield TestInstance([[block, True]]) ''' Check that the new CLTV rules are enforced in the 751st version 4 block. ''' spendtx = self.create_transaction(self.nodes[0], self.coinbase_blocks[1], self.nodeaddress, 1.0) cltv_invalidate(spendtx) spendtx.rehash() block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1) block.nVersion = 4 block.vtx.append(spendtx) block.hashMerkleRoot = block.calc_merkle_root() block.rehash() block.solve() self.last_block_time += 1 yield TestInstance([[block, False]]) ''' Mine 199 new version blocks on last valid tip ''' test_blocks = [] for i in xrange(199): block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1) block.nVersion = 4 block.rehash() block.solve() test_blocks.append([block, True]) self.last_block_time += 1 self.tip = block.sha256 yield TestInstance(test_blocks, sync_every_block=False) ''' Mine 1 old version block ''' block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1) block.nVersion = 3 block.rehash() block.solve() self.last_block_time += 1 self.tip = block.sha256 yield TestInstance([[block, True]]) ''' Mine 1 new version block ''' block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1) block.nVersion = 4 block.rehash() block.solve() self.last_block_time += 1 self.tip = block.sha256 yield TestInstance([[block, True]]) ''' Mine 1 old version block, should be invalid ''' block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1) block.nVersion = 3 block.rehash() block.solve() self.last_block_time += 1 yield TestInstance([[block, False]]) if __name__ == '__main__': BIP65Test().main()
octocoin-project/octocoin
qa/rpc-tests/bip65-cltv-p2p.py
Python
mit
6,411
/*! MVW-Injection (0.2.5). (C) 2015 Xavier Boubert. MIT @license: en.wikipedia.org/wiki/MIT_License */ (function(root) { 'use strict'; var DependencyInjection = new (function DependencyInjection() { var _this = this, _interfaces = {}; function _formatFactoryFunction(factoryFunction) { if (typeof factoryFunction == 'function') { var funcString = factoryFunction .toString() // remove comments .replace(/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg, ''); var matches = funcString.match(/^function\s*[^\(]*\s*\(\s*([^\)]*)\)/m); if (matches === null || matches.length < 2) { factoryFunction = [factoryFunction]; } else { factoryFunction = matches[1] .replace(/\s/g, '') .split(',') .filter(function(arg) { return arg.trim().length > 0; }) .concat(factoryFunction); } return factoryFunction; } else { var factoryArrayCopy = []; for (var i = 0; i < factoryFunction.length; i++) { factoryArrayCopy.push(factoryFunction[i]); } factoryFunction = factoryArrayCopy; } return factoryFunction; } function Injector(instanceName) { function _getInjections(dependencies, name, customDependencies, noError) { var interfaces = _interfaces[name].interfacesSupported, injections = [], i, j; for (i = 0; i < dependencies.length; i++) { var factory = null; if (customDependencies && typeof customDependencies[dependencies[i]] != 'undefined') { factory = customDependencies[dependencies[i]]; } else { for (j = 0; j < interfaces.length; j++) { if (!_interfaces[interfaces[j]]) { if (noError) { return false; } throw new Error('DependencyInjection: "' + interfaces[j] + '" interface is not registered.'); } factory = _interfaces[interfaces[j]].factories[dependencies[i]]; if (factory) { factory.interfaceName = interfaces[j]; break; } } } if (factory) { if (!factory.instantiated) { var deps = _formatFactoryFunction(factory.result); factory.result = deps.pop(); var factoryInjections = _getInjections(deps, factory.interfaceName); factory.result = factory.result.apply(_this, factoryInjections); factory.instantiated = true; } injections.push(factory.result); } else { if (noError) { return false; } throw new Error('DependencyInjection: "' + dependencies[i] + '" is not registered or accessible in ' + name + '.'); } } return injections; } this.get = function(factoryName, noError) { var injections = _getInjections([factoryName], instanceName, null, noError); if (injections.length) { return injections[0]; } return false; }; this.invoke = function(thisArg, func, customDependencies) { var dependencies = _formatFactoryFunction(func); func = dependencies.pop(); if (customDependencies) { var formatcustomDependencies = {}, interfaceName, factory; for (interfaceName in customDependencies) { for (factory in customDependencies[interfaceName]) { formatcustomDependencies[factory] = { interfaceName: interfaceName, instantiated: false, result: customDependencies[interfaceName][factory] }; } } customDependencies = formatcustomDependencies; } var injections = _getInjections(dependencies, instanceName, customDependencies); return func.apply(thisArg, injections); }; } this.injector = {}; this.registerInterface = function(name, canInjectInterfaces) { if (_this[name]) { return _this; } _interfaces[name] = { interfacesSupported: (canInjectInterfaces || []).concat(name), factories: {} }; _this.injector[name] = new Injector(name); _this[name] = function DependencyInjectionFactory(factoryName, factoryFunction, replaceIfExists) { if (!replaceIfExists && _interfaces[name].factories[factoryName]) { return _this; } _interfaces[name].factories[factoryName] = { instantiated: false, result: factoryFunction }; return _this; }; return _this; }; })(); if (typeof module != 'undefined' && typeof module.exports != 'undefined') { module.exports = DependencyInjection; } else { root.DependencyInjection = DependencyInjection; } })(this);
dlueth/cdnjs
ajax/libs/mvw-injection/0.2.5/dependency-injection.js
JavaScript
mit
5,110
/** * Copyright 2013-2014, 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. * * @providesModule ReactCompositeComponent */ "use strict"; var ReactComponent = require("./ReactComponent"); var ReactContext = require("./ReactContext"); var ReactCurrentOwner = require("./ReactCurrentOwner"); var ReactElement = require("./ReactElement"); var ReactElementValidator = require("./ReactElementValidator"); var ReactEmptyComponent = require("./ReactEmptyComponent"); var ReactErrorUtils = require("./ReactErrorUtils"); var ReactLegacyElement = require("./ReactLegacyElement"); var ReactOwner = require("./ReactOwner"); var ReactPerf = require("./ReactPerf"); var ReactPropTransferer = require("./ReactPropTransferer"); var ReactPropTypeLocations = require("./ReactPropTypeLocations"); var ReactPropTypeLocationNames = require("./ReactPropTypeLocationNames"); var ReactUpdates = require("./ReactUpdates"); var assign = require("./Object.assign"); var instantiateReactComponent = require("./instantiateReactComponent"); var invariant = require("./invariant"); var keyMirror = require("./keyMirror"); var keyOf = require("./keyOf"); var monitorCodeUse = require("./monitorCodeUse"); var mapObject = require("./mapObject"); var shouldUpdateReactComponent = require("./shouldUpdateReactComponent"); var warning = require("./warning"); var MIXINS_KEY = keyOf({mixins: null}); /** * Policies that describe methods in `ReactCompositeComponentInterface`. */ var SpecPolicy = keyMirror({ /** * These methods may be defined only once by the class specification or mixin. */ DEFINE_ONCE: null, /** * These methods may be defined by both the class specification and mixins. * Subsequent definitions will be chained. These methods must return void. */ DEFINE_MANY: null, /** * These methods are overriding the base ReactCompositeComponent class. */ OVERRIDE_BASE: null, /** * These methods are similar to DEFINE_MANY, except we assume they return * objects. We try to merge the keys of the return values of all the mixed in * functions. If there is a key conflict we throw. */ DEFINE_MANY_MERGED: null }); var injectedMixins = []; /** * Composite components are higher-level components that compose other composite * or native components. * * To create a new type of `ReactCompositeComponent`, pass a specification of * your new class to `React.createClass`. The only requirement of your class * specification is that you implement a `render` method. * * var MyComponent = React.createClass({ * render: function() { * return <div>Hello World</div>; * } * }); * * The class specification supports a specific protocol of methods that have * special meaning (e.g. `render`). See `ReactCompositeComponentInterface` for * more the comprehensive protocol. Any other properties and methods in the * class specification will available on the prototype. * * @interface ReactCompositeComponentInterface * @internal */ var ReactCompositeComponentInterface = { /** * An array of Mixin objects to include when defining your component. * * @type {array} * @optional */ mixins: SpecPolicy.DEFINE_MANY, /** * An object containing properties and methods that should be defined on * the component's constructor instead of its prototype (static methods). * * @type {object} * @optional */ statics: SpecPolicy.DEFINE_MANY, /** * Definition of prop types for this component. * * @type {object} * @optional */ propTypes: SpecPolicy.DEFINE_MANY, /** * Definition of context types for this component. * * @type {object} * @optional */ contextTypes: SpecPolicy.DEFINE_MANY, /** * Definition of context types this component sets for its children. * * @type {object} * @optional */ childContextTypes: SpecPolicy.DEFINE_MANY, // ==== Definition methods ==== /** * Invoked when the component is mounted. Values in the mapping will be set on * `this.props` if that prop is not specified (i.e. using an `in` check). * * This method is invoked before `getInitialState` and therefore cannot rely * on `this.state` or use `this.setState`. * * @return {object} * @optional */ getDefaultProps: SpecPolicy.DEFINE_MANY_MERGED, /** * Invoked once before the component is mounted. The return value will be used * as the initial value of `this.state`. * * getInitialState: function() { * return { * isOn: false, * fooBaz: new BazFoo() * } * } * * @return {object} * @optional */ getInitialState: SpecPolicy.DEFINE_MANY_MERGED, /** * @return {object} * @optional */ getChildContext: SpecPolicy.DEFINE_MANY_MERGED, /** * Uses props from `this.props` and state from `this.state` to render the * structure of the component. * * No guarantees are made about when or how often this method is invoked, so * it must not have side effects. * * render: function() { * var name = this.props.name; * return <div>Hello, {name}!</div>; * } * * @return {ReactComponent} * @nosideeffects * @required */ render: SpecPolicy.DEFINE_ONCE, // ==== Delegate methods ==== /** * Invoked when the component is initially created and about to be mounted. * This may have side effects, but any external subscriptions or data created * by this method must be cleaned up in `componentWillUnmount`. * * @optional */ componentWillMount: SpecPolicy.DEFINE_MANY, /** * Invoked when the component has been mounted and has a DOM representation. * However, there is no guarantee that the DOM node is in the document. * * Use this as an opportunity to operate on the DOM when the component has * been mounted (initialized and rendered) for the first time. * * @param {DOMElement} rootNode DOM element representing the component. * @optional */ componentDidMount: SpecPolicy.DEFINE_MANY, /** * Invoked before the component receives new props. * * Use this as an opportunity to react to a prop transition by updating the * state using `this.setState`. Current props are accessed via `this.props`. * * componentWillReceiveProps: function(nextProps, nextContext) { * this.setState({ * likesIncreasing: nextProps.likeCount > this.props.likeCount * }); * } * * NOTE: There is no equivalent `componentWillReceiveState`. An incoming prop * transition may cause a state change, but the opposite is not true. If you * need it, you are probably looking for `componentWillUpdate`. * * @param {object} nextProps * @optional */ componentWillReceiveProps: SpecPolicy.DEFINE_MANY, /** * Invoked while deciding if the component should be updated as a result of * receiving new props, state and/or context. * * Use this as an opportunity to `return false` when you're certain that the * transition to the new props/state/context will not require a component * update. * * shouldComponentUpdate: function(nextProps, nextState, nextContext) { * return !equal(nextProps, this.props) || * !equal(nextState, this.state) || * !equal(nextContext, this.context); * } * * @param {object} nextProps * @param {?object} nextState * @param {?object} nextContext * @return {boolean} True if the component should update. * @optional */ shouldComponentUpdate: SpecPolicy.DEFINE_ONCE, /** * Invoked when the component is about to update due to a transition from * `this.props`, `this.state` and `this.context` to `nextProps`, `nextState` * and `nextContext`. * * Use this as an opportunity to perform preparation before an update occurs. * * NOTE: You **cannot** use `this.setState()` in this method. * * @param {object} nextProps * @param {?object} nextState * @param {?object} nextContext * @param {ReactReconcileTransaction} transaction * @optional */ componentWillUpdate: SpecPolicy.DEFINE_MANY, /** * Invoked when the component's DOM representation has been updated. * * Use this as an opportunity to operate on the DOM when the component has * been updated. * * @param {object} prevProps * @param {?object} prevState * @param {?object} prevContext * @param {DOMElement} rootNode DOM element representing the component. * @optional */ componentDidUpdate: SpecPolicy.DEFINE_MANY, /** * Invoked when the component is about to be removed from its parent and have * its DOM representation destroyed. * * Use this as an opportunity to deallocate any external resources. * * NOTE: There is no `componentDidUnmount` since your component will have been * destroyed by that point. * * @optional */ componentWillUnmount: SpecPolicy.DEFINE_MANY, // ==== Advanced methods ==== /** * Updates the component's currently mounted DOM representation. * * By default, this implements React's rendering and reconciliation algorithm. * Sophisticated clients may wish to override this. * * @param {ReactReconcileTransaction} transaction * @internal * @overridable */ updateComponent: SpecPolicy.OVERRIDE_BASE }; /** * Mapping from class specification keys to special processing functions. * * Although these are declared like instance properties in the specification * when defining classes using `React.createClass`, they are actually static * and are accessible on the constructor instead of the prototype. Despite * being static, they must be defined outside of the "statics" key under * which all other static methods are defined. */ var RESERVED_SPEC_KEYS = { displayName: function(Constructor, displayName) { Constructor.displayName = displayName; }, mixins: function(Constructor, mixins) { if (mixins) { for (var i = 0; i < mixins.length; i++) { mixSpecIntoComponent(Constructor, mixins[i]); } } }, childContextTypes: function(Constructor, childContextTypes) { validateTypeDef( Constructor, childContextTypes, ReactPropTypeLocations.childContext ); Constructor.childContextTypes = assign( {}, Constructor.childContextTypes, childContextTypes ); }, contextTypes: function(Constructor, contextTypes) { validateTypeDef( Constructor, contextTypes, ReactPropTypeLocations.context ); Constructor.contextTypes = assign( {}, Constructor.contextTypes, contextTypes ); }, /** * Special case getDefaultProps which should move into statics but requires * automatic merging. */ getDefaultProps: function(Constructor, getDefaultProps) { if (Constructor.getDefaultProps) { Constructor.getDefaultProps = createMergedResultFunction( Constructor.getDefaultProps, getDefaultProps ); } else { Constructor.getDefaultProps = getDefaultProps; } }, propTypes: function(Constructor, propTypes) { validateTypeDef( Constructor, propTypes, ReactPropTypeLocations.prop ); Constructor.propTypes = assign( {}, Constructor.propTypes, propTypes ); }, statics: function(Constructor, statics) { mixStaticSpecIntoComponent(Constructor, statics); } }; function getDeclarationErrorAddendum(component) { var owner = component._owner || null; if (owner && owner.constructor && owner.constructor.displayName) { return ' Check the render method of `' + owner.constructor.displayName + '`.'; } return ''; } function validateTypeDef(Constructor, typeDef, location) { for (var propName in typeDef) { if (typeDef.hasOwnProperty(propName)) { ("production" !== process.env.NODE_ENV ? invariant( typeof typeDef[propName] == 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', Constructor.displayName || 'ReactCompositeComponent', ReactPropTypeLocationNames[location], propName ) : invariant(typeof typeDef[propName] == 'function')); } } } function validateMethodOverride(proto, name) { var specPolicy = ReactCompositeComponentInterface.hasOwnProperty(name) ? ReactCompositeComponentInterface[name] : null; // Disallow overriding of base class methods unless explicitly allowed. if (ReactCompositeComponentMixin.hasOwnProperty(name)) { ("production" !== process.env.NODE_ENV ? invariant( specPolicy === SpecPolicy.OVERRIDE_BASE, 'ReactCompositeComponentInterface: You are attempting to override ' + '`%s` from your class specification. Ensure that your method names ' + 'do not overlap with React methods.', name ) : invariant(specPolicy === SpecPolicy.OVERRIDE_BASE)); } // Disallow defining methods more than once unless explicitly allowed. if (proto.hasOwnProperty(name)) { ("production" !== process.env.NODE_ENV ? invariant( specPolicy === SpecPolicy.DEFINE_MANY || specPolicy === SpecPolicy.DEFINE_MANY_MERGED, 'ReactCompositeComponentInterface: You are attempting to define ' + '`%s` on your component more than once. This conflict may be due ' + 'to a mixin.', name ) : invariant(specPolicy === SpecPolicy.DEFINE_MANY || specPolicy === SpecPolicy.DEFINE_MANY_MERGED)); } } function validateLifeCycleOnReplaceState(instance) { var compositeLifeCycleState = instance._compositeLifeCycleState; ("production" !== process.env.NODE_ENV ? invariant( instance.isMounted() || compositeLifeCycleState === CompositeLifeCycle.MOUNTING, 'replaceState(...): Can only update a mounted or mounting component.' ) : invariant(instance.isMounted() || compositeLifeCycleState === CompositeLifeCycle.MOUNTING)); ("production" !== process.env.NODE_ENV ? invariant( ReactCurrentOwner.current == null, 'replaceState(...): Cannot update during an existing state transition ' + '(such as within `render`). Render methods should be a pure function ' + 'of props and state.' ) : invariant(ReactCurrentOwner.current == null)); ("production" !== process.env.NODE_ENV ? invariant(compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING, 'replaceState(...): Cannot update while unmounting component. This ' + 'usually means you called setState() on an unmounted component.' ) : invariant(compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING)); } /** * Mixin helper which handles policy validation and reserved * specification keys when building `ReactCompositeComponent` classses. */ function mixSpecIntoComponent(Constructor, spec) { if (!spec) { return; } ("production" !== process.env.NODE_ENV ? invariant( !ReactLegacyElement.isValidFactory(spec), 'ReactCompositeComponent: You\'re attempting to ' + 'use a component class as a mixin. Instead, just use a regular object.' ) : invariant(!ReactLegacyElement.isValidFactory(spec))); ("production" !== process.env.NODE_ENV ? invariant( !ReactElement.isValidElement(spec), 'ReactCompositeComponent: You\'re attempting to ' + 'use a component as a mixin. Instead, just use a regular object.' ) : invariant(!ReactElement.isValidElement(spec))); var proto = Constructor.prototype; // By handling mixins before any other properties, we ensure the same // chaining order is applied to methods with DEFINE_MANY policy, whether // mixins are listed before or after these methods in the spec. if (spec.hasOwnProperty(MIXINS_KEY)) { RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins); } for (var name in spec) { if (!spec.hasOwnProperty(name)) { continue; } if (name === MIXINS_KEY) { // We have already handled mixins in a special case above continue; } var property = spec[name]; validateMethodOverride(proto, name); if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) { RESERVED_SPEC_KEYS[name](Constructor, property); } else { // Setup methods on prototype: // The following member methods should not be automatically bound: // 1. Expected ReactCompositeComponent methods (in the "interface"). // 2. Overridden methods (that were mixed in). var isCompositeComponentMethod = ReactCompositeComponentInterface.hasOwnProperty(name); var isAlreadyDefined = proto.hasOwnProperty(name); var markedDontBind = property && property.__reactDontBind; var isFunction = typeof property === 'function'; var shouldAutoBind = isFunction && !isCompositeComponentMethod && !isAlreadyDefined && !markedDontBind; if (shouldAutoBind) { if (!proto.__reactAutoBindMap) { proto.__reactAutoBindMap = {}; } proto.__reactAutoBindMap[name] = property; proto[name] = property; } else { if (isAlreadyDefined) { var specPolicy = ReactCompositeComponentInterface[name]; // These cases should already be caught by validateMethodOverride ("production" !== process.env.NODE_ENV ? invariant( isCompositeComponentMethod && ( specPolicy === SpecPolicy.DEFINE_MANY_MERGED || specPolicy === SpecPolicy.DEFINE_MANY ), 'ReactCompositeComponent: Unexpected spec policy %s for key %s ' + 'when mixing in component specs.', specPolicy, name ) : invariant(isCompositeComponentMethod && ( specPolicy === SpecPolicy.DEFINE_MANY_MERGED || specPolicy === SpecPolicy.DEFINE_MANY ))); // For methods which are defined more than once, call the existing // methods before calling the new property, merging if appropriate. if (specPolicy === SpecPolicy.DEFINE_MANY_MERGED) { proto[name] = createMergedResultFunction(proto[name], property); } else if (specPolicy === SpecPolicy.DEFINE_MANY) { proto[name] = createChainedFunction(proto[name], property); } } else { proto[name] = property; if ("production" !== process.env.NODE_ENV) { // Add verbose displayName to the function, which helps when looking // at profiling tools. if (typeof property === 'function' && spec.displayName) { proto[name].displayName = spec.displayName + '_' + name; } } } } } } } function mixStaticSpecIntoComponent(Constructor, statics) { if (!statics) { return; } for (var name in statics) { var property = statics[name]; if (!statics.hasOwnProperty(name)) { continue; } var isReserved = name in RESERVED_SPEC_KEYS; ("production" !== process.env.NODE_ENV ? invariant( !isReserved, 'ReactCompositeComponent: You are attempting to define a reserved ' + 'property, `%s`, that shouldn\'t be on the "statics" key. Define it ' + 'as an instance property instead; it will still be accessible on the ' + 'constructor.', name ) : invariant(!isReserved)); var isInherited = name in Constructor; ("production" !== process.env.NODE_ENV ? invariant( !isInherited, 'ReactCompositeComponent: You are attempting to define ' + '`%s` on your component more than once. This conflict may be ' + 'due to a mixin.', name ) : invariant(!isInherited)); Constructor[name] = property; } } /** * Merge two objects, but throw if both contain the same key. * * @param {object} one The first object, which is mutated. * @param {object} two The second object * @return {object} one after it has been mutated to contain everything in two. */ function mergeObjectsWithNoDuplicateKeys(one, two) { ("production" !== process.env.NODE_ENV ? invariant( one && two && typeof one === 'object' && typeof two === 'object', 'mergeObjectsWithNoDuplicateKeys(): Cannot merge non-objects' ) : invariant(one && two && typeof one === 'object' && typeof two === 'object')); mapObject(two, function(value, key) { ("production" !== process.env.NODE_ENV ? invariant( one[key] === undefined, 'mergeObjectsWithNoDuplicateKeys(): ' + 'Tried to merge two objects with the same key: `%s`. This conflict ' + 'may be due to a mixin; in particular, this may be caused by two ' + 'getInitialState() or getDefaultProps() methods returning objects ' + 'with clashing keys.', key ) : invariant(one[key] === undefined)); one[key] = value; }); return one; } /** * Creates a function that invokes two functions and merges their return values. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createMergedResultFunction(one, two) { return function mergedResult() { var a = one.apply(this, arguments); var b = two.apply(this, arguments); if (a == null) { return b; } else if (b == null) { return a; } return mergeObjectsWithNoDuplicateKeys(a, b); }; } /** * Creates a function that invokes two functions and ignores their return vales. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createChainedFunction(one, two) { return function chainedFunction() { one.apply(this, arguments); two.apply(this, arguments); }; } /** * `ReactCompositeComponent` maintains an auxiliary life cycle state in * `this._compositeLifeCycleState` (which can be null). * * This is different from the life cycle state maintained by `ReactComponent` in * `this._lifeCycleState`. The following diagram shows how the states overlap in * time. There are times when the CompositeLifeCycle is null - at those times it * is only meaningful to look at ComponentLifeCycle alone. * * Top Row: ReactComponent.ComponentLifeCycle * Low Row: ReactComponent.CompositeLifeCycle * * +-------+---------------------------------+--------+ * | UN | MOUNTED | UN | * |MOUNTED| | MOUNTED| * +-------+---------------------------------+--------+ * | ^--------+ +-------+ +--------^ | * | | | | | | | | * | 0--|MOUNTING|-0-|RECEIVE|-0-| UN |--->0 | * | | | |PROPS | |MOUNTING| | * | | | | | | | | * | | | | | | | | * | +--------+ +-------+ +--------+ | * | | | | * +-------+---------------------------------+--------+ */ var CompositeLifeCycle = keyMirror({ /** * Components in the process of being mounted respond to state changes * differently. */ MOUNTING: null, /** * Components in the process of being unmounted are guarded against state * changes. */ UNMOUNTING: null, /** * Components that are mounted and receiving new props respond to state * changes differently. */ RECEIVING_PROPS: null }); /** * @lends {ReactCompositeComponent.prototype} */ var ReactCompositeComponentMixin = { /** * Base constructor for all composite component. * * @param {ReactElement} element * @final * @internal */ construct: function(element) { // Children can be either an array or more than one argument ReactComponent.Mixin.construct.apply(this, arguments); ReactOwner.Mixin.construct.apply(this, arguments); this.state = null; this._pendingState = null; // This is the public post-processed context. The real context and pending // context lives on the element. this.context = null; this._compositeLifeCycleState = null; }, /** * Checks whether or not this composite component is mounted. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function() { return ReactComponent.Mixin.isMounted.call(this) && this._compositeLifeCycleState !== CompositeLifeCycle.MOUNTING; }, /** * Initializes the component, renders markup, and registers event listeners. * * @param {string} rootID DOM ID of the root node. * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {number} mountDepth number of components in the owner hierarchy * @return {?string} Rendered markup to be inserted into the DOM. * @final * @internal */ mountComponent: ReactPerf.measure( 'ReactCompositeComponent', 'mountComponent', function(rootID, transaction, mountDepth) { ReactComponent.Mixin.mountComponent.call( this, rootID, transaction, mountDepth ); this._compositeLifeCycleState = CompositeLifeCycle.MOUNTING; if (this.__reactAutoBindMap) { this._bindAutoBindMethods(); } this.context = this._processContext(this._currentElement._context); this.props = this._processProps(this.props); this.state = this.getInitialState ? this.getInitialState() : null; ("production" !== process.env.NODE_ENV ? invariant( typeof this.state === 'object' && !Array.isArray(this.state), '%s.getInitialState(): must return an object or null', this.constructor.displayName || 'ReactCompositeComponent' ) : invariant(typeof this.state === 'object' && !Array.isArray(this.state))); this._pendingState = null; this._pendingForceUpdate = false; if (this.componentWillMount) { this.componentWillMount(); // When mounting, calls to `setState` by `componentWillMount` will set // `this._pendingState` without triggering a re-render. if (this._pendingState) { this.state = this._pendingState; this._pendingState = null; } } this._renderedComponent = instantiateReactComponent( this._renderValidatedComponent(), this._currentElement.type // The wrapping type ); // Done with mounting, `setState` will now trigger UI changes. this._compositeLifeCycleState = null; var markup = this._renderedComponent.mountComponent( rootID, transaction, mountDepth + 1 ); if (this.componentDidMount) { transaction.getReactMountReady().enqueue(this.componentDidMount, this); } return markup; } ), /** * Releases any resources allocated by `mountComponent`. * * @final * @internal */ unmountComponent: function() { this._compositeLifeCycleState = CompositeLifeCycle.UNMOUNTING; if (this.componentWillUnmount) { this.componentWillUnmount(); } this._compositeLifeCycleState = null; this._renderedComponent.unmountComponent(); this._renderedComponent = null; ReactComponent.Mixin.unmountComponent.call(this); // Some existing components rely on this.props even after they've been // destroyed (in event handlers). // TODO: this.props = null; // TODO: this.state = null; }, /** * Sets a subset of the state. Always use this or `replaceState` to mutate * state. You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * There is no guarantee that calls to `setState` will run synchronously, * as they may eventually be batched together. You can provide an optional * callback that will be executed when the call to setState is actually * completed. * * @param {object} partialState Next partial state to be merged with state. * @param {?function} callback Called after state is updated. * @final * @protected */ setState: function(partialState, callback) { ("production" !== process.env.NODE_ENV ? invariant( typeof partialState === 'object' || partialState == null, 'setState(...): takes an object of state variables to update.' ) : invariant(typeof partialState === 'object' || partialState == null)); if ("production" !== process.env.NODE_ENV){ ("production" !== process.env.NODE_ENV ? warning( partialState != null, 'setState(...): You passed an undefined or null state object; ' + 'instead, use forceUpdate().' ) : null); } // Merge with `_pendingState` if it exists, otherwise with existing state. this.replaceState( assign({}, this._pendingState || this.state, partialState), callback ); }, /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {object} completeState Next state. * @param {?function} callback Called after state is updated. * @final * @protected */ replaceState: function(completeState, callback) { validateLifeCycleOnReplaceState(this); this._pendingState = completeState; if (this._compositeLifeCycleState !== CompositeLifeCycle.MOUNTING) { // If we're in a componentWillMount handler, don't enqueue a rerender // because ReactUpdates assumes we're in a browser context (which is wrong // for server rendering) and we're about to do a render anyway. // TODO: The callback here is ignored when setState is called from // componentWillMount. Either fix it or disallow doing so completely in // favor of getInitialState. ReactUpdates.enqueueUpdate(this, callback); } }, /** * Filters the context object to only contain keys specified in * `contextTypes`, and asserts that they are valid. * * @param {object} context * @return {?object} * @private */ _processContext: function(context) { var maskedContext = null; var contextTypes = this.constructor.contextTypes; if (contextTypes) { maskedContext = {}; for (var contextName in contextTypes) { maskedContext[contextName] = context[contextName]; } if ("production" !== process.env.NODE_ENV) { this._checkPropTypes( contextTypes, maskedContext, ReactPropTypeLocations.context ); } } return maskedContext; }, /** * @param {object} currentContext * @return {object} * @private */ _processChildContext: function(currentContext) { var childContext = this.getChildContext && this.getChildContext(); var displayName = this.constructor.displayName || 'ReactCompositeComponent'; if (childContext) { ("production" !== process.env.NODE_ENV ? invariant( typeof this.constructor.childContextTypes === 'object', '%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', displayName ) : invariant(typeof this.constructor.childContextTypes === 'object')); if ("production" !== process.env.NODE_ENV) { this._checkPropTypes( this.constructor.childContextTypes, childContext, ReactPropTypeLocations.childContext ); } for (var name in childContext) { ("production" !== process.env.NODE_ENV ? invariant( name in this.constructor.childContextTypes, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', displayName, name ) : invariant(name in this.constructor.childContextTypes)); } return assign({}, currentContext, childContext); } return currentContext; }, /** * Processes props by setting default values for unspecified props and * asserting that the props are valid. Does not mutate its argument; returns * a new props object with defaults merged in. * * @param {object} newProps * @return {object} * @private */ _processProps: function(newProps) { if ("production" !== process.env.NODE_ENV) { var propTypes = this.constructor.propTypes; if (propTypes) { this._checkPropTypes(propTypes, newProps, ReactPropTypeLocations.prop); } } return newProps; }, /** * Assert that the props are valid * * @param {object} propTypes Map of prop name to a ReactPropType * @param {object} props * @param {string} location e.g. "prop", "context", "child context" * @private */ _checkPropTypes: function(propTypes, props, location) { // TODO: Stop validating prop types here and only use the element // validation. var componentName = this.constructor.displayName; for (var propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { var error = propTypes[propName](props, propName, componentName, location); if (error instanceof Error) { // We may want to extend this logic for similar errors in // renderComponent calls, so I'm abstracting it away into // a function to minimize refactoring in the future var addendum = getDeclarationErrorAddendum(this); ("production" !== process.env.NODE_ENV ? warning(false, error.message + addendum) : null); } } } }, /** * If any of `_pendingElement`, `_pendingState`, or `_pendingForceUpdate` * is set, update the component. * * @param {ReactReconcileTransaction} transaction * @internal */ performUpdateIfNecessary: function(transaction) { var compositeLifeCycleState = this._compositeLifeCycleState; // Do not trigger a state transition if we are in the middle of mounting or // receiving props because both of those will already be doing this. if (compositeLifeCycleState === CompositeLifeCycle.MOUNTING || compositeLifeCycleState === CompositeLifeCycle.RECEIVING_PROPS) { return; } if (this._pendingElement == null && this._pendingState == null && !this._pendingForceUpdate) { return; } var nextContext = this.context; var nextProps = this.props; var nextElement = this._currentElement; if (this._pendingElement != null) { nextElement = this._pendingElement; nextContext = this._processContext(nextElement._context); nextProps = this._processProps(nextElement.props); this._pendingElement = null; this._compositeLifeCycleState = CompositeLifeCycle.RECEIVING_PROPS; if (this.componentWillReceiveProps) { this.componentWillReceiveProps(nextProps, nextContext); } } this._compositeLifeCycleState = null; var nextState = this._pendingState || this.state; this._pendingState = null; var shouldUpdate = this._pendingForceUpdate || !this.shouldComponentUpdate || this.shouldComponentUpdate(nextProps, nextState, nextContext); if ("production" !== process.env.NODE_ENV) { if (typeof shouldUpdate === "undefined") { console.warn( (this.constructor.displayName || 'ReactCompositeComponent') + '.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.' ); } } if (shouldUpdate) { this._pendingForceUpdate = false; // Will set `this.props`, `this.state` and `this.context`. this._performComponentUpdate( nextElement, nextProps, nextState, nextContext, transaction ); } else { // If it's determined that a component should not update, we still want // to set props and state. this._currentElement = nextElement; this.props = nextProps; this.state = nextState; this.context = nextContext; // Owner cannot change because shouldUpdateReactComponent doesn't allow // it. TODO: Remove this._owner completely. this._owner = nextElement._owner; } }, /** * Merges new props and state, notifies delegate methods of update and * performs update. * * @param {ReactElement} nextElement Next element * @param {object} nextProps Next public object to set as properties. * @param {?object} nextState Next object to set as state. * @param {?object} nextContext Next public object to set as context. * @param {ReactReconcileTransaction} transaction * @private */ _performComponentUpdate: function( nextElement, nextProps, nextState, nextContext, transaction ) { var prevElement = this._currentElement; var prevProps = this.props; var prevState = this.state; var prevContext = this.context; if (this.componentWillUpdate) { this.componentWillUpdate(nextProps, nextState, nextContext); } this._currentElement = nextElement; this.props = nextProps; this.state = nextState; this.context = nextContext; // Owner cannot change because shouldUpdateReactComponent doesn't allow // it. TODO: Remove this._owner completely. this._owner = nextElement._owner; this.updateComponent( transaction, prevElement ); if (this.componentDidUpdate) { transaction.getReactMountReady().enqueue( this.componentDidUpdate.bind(this, prevProps, prevState, prevContext), this ); } }, receiveComponent: function(nextElement, transaction) { if (nextElement === this._currentElement && nextElement._owner != null) { // Since elements are immutable after the owner is rendered, // we can do a cheap identity compare here to determine if this is a // superfluous reconcile. It's possible for state to be mutable but such // change should trigger an update of the owner which would recreate // the element. We explicitly check for the existence of an owner since // it's possible for a element created outside a composite to be // deeply mutated and reused. return; } ReactComponent.Mixin.receiveComponent.call( this, nextElement, transaction ); }, /** * Updates the component's currently mounted DOM representation. * * By default, this implements React's rendering and reconciliation algorithm. * Sophisticated clients may wish to override this. * * @param {ReactReconcileTransaction} transaction * @param {ReactElement} prevElement * @internal * @overridable */ updateComponent: ReactPerf.measure( 'ReactCompositeComponent', 'updateComponent', function(transaction, prevParentElement) { ReactComponent.Mixin.updateComponent.call( this, transaction, prevParentElement ); var prevComponentInstance = this._renderedComponent; var prevElement = prevComponentInstance._currentElement; var nextElement = this._renderValidatedComponent(); if (shouldUpdateReactComponent(prevElement, nextElement)) { prevComponentInstance.receiveComponent(nextElement, transaction); } else { // These two IDs are actually the same! But nothing should rely on that. var thisID = this._rootNodeID; var prevComponentID = prevComponentInstance._rootNodeID; prevComponentInstance.unmountComponent(); this._renderedComponent = instantiateReactComponent( nextElement, this._currentElement.type ); var nextMarkup = this._renderedComponent.mountComponent( thisID, transaction, this._mountDepth + 1 ); ReactComponent.BackendIDOperations.dangerouslyReplaceNodeWithMarkupByID( prevComponentID, nextMarkup ); } } ), /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldUpdateComponent`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {?function} callback Called after update is complete. * @final * @protected */ forceUpdate: function(callback) { var compositeLifeCycleState = this._compositeLifeCycleState; ("production" !== process.env.NODE_ENV ? invariant( this.isMounted() || compositeLifeCycleState === CompositeLifeCycle.MOUNTING, 'forceUpdate(...): Can only force an update on mounted or mounting ' + 'components.' ) : invariant(this.isMounted() || compositeLifeCycleState === CompositeLifeCycle.MOUNTING)); ("production" !== process.env.NODE_ENV ? invariant( compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING && ReactCurrentOwner.current == null, 'forceUpdate(...): Cannot force an update while unmounting component ' + 'or within a `render` function.' ) : invariant(compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING && ReactCurrentOwner.current == null)); this._pendingForceUpdate = true; ReactUpdates.enqueueUpdate(this, callback); }, /** * @private */ _renderValidatedComponent: ReactPerf.measure( 'ReactCompositeComponent', '_renderValidatedComponent', function() { var renderedComponent; var previousContext = ReactContext.current; ReactContext.current = this._processChildContext( this._currentElement._context ); ReactCurrentOwner.current = this; try { renderedComponent = this.render(); if (renderedComponent === null || renderedComponent === false) { renderedComponent = ReactEmptyComponent.getEmptyComponent(); ReactEmptyComponent.registerNullComponentID(this._rootNodeID); } else { ReactEmptyComponent.deregisterNullComponentID(this._rootNodeID); } } finally { ReactContext.current = previousContext; ReactCurrentOwner.current = null; } ("production" !== process.env.NODE_ENV ? invariant( ReactElement.isValidElement(renderedComponent), '%s.render(): A valid ReactComponent must be returned. You may have ' + 'returned undefined, an array or some other invalid object.', this.constructor.displayName || 'ReactCompositeComponent' ) : invariant(ReactElement.isValidElement(renderedComponent))); return renderedComponent; } ), /** * @private */ _bindAutoBindMethods: function() { for (var autoBindKey in this.__reactAutoBindMap) { if (!this.__reactAutoBindMap.hasOwnProperty(autoBindKey)) { continue; } var method = this.__reactAutoBindMap[autoBindKey]; this[autoBindKey] = this._bindAutoBindMethod(ReactErrorUtils.guard( method, this.constructor.displayName + '.' + autoBindKey )); } }, /** * Binds a method to the component. * * @param {function} method Method to be bound. * @private */ _bindAutoBindMethod: function(method) { var component = this; var boundMethod = method.bind(component); if ("production" !== process.env.NODE_ENV) { boundMethod.__reactBoundContext = component; boundMethod.__reactBoundMethod = method; boundMethod.__reactBoundArguments = null; var componentName = component.constructor.displayName; var _bind = boundMethod.bind; boundMethod.bind = function(newThis ) {for (var args=[],$__0=1,$__1=arguments.length;$__0<$__1;$__0++) args.push(arguments[$__0]); // User is trying to bind() an autobound method; we effectively will // ignore the value of "this" that the user is trying to use, so // let's warn. if (newThis !== component && newThis !== null) { monitorCodeUse('react_bind_warning', { component: componentName }); console.warn( 'bind(): React component methods may only be bound to the ' + 'component instance. See ' + componentName ); } else if (!args.length) { monitorCodeUse('react_bind_warning', { component: componentName }); console.warn( 'bind(): You are binding a component method to the component. ' + 'React does this for you automatically in a high-performance ' + 'way, so you can safely remove this call. See ' + componentName ); return boundMethod; } var reboundMethod = _bind.apply(boundMethod, arguments); reboundMethod.__reactBoundContext = component; reboundMethod.__reactBoundMethod = method; reboundMethod.__reactBoundArguments = args; return reboundMethod; }; } return boundMethod; } }; var ReactCompositeComponentBase = function() {}; assign( ReactCompositeComponentBase.prototype, ReactComponent.Mixin, ReactOwner.Mixin, ReactPropTransferer.Mixin, ReactCompositeComponentMixin ); /** * Module for creating composite components. * * @class ReactCompositeComponent * @extends ReactComponent * @extends ReactOwner * @extends ReactPropTransferer */ var ReactCompositeComponent = { LifeCycle: CompositeLifeCycle, Base: ReactCompositeComponentBase, /** * Creates a composite component class given a class specification. * * @param {object} spec Class specification (which must define `render`). * @return {function} Component constructor function. * @public */ createClass: function(spec) { var Constructor = function(props) { // This constructor is overridden by mocks. The argument is used // by mocks to assert on what gets mounted. This will later be used // by the stand-alone class implementation. }; Constructor.prototype = new ReactCompositeComponentBase(); Constructor.prototype.constructor = Constructor; injectedMixins.forEach( mixSpecIntoComponent.bind(null, Constructor) ); mixSpecIntoComponent(Constructor, spec); // Initialize the defaultProps property after all mixins have been merged if (Constructor.getDefaultProps) { Constructor.defaultProps = Constructor.getDefaultProps(); } ("production" !== process.env.NODE_ENV ? invariant( Constructor.prototype.render, 'createClass(...): Class specification must implement a `render` method.' ) : invariant(Constructor.prototype.render)); if ("production" !== process.env.NODE_ENV) { if (Constructor.prototype.componentShouldUpdate) { monitorCodeUse( 'react_component_should_update_warning', { component: spec.displayName } ); console.warn( (spec.displayName || 'A component') + ' has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.' ); } } // Reduce time spent doing lookups by setting these on the prototype. for (var methodName in ReactCompositeComponentInterface) { if (!Constructor.prototype[methodName]) { Constructor.prototype[methodName] = null; } } if ("production" !== process.env.NODE_ENV) { return ReactLegacyElement.wrapFactory( ReactElementValidator.createFactory(Constructor) ); } return ReactLegacyElement.wrapFactory( ReactElement.createFactory(Constructor) ); }, injection: { injectMixin: function(mixin) { injectedMixins.push(mixin); } } }; module.exports = ReactCompositeComponent;
demns/todomvc-perf-comparison
todomvc/react/node_modules/react/lib/ReactCompositeComponent.js
JavaScript
mit
48,272
<?php /** * System messages translation for CodeIgniter(tm) * * @author CodeIgniter community * @author Mutasim Ridlo, S.Kom * @copyright Copyright (c) 2014 - 2015, British Columbia Institute of Technology (http://bcit.ca/) * @license http://opensource.org/licenses/MIT MIT License * @link http://codeigniter.com */ defined('BASEPATH') OR exit('No direct script access allowed'); $lang['ftp_no_connection'] = 'Tidak dapat menemukan ID koneksi yang sah. Pastikan Anda terhubung sebelum melakukan rutinitas berkas.'; $lang['ftp_unable_to_connect'] = 'Tidak dapat terhubung ke server FTP Anda menggunakan nama host yang disediakan.'; $lang['ftp_unable_to_login'] = 'Tidak dapat masuk ke server FTP Anda. Silakan periksa nama pengguna dan password Anda.'; $lang['ftp_unable_to_mkdir'] = 'Tidak dapat membuat direktori yang telah Anda tentukan.'; $lang['ftp_unable_to_changedir'] = 'Tidak dapat mengubah direktori.'; $lang['ftp_unable_to_chmod'] = 'Tidak dapat mengatur hak akses berkas. Silakan periksa jalur Anda.'; $lang['ftp_unable_to_upload'] = 'Tidak dapat mengunggah berkas yang ditentukan. Silakan periksa jalur Anda.'; $lang['ftp_unable_to_download'] = 'Tidak dapat mengunduh berkas yang ditentukan. Silakan periksa jalur Anda.'; $lang['ftp_no_source_file'] = 'Tidak dapat menemukan sumber berkas. Silakan periksa jalur Anda.'; $lang['ftp_unable_to_rename'] = 'Tidak dapat mengubah nama berkas.'; $lang['ftp_unable_to_delete'] = 'Tidak dapat menghapus berkas.'; $lang['ftp_unable_to_move'] = 'Tidak dapat memindahkan berkas. Pastikan direktori tujuan ada.';
sbrodin/FolletXmasGifts
system/language/indonesian/ftp_lang.php
PHP
mit
1,570
/** * Copyright 2016 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Entry point into AMP for compilation with babel. Just loads amp.js and // Babel's helpers. import '../third_party/babel/custom-babel-helpers'; import './amp-shadow';
DistroScale/amphtml
src/amp-shadow-babel.js
JavaScript
apache-2.0
799
cask "prezi-video" do version "1.13.0" sha256 "477a3d199b1f108e3e1e394a93787fde89f499dea273937c0c1f5fd410b66410" url "https://desktopassets.prezi.com/mac/prezi-video/releases/Prezi_Video_#{version}.dmg" name "Prezi Video" desc "Lets you interact with your content live as you stream or record" homepage "https://prezi.com/video/" pkg "Install Prezi Video.pkg" uninstall quit: "com.prezi.PreziCast", launchctl: "com.prezi.prezivideo.vcam.assistant", pkgutil: [ "com.prezi.PreziCast", "com.prezi.prezivideo.vcam.plugin", ], delete: [ "/Applications/Prezi Video.app", "/Library/CoreMediaIO/Plug-Ins/DAL/PreziAR.plugin", ] zap trash: [ "~/Library/Application Support/com.prezi.PreziCast", "~/Library/Preferences/com.prezi.PreziCast.plist", "~/Library/Preferences/com.prezi.PreziVideo.vcam", ] end
danielbayley/homebrew-cask
Casks/prezi-video.rb
Ruby
bsd-2-clause
955
<?php /* * CKFinder * ======== * http://ckfinder.com * Copyright (C) 2007-2012, CKSource - Frederico Knabben. All rights reserved. * * The software, this file and its contents are subject to the CKFinder * License. Please read the license.txt file before using, installing, copying, * modifying or distribute this file or part of its contents. The contents of * this file is part of the Source Code of CKFinder. */ if (!defined('IN_CKFINDER')) exit; /** * @package CKFinder * @subpackage Utils * @copyright CKSource - Frederico Knabben */ /** * @package CKFinder * @subpackage Utils * @copyright CKSource - Frederico Knabben */ class CKFinder_Connector_Utils_Misc { public static function getErrorMessage($number, $arg = "") { $langCode = 'en'; if (!empty($_GET['langCode']) && preg_match("/^[a-z\-]+$/", $_GET['langCode'])) { if (file_exists(CKFINDER_CONNECTOR_LANG_PATH . "/" . $_GET['langCode'] . ".php")) $langCode = $_GET['langCode']; } include CKFINDER_CONNECTOR_LANG_PATH . "/" . $langCode . ".php"; if ($number) { if (!empty ($GLOBALS['CKFLang']['Errors'][$number])) { $errorMessage = str_replace("%1", $arg, $GLOBALS['CKFLang']['Errors'][$number]); } else { $errorMessage = str_replace("%1", $number, $GLOBALS['CKFLang']['ErrorUnknown']); } } else { $errorMessage = ""; } return $errorMessage; } /** * Simulate the encodeURIComponent() function available in JavaScript * @param string $str * @return string */ public static function encodeURIComponent($str) { $revert = array('%21'=>'!', '%2A'=>'*', '%27'=>"'", '%28'=>'(', '%29'=>')'); return strtr(rawurlencode($str), $revert); } /** * Convert any value to boolean, strings like "false", "FalSE" and "off" are also considered as false * * @static * @access public * @param mixed $value * @return boolean */ public static function booleanValue($value) { if (strcasecmp("false", $value) == 0 || strcasecmp("off", $value) == 0 || !$value) { return false; } else { return true; } } /** * @link http://pl.php.net/manual/en/function.imagecopyresampled.php * replacement to imagecopyresampled that will deliver results that are almost identical except MUCH faster (very typically 30 times faster) * * @static * @access public * @param string $dst_image * @param string $src_image * @param int $dst_x * @param int $dst_y * @param int $src_x * @param int $src_y * @param int $dst_w * @param int $dst_h * @param int $src_w * @param int $src_h * @param int $quality * @return boolean */ public static function fastImageCopyResampled (&$dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h, $quality = 3) { if (empty($src_image) || empty($dst_image)) { return false; } if ($quality <= 1) { $temp = imagecreatetruecolor ($dst_w + 1, $dst_h + 1); imagecopyresized ($temp, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w + 1, $dst_h + 1, $src_w, $src_h); imagecopyresized ($dst_image, $temp, 0, 0, 0, 0, $dst_w, $dst_h, $dst_w, $dst_h); imagedestroy ($temp); } elseif ($quality < 5 && (($dst_w * $quality) < $src_w || ($dst_h * $quality) < $src_h)) { $tmp_w = $dst_w * $quality; $tmp_h = $dst_h * $quality; $temp = imagecreatetruecolor ($tmp_w + 1, $tmp_h + 1); imagecopyresized ($temp, $src_image, 0, 0, $src_x, $src_y, $tmp_w + 1, $tmp_h + 1, $src_w, $src_h); imagecopyresampled ($dst_image, $temp, $dst_x, $dst_y, 0, 0, $dst_w, $dst_h, $tmp_w, $tmp_h); imagedestroy ($temp); } else { imagecopyresampled ($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h); } return true; } /** * @link http://pl.php.net/manual/pl/function.imagecreatefromjpeg.php * function posted by e dot a dot schultz at gmail dot com * * @static * @access public * @param string $filename * @return boolean */ public static function setMemoryForImage($imageWidth, $imageHeight, $imageBits, $imageChannels) { $MB = 1048576; // number of bytes in 1M $K64 = 65536; // number of bytes in 64K $TWEAKFACTOR = 2.4; // Or whatever works for you $memoryNeeded = round( ( $imageWidth * $imageHeight * $imageBits * $imageChannels / 8 + $K64 ) * $TWEAKFACTOR ) + 3*$MB; //ini_get('memory_limit') only works if compiled with "--enable-memory-limit" also //Default memory limit is 8MB so well stick with that. //To find out what yours is, view your php.ini file. $memoryLimit = CKFinder_Connector_Utils_Misc::returnBytes(@ini_get('memory_limit'))/$MB; // There are no memory limits, nothing to do if ($memoryLimit == -1) { return true; } if (!$memoryLimit) { $memoryLimit = 8; } $memoryLimitMB = $memoryLimit * $MB; if (function_exists('memory_get_usage')) { if (memory_get_usage() + $memoryNeeded > $memoryLimitMB) { $newLimit = $memoryLimit + ceil( ( memory_get_usage() + $memoryNeeded - $memoryLimitMB ) / $MB ); if (@ini_set( 'memory_limit', $newLimit . 'M' ) === false) { return false; } } } else { if ($memoryNeeded + 3*$MB > $memoryLimitMB) { $newLimit = $memoryLimit + ceil(( 3*$MB + $memoryNeeded - $memoryLimitMB ) / $MB ); if (false === @ini_set( 'memory_limit', $newLimit . 'M' )) { return false; } } } return true; } /** * convert shorthand php.ini notation into bytes, much like how the PHP source does it * @link http://pl.php.net/manual/en/function.ini-get.php * * @static * @access public * @param string $val * @return int */ public static function returnBytes($val) { $val = trim($val); if (!$val) { return 0; } $last = strtolower($val[strlen($val)-1]); switch($last) { // The 'G' modifier is available since PHP 5.1.0 case 'g': $val *= 1024; case 'm': $val *= 1024; case 'k': $val *= 1024; } return $val; } /** * Checks if a value exists in an array (case insensitive) * * @static * @access public * @param string $needle * @param array $haystack * @return boolean */ public static function inArrayCaseInsensitive($needle, $haystack) { if (!$haystack || !is_array($haystack)) { return false; } $lcase = array(); foreach ($haystack as $key => $val) { $lcase[$key] = strtolower($val); } return in_array($needle, $lcase); } /** * UTF-8 compatible version of basename() * * @static * @access public * @param string $file * @return string */ public static function mbBasename($file) { $explode = explode('/', str_replace("\\", "/", $file)); return end($explode); } /** * Checks whether the string is valid UTF8 * @static * @access public * @param string $string * @return boolean */ public static function isValidUTF8($string) { if (strlen($string) == 0) { return true; } return (preg_match('/^./us', $string) == 1); } /** * Source: http://pl.php.net/imagecreate * (optimized for speed and memory usage, but yet not very efficient) * * @static * @access public * @param string $filename * @return resource */ public static function imageCreateFromBmp($filename) { //20 seconds seems to be a reasonable value to not kill a server and process images up to 1680x1050 @set_time_limit(20); if (false === ($f1 = fopen($filename, "rb"))) { return false; } $FILE = unpack("vfile_type/Vfile_size/Vreserved/Vbitmap_offset", fread($f1, 14)); if ($FILE['file_type'] != 19778) { return false; } $BMP = unpack('Vheader_size/Vwidth/Vheight/vplanes/vbits_per_pixel'. '/Vcompression/Vsize_bitmap/Vhoriz_resolution'. '/Vvert_resolution/Vcolors_used/Vcolors_important', fread($f1, 40)); $BMP['colors'] = pow(2,$BMP['bits_per_pixel']); if ($BMP['size_bitmap'] == 0) { $BMP['size_bitmap'] = $FILE['file_size'] - $FILE['bitmap_offset']; } $BMP['bytes_per_pixel'] = $BMP['bits_per_pixel']/8; $BMP['bytes_per_pixel2'] = ceil($BMP['bytes_per_pixel']); $BMP['decal'] = ($BMP['width']*$BMP['bytes_per_pixel']/4); $BMP['decal'] -= floor($BMP['width']*$BMP['bytes_per_pixel']/4); $BMP['decal'] = 4-(4*$BMP['decal']); if ($BMP['decal'] == 4) { $BMP['decal'] = 0; } $PALETTE = array(); if ($BMP['colors'] < 16777216) { $PALETTE = unpack('V'.$BMP['colors'], fread($f1, $BMP['colors']*4)); } //2048x1536px@24bit don't even try to process larger files as it will probably fail if ($BMP['size_bitmap'] > 3 * 2048 * 1536) { return false; } $IMG = fread($f1, $BMP['size_bitmap']); fclose($f1); $VIDE = chr(0); $res = imagecreatetruecolor($BMP['width'],$BMP['height']); $P = 0; $Y = $BMP['height']-1; $line_length = $BMP['bytes_per_pixel']*$BMP['width']; if ($BMP['bits_per_pixel'] == 24) { while ($Y >= 0) { $X=0; $temp = unpack( "C*", substr($IMG, $P, $line_length)); while ($X < $BMP['width']) { $offset = $X*3; imagesetpixel($res, $X++, $Y, ($temp[$offset+3] << 16) + ($temp[$offset+2] << 8) + $temp[$offset+1]); } $Y--; $P += $line_length + $BMP['decal']; } } elseif ($BMP['bits_per_pixel'] == 8) { while ($Y >= 0) { $X=0; $temp = unpack( "C*", substr($IMG, $P, $line_length)); while ($X < $BMP['width']) { imagesetpixel($res, $X++, $Y, $PALETTE[$temp[$X] +1]); } $Y--; $P += $line_length + $BMP['decal']; } } elseif ($BMP['bits_per_pixel'] == 4) { while ($Y >= 0) { $X=0; $i = 1; $low = true; $temp = unpack( "C*", substr($IMG, $P, $line_length)); while ($X < $BMP['width']) { if ($low) { $index = $temp[$i] >> 4; } else { $index = $temp[$i++] & 0x0F; } $low = !$low; imagesetpixel($res, $X++, $Y, $PALETTE[$index +1]); } $Y--; $P += $line_length + $BMP['decal']; } } elseif ($BMP['bits_per_pixel'] == 1) { $COLOR = unpack("n",$VIDE.substr($IMG,floor($P),1)); if (($P*8)%8 == 0) $COLOR[1] = $COLOR[1] >>7; elseif (($P*8)%8 == 1) $COLOR[1] = ($COLOR[1] & 0x40)>>6; elseif (($P*8)%8 == 2) $COLOR[1] = ($COLOR[1] & 0x20)>>5; elseif (($P*8)%8 == 3) $COLOR[1] = ($COLOR[1] & 0x10)>>4; elseif (($P*8)%8 == 4) $COLOR[1] = ($COLOR[1] & 0x8)>>3; elseif (($P*8)%8 == 5) $COLOR[1] = ($COLOR[1] & 0x4)>>2; elseif (($P*8)%8 == 6) $COLOR[1] = ($COLOR[1] & 0x2)>>1; elseif (($P*8)%8 == 7) $COLOR[1] = ($COLOR[1] & 0x1); $COLOR[1] = $PALETTE[$COLOR[1]+1]; } else { return false; } return $res; } }
nkhanhquoc/waterfactory
source/backend/web/js/ckfinder/core/connector/php/php5/Utils/Misc.php
PHP
mit
12,722
angular .module('menuDemoPosition', ['ngMaterial']) .config(function($mdIconProvider) { $mdIconProvider .iconSet("call", 'img/icons/sets/communication-icons.svg', 24) .iconSet("social", 'img/icons/sets/social-icons.svg', 24); }) .controller('PositionDemoCtrl', function DemoCtrl($mdDialog) { var originatorEv; this.openMenu = function($mdOpenMenu, ev) { originatorEv = ev; $mdOpenMenu(ev); }; this.announceClick = function(index) { $mdDialog.show( $mdDialog.alert() .title('You clicked!') .textContent('You clicked the menu item at index ' + index) .ok('Nice') .targetEvent(originatorEv) ); originatorEv = null; }; });
jelbourn/material
src/components/menu/demoMenuPositionModes/script.js
JavaScript
mit
747
/// <reference path="fourslash.ts" /> // @BaselineFile: getEmitOutputTsxFile_React.baseline // @declaration: true // @sourceMap: true // @jsx: react // @Filename: inputFile1.ts // @emitThisFile: true ////// regular ts file //// var t: number = 5; //// class Bar { //// x : string; //// y : number //// } //// /*1*/ // @Filename: inputFile2.tsx // @emitThisFile: true //// declare var React: any; //// var y = "my div"; //// var x = <div name= {y} /> //// /*2*/ goTo.marker("1"); verify.numberOfErrorsInCurrentFile(0); goTo.marker("2"); verify.numberOfErrorsInCurrentFile(0); verify.baselineGetEmitOutput();
plantain-00/TypeScript
tests/cases/fourslash/getEmitOutputTsxFile_React.ts
TypeScript
apache-2.0
646
/* * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.jps.model.serialization; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.util.io.FileUtil; import com.intellij.testFramework.PlatformTestUtil; import org.jdom.Element; import org.jetbrains.jps.model.JpsDummyElement; import org.jetbrains.jps.model.JpsEncodingConfigurationService; import org.jetbrains.jps.model.JpsEncodingProjectConfiguration; import org.jetbrains.jps.model.artifact.JpsArtifactService; import org.jetbrains.jps.model.java.*; import org.jetbrains.jps.model.library.JpsLibrary; import org.jetbrains.jps.model.library.JpsOrderRootType; import org.jetbrains.jps.model.library.sdk.JpsSdkReference; import org.jetbrains.jps.model.module.*; import org.jetbrains.jps.model.serialization.library.JpsLibraryTableSerializer; import org.jetbrains.jps.model.serialization.module.JpsModuleRootModelSerializer; import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.List; /** * @author nik */ public class JpsProjectSerializationTest extends JpsSerializationTestCase { public static final String SAMPLE_PROJECT_PATH = "/jps/model-serialization/testData/sampleProject"; public void testLoadProject() { loadProject(SAMPLE_PROJECT_PATH); String baseDirPath = getTestDataFileAbsolutePath(SAMPLE_PROJECT_PATH); assertTrue(FileUtil.filesEqual(new File(baseDirPath), JpsModelSerializationDataService.getBaseDirectory(myProject))); assertEquals("sampleProjectName", myProject.getName()); List<JpsModule> modules = myProject.getModules(); assertEquals(3, modules.size()); JpsModule main = modules.get(0); assertEquals("main", main.getName()); JpsModule util = modules.get(1); assertEquals("util", util.getName()); JpsModule xxx = modules.get(2); assertEquals("xxx", xxx.getName()); assertTrue(FileUtil.filesEqual(new File(baseDirPath, "util"), JpsModelSerializationDataService.getBaseDirectory(util))); List<JpsLibrary> libraries = myProject.getLibraryCollection().getLibraries(); assertEquals(3, libraries.size()); List<JpsDependencyElement> dependencies = util.getDependenciesList().getDependencies(); assertEquals(4, dependencies.size()); JpsSdkDependency sdkDependency = assertInstanceOf(dependencies.get(0), JpsSdkDependency.class); assertSame(JpsJavaSdkType.INSTANCE, sdkDependency.getSdkType()); JpsSdkReference<?> reference = sdkDependency.getSdkReference(); assertNotNull(reference); assertEquals("1.5", reference.getSdkName()); assertInstanceOf(dependencies.get(1), JpsModuleSourceDependency.class); assertInstanceOf(dependencies.get(2), JpsLibraryDependency.class); assertInstanceOf(dependencies.get(3), JpsLibraryDependency.class); JpsSdkDependency inheritedSdkDependency = assertInstanceOf(main.getDependenciesList().getDependencies().get(0), JpsSdkDependency.class); JpsSdkReference<?> projectSdkReference = inheritedSdkDependency.getSdkReference(); assertNotNull(projectSdkReference); assertEquals("1.6", projectSdkReference.getSdkName()); assertEquals(getUrl("xxx/output"), JpsJavaExtensionService.getInstance().getOutputUrl(xxx, true)); assertEquals(getUrl("xxx/output"), JpsJavaExtensionService.getInstance().getOutputUrl(xxx, false)); } public void testFileBasedProjectNameAndBaseDir() { String relativePath = "/jps/model-serialization/testData/run-configurations/run-configurations.ipr"; String absolutePath = getTestDataFileAbsolutePath(relativePath); loadProject(relativePath); assertEquals("run-configurations", myProject.getName()); assertTrue(FileUtil.filesEqual(new File(absolutePath).getParentFile(), JpsModelSerializationDataService.getBaseDirectory(myProject))); } public void testDirectoryBasedProjectName() { loadProject("/jps/model-serialization/testData/run-configurations-dir"); assertEquals("run-configurations-dir", myProject.getName()); } public void testImlUnderDotIdea() { loadProject("/jps/model-serialization/testData/imlUnderDotIdea"); JpsModule module = assertOneElement(myProject.getModules()); JpsModuleSourceRoot root = assertOneElement(module.getSourceRoots()); assertEquals(getUrl("src"), root.getUrl()); } public void testProjectSdkWithoutType() { loadProject("/jps/model-serialization/testData/projectSdkWithoutType/projectSdkWithoutType.ipr"); JpsSdkReference<JpsDummyElement> reference = myProject.getSdkReferencesTable().getSdkReference(JpsJavaSdkType.INSTANCE); assertNotNull(reference); assertEquals("1.6", reference.getSdkName()); } public void testInvalidDependencyScope() { loadProject("/jps/model-serialization/testData/invalidDependencyScope/invalidDependencyScope.ipr"); JpsModule module = assertOneElement(myProject.getModules()); List<JpsDependencyElement> dependencies = module.getDependenciesList().getDependencies(); assertEquals(3, dependencies.size()); JpsJavaDependencyExtension extension = JpsJavaExtensionService.getInstance().getDependencyExtension(dependencies.get(2)); assertNotNull(extension); assertEquals(JpsJavaDependencyScope.COMPILE, extension.getScope()); } public void testDuplicatedModuleLibrary() { loadProject("/jps/model-serialization/testData/duplicatedModuleLibrary/duplicatedModuleLibrary.ipr"); JpsModule module = assertOneElement(myProject.getModules()); List<JpsDependencyElement> dependencies = module.getDependenciesList().getDependencies(); assertEquals(4, dependencies.size()); JpsLibrary lib1 = assertInstanceOf(dependencies.get(2), JpsLibraryDependency.class).getLibrary(); assertNotNull(lib1); assertSameElements(lib1.getRootUrls(JpsOrderRootType.COMPILED), getUrl("data/lib1")); JpsLibrary lib2 = assertInstanceOf(dependencies.get(3), JpsLibraryDependency.class).getLibrary(); assertNotSame(lib1, lib2); assertNotNull(lib2); assertSameElements(lib2.getRootUrls(JpsOrderRootType.COMPILED), getUrl("data/lib2")); } public void testDotIdeaUnderDotIdea() { loadProject("/jps/model-serialization/testData/matryoshka/.idea"); JpsJavaProjectExtension extension = JpsJavaExtensionService.getInstance().getProjectExtension(myProject); assertNotNull(extension); assertEquals(getUrl("out"), extension.getOutputUrl()); } public void testLoadEncoding() { loadProject(SAMPLE_PROJECT_PATH); JpsEncodingConfigurationService service = JpsEncodingConfigurationService.getInstance(); assertEquals("UTF-8", service.getProjectEncoding(myModel)); JpsEncodingProjectConfiguration configuration = service.getEncodingConfiguration(myProject); assertNotNull(configuration); assertEquals("UTF-8", configuration.getProjectEncoding()); assertEquals("windows-1251", configuration.getEncoding(new File(getAbsolutePath("util")))); assertEquals("windows-1251", configuration.getEncoding(new File(getAbsolutePath("util/foo/bar/file.txt")))); assertEquals("UTF-8", configuration.getEncoding(new File(getAbsolutePath("other")))); } public void testResourceRoots() { String projectPath = "/jps/model-serialization/testData/resourceRoots/"; loadProject(projectPath + "resourceRoots.ipr"); JpsModule module = assertOneElement(myProject.getModules()); List<JpsModuleSourceRoot> roots = module.getSourceRoots(); assertSame(JavaSourceRootType.SOURCE, roots.get(0).getRootType()); checkResourceRoot(roots.get(1), false, ""); checkResourceRoot(roots.get(2), true, ""); checkResourceRoot(roots.get(3), true, "foo"); doTestSaveModule(module, projectPath + "resourceRoots.iml"); } private static void checkResourceRoot(JpsModuleSourceRoot root, boolean forGenerated, String relativeOutput) { assertSame(JavaResourceRootType.RESOURCE, root.getRootType()); JavaResourceRootProperties properties = root.getProperties(JavaResourceRootType.RESOURCE); assertNotNull(properties); assertEquals(forGenerated, properties.isForGeneratedSources()); assertEquals(relativeOutput, properties.getRelativeOutputPath()); } public void testSaveProject() { loadProject(SAMPLE_PROJECT_PATH); List<JpsModule> modules = myProject.getModules(); doTestSaveModule(modules.get(0), SAMPLE_PROJECT_PATH + "/main.iml"); doTestSaveModule(modules.get(1), SAMPLE_PROJECT_PATH + "/util/util.iml"); //tod[nik] remember that test output root wasn't specified and doesn't save it to avoid unnecessary modifications of iml files //doTestSaveModule(modules.get(2), "xxx/xxx.iml"); File[] libs = getFileInSampleProject(".idea/libraries").listFiles(); assertNotNull(libs); for (File libFile : libs) { String libName = FileUtil.getNameWithoutExtension(libFile); JpsLibrary library = myProject.getLibraryCollection().findLibrary(libName); assertNotNull(libName, library); doTestSaveLibrary(libFile, libName, library); } } private void doTestSaveLibrary(File libFile, String libName, JpsLibrary library) { try { Element actual = new Element("library"); JpsLibraryTableSerializer.saveLibrary(library, actual, libName); JpsMacroExpander macroExpander = JpsProjectLoader.createProjectMacroExpander(Collections.<String, String>emptyMap(), getFileInSampleProject("")); Element rootElement = JpsLoaderBase.loadRootElement(libFile, macroExpander); Element expected = rootElement.getChild("library"); PlatformTestUtil.assertElementsEqual(expected, actual); } catch (IOException e) { throw new RuntimeException(e); } } private void doTestSaveModule(JpsModule module, final String moduleFilePath) { try { Element actual = JDomSerializationUtil.createComponentElement("NewModuleRootManager"); JpsModuleRootModelSerializer.saveRootModel(module, actual); File imlFile = new File(getTestDataFileAbsolutePath(moduleFilePath)); Element rootElement = loadModuleRootTag(imlFile); Element expected = JDomSerializationUtil.findComponent(rootElement, "NewModuleRootManager"); PlatformTestUtil.assertElementsEqual(expected, actual); } catch (Exception e) { throw new RuntimeException(e); } } public File getFileInSampleProject(String relativePath) { return new File(getTestDataFileAbsolutePath(SAMPLE_PROJECT_PATH + "/" + relativePath)); } public void testLoadIdeaProject() { long start = System.currentTimeMillis(); loadProjectByAbsolutePath(PathManager.getHomePath()); assertTrue(myProject.getModules().size() > 0); System.out.println("JpsProjectSerializationTest: " + myProject.getModules().size() + " modules, " + myProject.getLibraryCollection().getLibraries().size() + " libraries and " + JpsArtifactService.getInstance().getArtifacts(myProject).size() + " artifacts loaded in " + (System.currentTimeMillis() - start) + "ms"); } }
akosyakov/intellij-community
jps/model-serialization/testSrc/org/jetbrains/jps/model/serialization/JpsProjectSerializationTest.java
Java
apache-2.0
11,503
// // basic_socket.hpp // ~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef ASIO_BASIC_SOCKET_HPP #define ASIO_BASIC_SOCKET_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/async_result.hpp" #include "asio/basic_io_object.hpp" #include "asio/detail/handler_type_requirements.hpp" #include "asio/detail/throw_error.hpp" #include "asio/detail/type_traits.hpp" #include "asio/error.hpp" #include "asio/socket_base.hpp" #include "asio/detail/push_options.hpp" namespace asio { /// Provides socket functionality. /** * The basic_socket class template provides functionality that is common to both * stream-oriented and datagram-oriented sockets. * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Unsafe. */ template <typename Protocol, typename SocketService> class basic_socket : public basic_io_object<SocketService>, public socket_base { public: /// (Deprecated: Use native_handle_type.) The native representation of a /// socket. typedef typename SocketService::native_handle_type native_type; /// The native representation of a socket. typedef typename SocketService::native_handle_type native_handle_type; /// The protocol type. typedef Protocol protocol_type; /// The endpoint type. typedef typename Protocol::endpoint endpoint_type; /// A basic_socket is always the lowest layer. typedef basic_socket<Protocol, SocketService> lowest_layer_type; /// Construct a basic_socket without opening it. /** * This constructor creates a socket without opening it. * * @param io_service The io_service object that the socket will use to * dispatch handlers for any asynchronous operations performed on the socket. */ explicit basic_socket(asio::io_service& io_service) : basic_io_object<SocketService>(io_service) { } /// Construct and open a basic_socket. /** * This constructor creates and opens a socket. * * @param io_service The io_service object that the socket will use to * dispatch handlers for any asynchronous operations performed on the socket. * * @param protocol An object specifying protocol parameters to be used. * * @throws asio::system_error Thrown on failure. */ basic_socket(asio::io_service& io_service, const protocol_type& protocol) : basic_io_object<SocketService>(io_service) { asio::error_code ec; this->get_service().open(this->get_implementation(), protocol, ec); asio::detail::throw_error(ec, "open"); } /// Construct a basic_socket, opening it and binding it to the given local /// endpoint. /** * This constructor creates a socket and automatically opens it bound to the * specified endpoint on the local machine. The protocol used is the protocol * associated with the given endpoint. * * @param io_service The io_service object that the socket will use to * dispatch handlers for any asynchronous operations performed on the socket. * * @param endpoint An endpoint on the local machine to which the socket will * be bound. * * @throws asio::system_error Thrown on failure. */ basic_socket(asio::io_service& io_service, const endpoint_type& endpoint) : basic_io_object<SocketService>(io_service) { asio::error_code ec; const protocol_type protocol = endpoint.protocol(); this->get_service().open(this->get_implementation(), protocol, ec); asio::detail::throw_error(ec, "open"); this->get_service().bind(this->get_implementation(), endpoint, ec); asio::detail::throw_error(ec, "bind"); } /// Construct a basic_socket on an existing native socket. /** * This constructor creates a socket object to hold an existing native socket. * * @param io_service The io_service object that the socket will use to * dispatch handlers for any asynchronous operations performed on the socket. * * @param protocol An object specifying protocol parameters to be used. * * @param native_socket A native socket. * * @throws asio::system_error Thrown on failure. */ basic_socket(asio::io_service& io_service, const protocol_type& protocol, const native_handle_type& native_socket) : basic_io_object<SocketService>(io_service) { asio::error_code ec; this->get_service().assign(this->get_implementation(), protocol, native_socket, ec); asio::detail::throw_error(ec, "assign"); } #if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) /// Move-construct a basic_socket from another. /** * This constructor moves a socket from one object to another. * * @param other The other basic_socket object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_socket(io_service&) constructor. */ basic_socket(basic_socket&& other) : basic_io_object<SocketService>( ASIO_MOVE_CAST(basic_socket)(other)) { } /// Move-assign a basic_socket from another. /** * This assignment operator moves a socket from one object to another. * * @param other The other basic_socket object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_socket(io_service&) constructor. */ basic_socket& operator=(basic_socket&& other) { basic_io_object<SocketService>::operator=( ASIO_MOVE_CAST(basic_socket)(other)); return *this; } // All sockets have access to each other's implementations. template <typename Protocol1, typename SocketService1> friend class basic_socket; /// Move-construct a basic_socket from a socket of another protocol type. /** * This constructor moves a socket from one object to another. * * @param other The other basic_socket object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_socket(io_service&) constructor. */ template <typename Protocol1, typename SocketService1> basic_socket(basic_socket<Protocol1, SocketService1>&& other, typename enable_if<is_convertible<Protocol1, Protocol>::value>::type* = 0) : basic_io_object<SocketService>(other.get_io_service()) { this->get_service().template converting_move_construct<Protocol1>( this->get_implementation(), other.get_implementation()); } /// Move-assign a basic_socket from a socket of another protocol type. /** * This assignment operator moves a socket from one object to another. * * @param other The other basic_socket object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_socket(io_service&) constructor. */ template <typename Protocol1, typename SocketService1> typename enable_if<is_convertible<Protocol1, Protocol>::value, basic_socket>::type& operator=( basic_socket<Protocol1, SocketService1>&& other) { basic_socket tmp(ASIO_MOVE_CAST2(basic_socket< Protocol1, SocketService1>)(other)); basic_io_object<SocketService>::operator=( ASIO_MOVE_CAST(basic_socket)(tmp)); return *this; } #endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) /// Get a reference to the lowest layer. /** * This function returns a reference to the lowest layer in a stack of * layers. Since a basic_socket cannot contain any further layers, it simply * returns a reference to itself. * * @return A reference to the lowest layer in the stack of layers. Ownership * is not transferred to the caller. */ lowest_layer_type& lowest_layer() { return *this; } /// Get a const reference to the lowest layer. /** * This function returns a const reference to the lowest layer in a stack of * layers. Since a basic_socket cannot contain any further layers, it simply * returns a reference to itself. * * @return A const reference to the lowest layer in the stack of layers. * Ownership is not transferred to the caller. */ const lowest_layer_type& lowest_layer() const { return *this; } /// Open the socket using the specified protocol. /** * This function opens the socket so that it will use the specified protocol. * * @param protocol An object specifying protocol parameters to be used. * * @throws asio::system_error Thrown on failure. * * @par Example * @code * asio::ip::tcp::socket socket(io_service); * socket.open(asio::ip::tcp::v4()); * @endcode */ void open(const protocol_type& protocol = protocol_type()) { asio::error_code ec; this->get_service().open(this->get_implementation(), protocol, ec); asio::detail::throw_error(ec, "open"); } /// Open the socket using the specified protocol. /** * This function opens the socket so that it will use the specified protocol. * * @param protocol An object specifying which protocol is to be used. * * @param ec Set to indicate what error occurred, if any. * * @par Example * @code * asio::ip::tcp::socket socket(io_service); * asio::error_code ec; * socket.open(asio::ip::tcp::v4(), ec); * if (ec) * { * // An error occurred. * } * @endcode */ asio::error_code open(const protocol_type& protocol, asio::error_code& ec) { return this->get_service().open(this->get_implementation(), protocol, ec); } /// Assign an existing native socket to the socket. /* * This function opens the socket to hold an existing native socket. * * @param protocol An object specifying which protocol is to be used. * * @param native_socket A native socket. * * @throws asio::system_error Thrown on failure. */ void assign(const protocol_type& protocol, const native_handle_type& native_socket) { asio::error_code ec; this->get_service().assign(this->get_implementation(), protocol, native_socket, ec); asio::detail::throw_error(ec, "assign"); } /// Assign an existing native socket to the socket. /* * This function opens the socket to hold an existing native socket. * * @param protocol An object specifying which protocol is to be used. * * @param native_socket A native socket. * * @param ec Set to indicate what error occurred, if any. */ asio::error_code assign(const protocol_type& protocol, const native_handle_type& native_socket, asio::error_code& ec) { return this->get_service().assign(this->get_implementation(), protocol, native_socket, ec); } /// Determine whether the socket is open. bool is_open() const { return this->get_service().is_open(this->get_implementation()); } /// Close the socket. /** * This function is used to close the socket. Any asynchronous send, receive * or connect operations will be cancelled immediately, and will complete * with the asio::error::operation_aborted error. * * @throws asio::system_error Thrown on failure. Note that, even if * the function indicates an error, the underlying descriptor is closed. * * @note For portable behaviour with respect to graceful closure of a * connected socket, call shutdown() before closing the socket. */ void close() { asio::error_code ec; this->get_service().close(this->get_implementation(), ec); asio::detail::throw_error(ec, "close"); } /// Close the socket. /** * This function is used to close the socket. Any asynchronous send, receive * or connect operations will be cancelled immediately, and will complete * with the asio::error::operation_aborted error. * * @param ec Set to indicate what error occurred, if any. Note that, even if * the function indicates an error, the underlying descriptor is closed. * * @par Example * @code * asio::ip::tcp::socket socket(io_service); * ... * asio::error_code ec; * socket.close(ec); * if (ec) * { * // An error occurred. * } * @endcode * * @note For portable behaviour with respect to graceful closure of a * connected socket, call shutdown() before closing the socket. */ asio::error_code close(asio::error_code& ec) { return this->get_service().close(this->get_implementation(), ec); } /// (Deprecated: Use native_handle().) Get the native socket representation. /** * This function may be used to obtain the underlying representation of the * socket. This is intended to allow access to native socket functionality * that is not otherwise provided. */ native_type native() { return this->get_service().native_handle(this->get_implementation()); } /// Get the native socket representation. /** * This function may be used to obtain the underlying representation of the * socket. This is intended to allow access to native socket functionality * that is not otherwise provided. */ native_handle_type native_handle() { return this->get_service().native_handle(this->get_implementation()); } /// Cancel all asynchronous operations associated with the socket. /** * This function causes all outstanding asynchronous connect, send and receive * operations to finish immediately, and the handlers for cancelled operations * will be passed the asio::error::operation_aborted error. * * @throws asio::system_error Thrown on failure. * * @note Calls to cancel() will always fail with * asio::error::operation_not_supported when run on Windows XP, Windows * Server 2003, and earlier versions of Windows, unless * ASIO_ENABLE_CANCELIO is defined. However, the CancelIo function has * two issues that should be considered before enabling its use: * * @li It will only cancel asynchronous operations that were initiated in the * current thread. * * @li It can appear to complete without error, but the request to cancel the * unfinished operations may be silently ignored by the operating system. * Whether it works or not seems to depend on the drivers that are installed. * * For portable cancellation, consider using one of the following * alternatives: * * @li Disable asio's I/O completion port backend by defining * ASIO_DISABLE_IOCP. * * @li Use the close() function to simultaneously cancel the outstanding * operations and close the socket. * * When running on Windows Vista, Windows Server 2008, and later, the * CancelIoEx function is always used. This function does not have the * problems described above. */ #if defined(ASIO_MSVC) && (ASIO_MSVC >= 1400) \ && (!defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0600) \ && !defined(ASIO_ENABLE_CANCELIO) __declspec(deprecated("By default, this function always fails with " "operation_not_supported when used on Windows XP, Windows Server 2003, " "or earlier. Consult documentation for details.")) #endif void cancel() { asio::error_code ec; this->get_service().cancel(this->get_implementation(), ec); asio::detail::throw_error(ec, "cancel"); } /// Cancel all asynchronous operations associated with the socket. /** * This function causes all outstanding asynchronous connect, send and receive * operations to finish immediately, and the handlers for cancelled operations * will be passed the asio::error::operation_aborted error. * * @param ec Set to indicate what error occurred, if any. * * @note Calls to cancel() will always fail with * asio::error::operation_not_supported when run on Windows XP, Windows * Server 2003, and earlier versions of Windows, unless * ASIO_ENABLE_CANCELIO is defined. However, the CancelIo function has * two issues that should be considered before enabling its use: * * @li It will only cancel asynchronous operations that were initiated in the * current thread. * * @li It can appear to complete without error, but the request to cancel the * unfinished operations may be silently ignored by the operating system. * Whether it works or not seems to depend on the drivers that are installed. * * For portable cancellation, consider using one of the following * alternatives: * * @li Disable asio's I/O completion port backend by defining * ASIO_DISABLE_IOCP. * * @li Use the close() function to simultaneously cancel the outstanding * operations and close the socket. * * When running on Windows Vista, Windows Server 2008, and later, the * CancelIoEx function is always used. This function does not have the * problems described above. */ #if defined(ASIO_MSVC) && (ASIO_MSVC >= 1400) \ && (!defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0600) \ && !defined(ASIO_ENABLE_CANCELIO) __declspec(deprecated("By default, this function always fails with " "operation_not_supported when used on Windows XP, Windows Server 2003, " "or earlier. Consult documentation for details.")) #endif asio::error_code cancel(asio::error_code& ec) { return this->get_service().cancel(this->get_implementation(), ec); } /// Determine whether the socket is at the out-of-band data mark. /** * This function is used to check whether the socket input is currently * positioned at the out-of-band data mark. * * @return A bool indicating whether the socket is at the out-of-band data * mark. * * @throws asio::system_error Thrown on failure. */ bool at_mark() const { asio::error_code ec; bool b = this->get_service().at_mark(this->get_implementation(), ec); asio::detail::throw_error(ec, "at_mark"); return b; } /// Determine whether the socket is at the out-of-band data mark. /** * This function is used to check whether the socket input is currently * positioned at the out-of-band data mark. * * @param ec Set to indicate what error occurred, if any. * * @return A bool indicating whether the socket is at the out-of-band data * mark. */ bool at_mark(asio::error_code& ec) const { return this->get_service().at_mark(this->get_implementation(), ec); } /// Determine the number of bytes available for reading. /** * This function is used to determine the number of bytes that may be read * without blocking. * * @return The number of bytes that may be read without blocking, or 0 if an * error occurs. * * @throws asio::system_error Thrown on failure. */ std::size_t available() const { asio::error_code ec; std::size_t s = this->get_service().available( this->get_implementation(), ec); asio::detail::throw_error(ec, "available"); return s; } /// Determine the number of bytes available for reading. /** * This function is used to determine the number of bytes that may be read * without blocking. * * @param ec Set to indicate what error occurred, if any. * * @return The number of bytes that may be read without blocking, or 0 if an * error occurs. */ std::size_t available(asio::error_code& ec) const { return this->get_service().available(this->get_implementation(), ec); } /// Bind the socket to the given local endpoint. /** * This function binds the socket to the specified endpoint on the local * machine. * * @param endpoint An endpoint on the local machine to which the socket will * be bound. * * @throws asio::system_error Thrown on failure. * * @par Example * @code * asio::ip::tcp::socket socket(io_service); * socket.open(asio::ip::tcp::v4()); * socket.bind(asio::ip::tcp::endpoint( * asio::ip::tcp::v4(), 12345)); * @endcode */ void bind(const endpoint_type& endpoint) { asio::error_code ec; this->get_service().bind(this->get_implementation(), endpoint, ec); asio::detail::throw_error(ec, "bind"); } /// Bind the socket to the given local endpoint. /** * This function binds the socket to the specified endpoint on the local * machine. * * @param endpoint An endpoint on the local machine to which the socket will * be bound. * * @param ec Set to indicate what error occurred, if any. * * @par Example * @code * asio::ip::tcp::socket socket(io_service); * socket.open(asio::ip::tcp::v4()); * asio::error_code ec; * socket.bind(asio::ip::tcp::endpoint( * asio::ip::tcp::v4(), 12345), ec); * if (ec) * { * // An error occurred. * } * @endcode */ asio::error_code bind(const endpoint_type& endpoint, asio::error_code& ec) { return this->get_service().bind(this->get_implementation(), endpoint, ec); } /// Connect the socket to the specified endpoint. /** * This function is used to connect a socket to the specified remote endpoint. * The function call will block until the connection is successfully made or * an error occurs. * * The socket is automatically opened if it is not already open. If the * connect fails, and the socket was automatically opened, the socket is * not returned to the closed state. * * @param peer_endpoint The remote endpoint to which the socket will be * connected. * * @throws asio::system_error Thrown on failure. * * @par Example * @code * asio::ip::tcp::socket socket(io_service); * asio::ip::tcp::endpoint endpoint( * asio::ip::address::from_string("1.2.3.4"), 12345); * socket.connect(endpoint); * @endcode */ void connect(const endpoint_type& peer_endpoint) { asio::error_code ec; if (!is_open()) { this->get_service().open(this->get_implementation(), peer_endpoint.protocol(), ec); asio::detail::throw_error(ec, "connect"); } this->get_service().connect(this->get_implementation(), peer_endpoint, ec); asio::detail::throw_error(ec, "connect"); } /// Connect the socket to the specified endpoint. /** * This function is used to connect a socket to the specified remote endpoint. * The function call will block until the connection is successfully made or * an error occurs. * * The socket is automatically opened if it is not already open. If the * connect fails, and the socket was automatically opened, the socket is * not returned to the closed state. * * @param peer_endpoint The remote endpoint to which the socket will be * connected. * * @param ec Set to indicate what error occurred, if any. * * @par Example * @code * asio::ip::tcp::socket socket(io_service); * asio::ip::tcp::endpoint endpoint( * asio::ip::address::from_string("1.2.3.4"), 12345); * asio::error_code ec; * socket.connect(endpoint, ec); * if (ec) * { * // An error occurred. * } * @endcode */ asio::error_code connect(const endpoint_type& peer_endpoint, asio::error_code& ec) { if (!is_open()) { if (this->get_service().open(this->get_implementation(), peer_endpoint.protocol(), ec)) { return ec; } } return this->get_service().connect( this->get_implementation(), peer_endpoint, ec); } /// Start an asynchronous connect. /** * This function is used to asynchronously connect a socket to the specified * remote endpoint. The function call always returns immediately. * * The socket is automatically opened if it is not already open. If the * connect fails, and the socket was automatically opened, the socket is * not returned to the closed state. * * @param peer_endpoint The remote endpoint to which the socket will be * connected. Copies will be made of the endpoint object as required. * * @param handler The handler to be called when the connection operation * completes. Copies will be made of the handler as required. The function * signature of the handler must be: * @code void handler( * const asio::error_code& error // Result of operation * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the handler will not be invoked from within this function. Invocation * of the handler will be performed in a manner equivalent to using * asio::io_service::post(). * * @par Example * @code * void connect_handler(const asio::error_code& error) * { * if (!error) * { * // Connect succeeded. * } * } * * ... * * asio::ip::tcp::socket socket(io_service); * asio::ip::tcp::endpoint endpoint( * asio::ip::address::from_string("1.2.3.4"), 12345); * socket.async_connect(endpoint, connect_handler); * @endcode */ template <typename ConnectHandler> ASIO_INITFN_RESULT_TYPE(ConnectHandler, void (asio::error_code)) async_connect(const endpoint_type& peer_endpoint, ASIO_MOVE_ARG(ConnectHandler) handler) { // If you get an error on the following line it means that your handler does // not meet the documented type requirements for a ConnectHandler. ASIO_CONNECT_HANDLER_CHECK(ConnectHandler, handler) type_check; if (!is_open()) { asio::error_code ec; const protocol_type protocol = peer_endpoint.protocol(); if (this->get_service().open(this->get_implementation(), protocol, ec)) { detail::async_result_init< ConnectHandler, void (asio::error_code)> init( ASIO_MOVE_CAST(ConnectHandler)(handler)); this->get_io_service().post( asio::detail::bind_handler( ASIO_MOVE_CAST(ASIO_HANDLER_TYPE( ConnectHandler, void (asio::error_code)))( init.handler), ec)); return init.result.get(); } } return this->get_service().async_connect(this->get_implementation(), peer_endpoint, ASIO_MOVE_CAST(ConnectHandler)(handler)); } /// Set an option on the socket. /** * This function is used to set an option on the socket. * * @param option The new option value to be set on the socket. * * @throws asio::system_error Thrown on failure. * * @sa SettableSocketOption @n * asio::socket_base::broadcast @n * asio::socket_base::do_not_route @n * asio::socket_base::keep_alive @n * asio::socket_base::linger @n * asio::socket_base::receive_buffer_size @n * asio::socket_base::receive_low_watermark @n * asio::socket_base::reuse_address @n * asio::socket_base::send_buffer_size @n * asio::socket_base::send_low_watermark @n * asio::ip::multicast::join_group @n * asio::ip::multicast::leave_group @n * asio::ip::multicast::enable_loopback @n * asio::ip::multicast::outbound_interface @n * asio::ip::multicast::hops @n * asio::ip::tcp::no_delay * * @par Example * Setting the IPPROTO_TCP/TCP_NODELAY option: * @code * asio::ip::tcp::socket socket(io_service); * ... * asio::ip::tcp::no_delay option(true); * socket.set_option(option); * @endcode */ template <typename SettableSocketOption> void set_option(const SettableSocketOption& option) { asio::error_code ec; this->get_service().set_option(this->get_implementation(), option, ec); asio::detail::throw_error(ec, "set_option"); } /// Set an option on the socket. /** * This function is used to set an option on the socket. * * @param option The new option value to be set on the socket. * * @param ec Set to indicate what error occurred, if any. * * @sa SettableSocketOption @n * asio::socket_base::broadcast @n * asio::socket_base::do_not_route @n * asio::socket_base::keep_alive @n * asio::socket_base::linger @n * asio::socket_base::receive_buffer_size @n * asio::socket_base::receive_low_watermark @n * asio::socket_base::reuse_address @n * asio::socket_base::send_buffer_size @n * asio::socket_base::send_low_watermark @n * asio::ip::multicast::join_group @n * asio::ip::multicast::leave_group @n * asio::ip::multicast::enable_loopback @n * asio::ip::multicast::outbound_interface @n * asio::ip::multicast::hops @n * asio::ip::tcp::no_delay * * @par Example * Setting the IPPROTO_TCP/TCP_NODELAY option: * @code * asio::ip::tcp::socket socket(io_service); * ... * asio::ip::tcp::no_delay option(true); * asio::error_code ec; * socket.set_option(option, ec); * if (ec) * { * // An error occurred. * } * @endcode */ template <typename SettableSocketOption> asio::error_code set_option(const SettableSocketOption& option, asio::error_code& ec) { return this->get_service().set_option( this->get_implementation(), option, ec); } /// Get an option from the socket. /** * This function is used to get the current value of an option on the socket. * * @param option The option value to be obtained from the socket. * * @throws asio::system_error Thrown on failure. * * @sa GettableSocketOption @n * asio::socket_base::broadcast @n * asio::socket_base::do_not_route @n * asio::socket_base::keep_alive @n * asio::socket_base::linger @n * asio::socket_base::receive_buffer_size @n * asio::socket_base::receive_low_watermark @n * asio::socket_base::reuse_address @n * asio::socket_base::send_buffer_size @n * asio::socket_base::send_low_watermark @n * asio::ip::multicast::join_group @n * asio::ip::multicast::leave_group @n * asio::ip::multicast::enable_loopback @n * asio::ip::multicast::outbound_interface @n * asio::ip::multicast::hops @n * asio::ip::tcp::no_delay * * @par Example * Getting the value of the SOL_SOCKET/SO_KEEPALIVE option: * @code * asio::ip::tcp::socket socket(io_service); * ... * asio::ip::tcp::socket::keep_alive option; * socket.get_option(option); * bool is_set = option.value(); * @endcode */ template <typename GettableSocketOption> void get_option(GettableSocketOption& option) const { asio::error_code ec; this->get_service().get_option(this->get_implementation(), option, ec); asio::detail::throw_error(ec, "get_option"); } /// Get an option from the socket. /** * This function is used to get the current value of an option on the socket. * * @param option The option value to be obtained from the socket. * * @param ec Set to indicate what error occurred, if any. * * @sa GettableSocketOption @n * asio::socket_base::broadcast @n * asio::socket_base::do_not_route @n * asio::socket_base::keep_alive @n * asio::socket_base::linger @n * asio::socket_base::receive_buffer_size @n * asio::socket_base::receive_low_watermark @n * asio::socket_base::reuse_address @n * asio::socket_base::send_buffer_size @n * asio::socket_base::send_low_watermark @n * asio::ip::multicast::join_group @n * asio::ip::multicast::leave_group @n * asio::ip::multicast::enable_loopback @n * asio::ip::multicast::outbound_interface @n * asio::ip::multicast::hops @n * asio::ip::tcp::no_delay * * @par Example * Getting the value of the SOL_SOCKET/SO_KEEPALIVE option: * @code * asio::ip::tcp::socket socket(io_service); * ... * asio::ip::tcp::socket::keep_alive option; * asio::error_code ec; * socket.get_option(option, ec); * if (ec) * { * // An error occurred. * } * bool is_set = option.value(); * @endcode */ template <typename GettableSocketOption> asio::error_code get_option(GettableSocketOption& option, asio::error_code& ec) const { return this->get_service().get_option( this->get_implementation(), option, ec); } /// Perform an IO control command on the socket. /** * This function is used to execute an IO control command on the socket. * * @param command The IO control command to be performed on the socket. * * @throws asio::system_error Thrown on failure. * * @sa IoControlCommand @n * asio::socket_base::bytes_readable @n * asio::socket_base::non_blocking_io * * @par Example * Getting the number of bytes ready to read: * @code * asio::ip::tcp::socket socket(io_service); * ... * asio::ip::tcp::socket::bytes_readable command; * socket.io_control(command); * std::size_t bytes_readable = command.get(); * @endcode */ template <typename IoControlCommand> void io_control(IoControlCommand& command) { asio::error_code ec; this->get_service().io_control(this->get_implementation(), command, ec); asio::detail::throw_error(ec, "io_control"); } /// Perform an IO control command on the socket. /** * This function is used to execute an IO control command on the socket. * * @param command The IO control command to be performed on the socket. * * @param ec Set to indicate what error occurred, if any. * * @sa IoControlCommand @n * asio::socket_base::bytes_readable @n * asio::socket_base::non_blocking_io * * @par Example * Getting the number of bytes ready to read: * @code * asio::ip::tcp::socket socket(io_service); * ... * asio::ip::tcp::socket::bytes_readable command; * asio::error_code ec; * socket.io_control(command, ec); * if (ec) * { * // An error occurred. * } * std::size_t bytes_readable = command.get(); * @endcode */ template <typename IoControlCommand> asio::error_code io_control(IoControlCommand& command, asio::error_code& ec) { return this->get_service().io_control( this->get_implementation(), command, ec); } /// Gets the non-blocking mode of the socket. /** * @returns @c true if the socket's synchronous operations will fail with * asio::error::would_block if they are unable to perform the requested * operation immediately. If @c false, synchronous operations will block * until complete. * * @note The non-blocking mode has no effect on the behaviour of asynchronous * operations. Asynchronous operations will never fail with the error * asio::error::would_block. */ bool non_blocking() const { return this->get_service().non_blocking(this->get_implementation()); } /// Sets the non-blocking mode of the socket. /** * @param mode If @c true, the socket's synchronous operations will fail with * asio::error::would_block if they are unable to perform the requested * operation immediately. If @c false, synchronous operations will block * until complete. * * @throws asio::system_error Thrown on failure. * * @note The non-blocking mode has no effect on the behaviour of asynchronous * operations. Asynchronous operations will never fail with the error * asio::error::would_block. */ void non_blocking(bool mode) { asio::error_code ec; this->get_service().non_blocking(this->get_implementation(), mode, ec); asio::detail::throw_error(ec, "non_blocking"); } /// Sets the non-blocking mode of the socket. /** * @param mode If @c true, the socket's synchronous operations will fail with * asio::error::would_block if they are unable to perform the requested * operation immediately. If @c false, synchronous operations will block * until complete. * * @param ec Set to indicate what error occurred, if any. * * @note The non-blocking mode has no effect on the behaviour of asynchronous * operations. Asynchronous operations will never fail with the error * asio::error::would_block. */ asio::error_code non_blocking( bool mode, asio::error_code& ec) { return this->get_service().non_blocking( this->get_implementation(), mode, ec); } /// Gets the non-blocking mode of the native socket implementation. /** * This function is used to retrieve the non-blocking mode of the underlying * native socket. This mode has no effect on the behaviour of the socket * object's synchronous operations. * * @returns @c true if the underlying socket is in non-blocking mode and * direct system calls may fail with asio::error::would_block (or the * equivalent system error). * * @note The current non-blocking mode is cached by the socket object. * Consequently, the return value may be incorrect if the non-blocking mode * was set directly on the native socket. * * @par Example * This function is intended to allow the encapsulation of arbitrary * non-blocking system calls as asynchronous operations, in a way that is * transparent to the user of the socket object. The following example * illustrates how Linux's @c sendfile system call might be encapsulated: * @code template <typename Handler> * struct sendfile_op * { * tcp::socket& sock_; * int fd_; * Handler handler_; * off_t offset_; * std::size_t total_bytes_transferred_; * * // Function call operator meeting WriteHandler requirements. * // Used as the handler for the async_write_some operation. * void operator()(asio::error_code ec, std::size_t) * { * // Put the underlying socket into non-blocking mode. * if (!ec) * if (!sock_.native_non_blocking()) * sock_.native_non_blocking(true, ec); * * if (!ec) * { * for (;;) * { * // Try the system call. * errno = 0; * int n = ::sendfile(sock_.native_handle(), fd_, &offset_, 65536); * ec = asio::error_code(n < 0 ? errno : 0, * asio::error::get_system_category()); * total_bytes_transferred_ += ec ? 0 : n; * * // Retry operation immediately if interrupted by signal. * if (ec == asio::error::interrupted) * continue; * * // Check if we need to run the operation again. * if (ec == asio::error::would_block * || ec == asio::error::try_again) * { * // We have to wait for the socket to become ready again. * sock_.async_write_some(asio::null_buffers(), *this); * return; * } * * if (ec || n == 0) * { * // An error occurred, or we have reached the end of the file. * // Either way we must exit the loop so we can call the handler. * break; * } * * // Loop around to try calling sendfile again. * } * } * * // Pass result back to user's handler. * handler_(ec, total_bytes_transferred_); * } * }; * * template <typename Handler> * void async_sendfile(tcp::socket& sock, int fd, Handler h) * { * sendfile_op<Handler> op = { sock, fd, h, 0, 0 }; * sock.async_write_some(asio::null_buffers(), op); * } @endcode */ bool native_non_blocking() const { return this->get_service().native_non_blocking(this->get_implementation()); } /// Sets the non-blocking mode of the native socket implementation. /** * This function is used to modify the non-blocking mode of the underlying * native socket. It has no effect on the behaviour of the socket object's * synchronous operations. * * @param mode If @c true, the underlying socket is put into non-blocking * mode and direct system calls may fail with asio::error::would_block * (or the equivalent system error). * * @throws asio::system_error Thrown on failure. If the @c mode is * @c false, but the current value of @c non_blocking() is @c true, this * function fails with asio::error::invalid_argument, as the * combination does not make sense. * * @par Example * This function is intended to allow the encapsulation of arbitrary * non-blocking system calls as asynchronous operations, in a way that is * transparent to the user of the socket object. The following example * illustrates how Linux's @c sendfile system call might be encapsulated: * @code template <typename Handler> * struct sendfile_op * { * tcp::socket& sock_; * int fd_; * Handler handler_; * off_t offset_; * std::size_t total_bytes_transferred_; * * // Function call operator meeting WriteHandler requirements. * // Used as the handler for the async_write_some operation. * void operator()(asio::error_code ec, std::size_t) * { * // Put the underlying socket into non-blocking mode. * if (!ec) * if (!sock_.native_non_blocking()) * sock_.native_non_blocking(true, ec); * * if (!ec) * { * for (;;) * { * // Try the system call. * errno = 0; * int n = ::sendfile(sock_.native_handle(), fd_, &offset_, 65536); * ec = asio::error_code(n < 0 ? errno : 0, * asio::error::get_system_category()); * total_bytes_transferred_ += ec ? 0 : n; * * // Retry operation immediately if interrupted by signal. * if (ec == asio::error::interrupted) * continue; * * // Check if we need to run the operation again. * if (ec == asio::error::would_block * || ec == asio::error::try_again) * { * // We have to wait for the socket to become ready again. * sock_.async_write_some(asio::null_buffers(), *this); * return; * } * * if (ec || n == 0) * { * // An error occurred, or we have reached the end of the file. * // Either way we must exit the loop so we can call the handler. * break; * } * * // Loop around to try calling sendfile again. * } * } * * // Pass result back to user's handler. * handler_(ec, total_bytes_transferred_); * } * }; * * template <typename Handler> * void async_sendfile(tcp::socket& sock, int fd, Handler h) * { * sendfile_op<Handler> op = { sock, fd, h, 0, 0 }; * sock.async_write_some(asio::null_buffers(), op); * } @endcode */ void native_non_blocking(bool mode) { asio::error_code ec; this->get_service().native_non_blocking( this->get_implementation(), mode, ec); asio::detail::throw_error(ec, "native_non_blocking"); } /// Sets the non-blocking mode of the native socket implementation. /** * This function is used to modify the non-blocking mode of the underlying * native socket. It has no effect on the behaviour of the socket object's * synchronous operations. * * @param mode If @c true, the underlying socket is put into non-blocking * mode and direct system calls may fail with asio::error::would_block * (or the equivalent system error). * * @param ec Set to indicate what error occurred, if any. If the @c mode is * @c false, but the current value of @c non_blocking() is @c true, this * function fails with asio::error::invalid_argument, as the * combination does not make sense. * * @par Example * This function is intended to allow the encapsulation of arbitrary * non-blocking system calls as asynchronous operations, in a way that is * transparent to the user of the socket object. The following example * illustrates how Linux's @c sendfile system call might be encapsulated: * @code template <typename Handler> * struct sendfile_op * { * tcp::socket& sock_; * int fd_; * Handler handler_; * off_t offset_; * std::size_t total_bytes_transferred_; * * // Function call operator meeting WriteHandler requirements. * // Used as the handler for the async_write_some operation. * void operator()(asio::error_code ec, std::size_t) * { * // Put the underlying socket into non-blocking mode. * if (!ec) * if (!sock_.native_non_blocking()) * sock_.native_non_blocking(true, ec); * * if (!ec) * { * for (;;) * { * // Try the system call. * errno = 0; * int n = ::sendfile(sock_.native_handle(), fd_, &offset_, 65536); * ec = asio::error_code(n < 0 ? errno : 0, * asio::error::get_system_category()); * total_bytes_transferred_ += ec ? 0 : n; * * // Retry operation immediately if interrupted by signal. * if (ec == asio::error::interrupted) * continue; * * // Check if we need to run the operation again. * if (ec == asio::error::would_block * || ec == asio::error::try_again) * { * // We have to wait for the socket to become ready again. * sock_.async_write_some(asio::null_buffers(), *this); * return; * } * * if (ec || n == 0) * { * // An error occurred, or we have reached the end of the file. * // Either way we must exit the loop so we can call the handler. * break; * } * * // Loop around to try calling sendfile again. * } * } * * // Pass result back to user's handler. * handler_(ec, total_bytes_transferred_); * } * }; * * template <typename Handler> * void async_sendfile(tcp::socket& sock, int fd, Handler h) * { * sendfile_op<Handler> op = { sock, fd, h, 0, 0 }; * sock.async_write_some(asio::null_buffers(), op); * } @endcode */ asio::error_code native_non_blocking( bool mode, asio::error_code& ec) { return this->get_service().native_non_blocking( this->get_implementation(), mode, ec); } /// Get the local endpoint of the socket. /** * This function is used to obtain the locally bound endpoint of the socket. * * @returns An object that represents the local endpoint of the socket. * * @throws asio::system_error Thrown on failure. * * @par Example * @code * asio::ip::tcp::socket socket(io_service); * ... * asio::ip::tcp::endpoint endpoint = socket.local_endpoint(); * @endcode */ endpoint_type local_endpoint() const { asio::error_code ec; endpoint_type ep = this->get_service().local_endpoint( this->get_implementation(), ec); asio::detail::throw_error(ec, "local_endpoint"); return ep; } /// Get the local endpoint of the socket. /** * This function is used to obtain the locally bound endpoint of the socket. * * @param ec Set to indicate what error occurred, if any. * * @returns An object that represents the local endpoint of the socket. * Returns a default-constructed endpoint object if an error occurred. * * @par Example * @code * asio::ip::tcp::socket socket(io_service); * ... * asio::error_code ec; * asio::ip::tcp::endpoint endpoint = socket.local_endpoint(ec); * if (ec) * { * // An error occurred. * } * @endcode */ endpoint_type local_endpoint(asio::error_code& ec) const { return this->get_service().local_endpoint(this->get_implementation(), ec); } /// Get the remote endpoint of the socket. /** * This function is used to obtain the remote endpoint of the socket. * * @returns An object that represents the remote endpoint of the socket. * * @throws asio::system_error Thrown on failure. * * @par Example * @code * asio::ip::tcp::socket socket(io_service); * ... * asio::ip::tcp::endpoint endpoint = socket.remote_endpoint(); * @endcode */ endpoint_type remote_endpoint() const { asio::error_code ec; endpoint_type ep = this->get_service().remote_endpoint( this->get_implementation(), ec); asio::detail::throw_error(ec, "remote_endpoint"); return ep; } /// Get the remote endpoint of the socket. /** * This function is used to obtain the remote endpoint of the socket. * * @param ec Set to indicate what error occurred, if any. * * @returns An object that represents the remote endpoint of the socket. * Returns a default-constructed endpoint object if an error occurred. * * @par Example * @code * asio::ip::tcp::socket socket(io_service); * ... * asio::error_code ec; * asio::ip::tcp::endpoint endpoint = socket.remote_endpoint(ec); * if (ec) * { * // An error occurred. * } * @endcode */ endpoint_type remote_endpoint(asio::error_code& ec) const { return this->get_service().remote_endpoint(this->get_implementation(), ec); } /// Disable sends or receives on the socket. /** * This function is used to disable send operations, receive operations, or * both. * * @param what Determines what types of operation will no longer be allowed. * * @throws asio::system_error Thrown on failure. * * @par Example * Shutting down the send side of the socket: * @code * asio::ip::tcp::socket socket(io_service); * ... * socket.shutdown(asio::ip::tcp::socket::shutdown_send); * @endcode */ void shutdown(shutdown_type what) { asio::error_code ec; this->get_service().shutdown(this->get_implementation(), what, ec); asio::detail::throw_error(ec, "shutdown"); } /// Disable sends or receives on the socket. /** * This function is used to disable send operations, receive operations, or * both. * * @param what Determines what types of operation will no longer be allowed. * * @param ec Set to indicate what error occurred, if any. * * @par Example * Shutting down the send side of the socket: * @code * asio::ip::tcp::socket socket(io_service); * ... * asio::error_code ec; * socket.shutdown(asio::ip::tcp::socket::shutdown_send, ec); * if (ec) * { * // An error occurred. * } * @endcode */ asio::error_code shutdown(shutdown_type what, asio::error_code& ec) { return this->get_service().shutdown(this->get_implementation(), what, ec); } protected: /// Protected destructor to prevent deletion through this type. ~basic_socket() { } }; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_BASIC_SOCKET_HPP
julien3/vertxbuspp
vertxbuspp/asio/include/asio/basic_socket.hpp
C++
apache-2.0
50,601
require "spec_helper" describe Mongoid::Changeable do describe "#attribute_change" do context "when the attribute has changed from the persisted value" do context "when using the setter" do let(:person) do Person.new(title: "Grand Poobah").tap(&:move_changes) end before do person.title = "Captain Obvious" end it "returns an array of the old value and new value" do expect(person.send(:attribute_change, "title")).to eq( [ "Grand Poobah", "Captain Obvious" ] ) end it "allows access via (attribute)_change" do expect(person.title_change).to eq( [ "Grand Poobah", "Captain Obvious" ] ) end context "when the field is aliased" do let(:person) do Person.new(test: "Aliased 1").tap(&:move_changes) end before do person.test = "Aliased 2" end it "returns an array of the old value and new value" do expect(person.send(:attribute_change, "test")).to eq( [ "Aliased 1", "Aliased 2" ] ) end it "allows access via (attribute)_change" do expect(person.test_change).to eq( [ "Aliased 1", "Aliased 2" ] ) end end end context "when using [] methods" do let(:person) do Person.new(title: "Grand Poobah").tap(&:move_changes) end before do person[:title] = "Captain Obvious" end it "returns an array of the old value and new value" do expect(person.send(:attribute_change, "title")).to eq( [ "Grand Poobah", "Captain Obvious" ] ) end it "allows access via (attribute)_change" do expect(person.title_change).to eq( [ "Grand Poobah", "Captain Obvious" ] ) end end end context "when the attribute has changed from the default value" do context "when using the setter" do let(:person) do Person.new(pets: true) end it "returns an array of nil and new value" do expect(person.send(:attribute_change, "pets")).to eq([ nil, true ]) end it "allows access via (attribute)_change" do expect(person.pets_change).to eq([ nil, true ]) end end context "when using [] methods" do context "when the field is defined" do let(:person) do Person.new end before do person[:pets] = true end it "returns an array of nil and new value" do expect(person.send(:attribute_change, "pets")).to eq([ nil, true ]) end it "allows access via (attribute)_change" do expect(person.pets_change).to eq([ nil, true ]) end end context "when the field is not defined" do let(:person) do Person.new end before do person[:t] = "test" end it "returns an array of nil and new value" do expect(person.send(:attribute_change, "t")).to eq([ nil, "test" ]) end end end end context "when the attribute changes multiple times" do let(:person) do Person.new(title: "Grand Poobah").tap(&:move_changes) end before do person.title = "Captain Obvious" person.title = "Dark Helmet" end it "returns an array of the original value and new value" do expect(person.send(:attribute_change, "title")).to eq( [ "Grand Poobah", "Dark Helmet" ] ) end it "allows access via (attribute)_change" do expect(person.title_change).to eq( [ "Grand Poobah", "Dark Helmet" ] ) end end context "when the attribute is modified in place" do context "when the attribute is an array" do let(:person) do Person.new(aliases: [ "Grand Poobah" ]).tap(&:move_changes) end before do person.aliases[0] = "Dark Helmet" end it "returns an array of the original value and new value" do expect(person.send(:attribute_change, "aliases")).to eq( [[ "Grand Poobah" ], [ "Dark Helmet" ]] ) end it "allows access via (attribute)_change" do expect(person.aliases_change).to eq( [[ "Grand Poobah" ], [ "Dark Helmet" ]] ) end context "when the attribute changes multiple times" do before do person.aliases << "Colonel Sanders" end it "returns an array of the original value and new value" do expect(person.send(:attribute_change, "aliases")).to eq( [[ "Grand Poobah" ], [ "Dark Helmet", "Colonel Sanders" ]] ) end end end context "when the attribute is a hash" do let(:person) do Person.new(map: { location: "Home" }).tap(&:move_changes) end before do person.map[:location] = "Work" end it "returns an array of the original value and new value" do expect(person.send(:attribute_change, "map")).to eq( [{ location: "Home" }, { location: "Work" }] ) end it "allows access via (attribute)_change" do expect(person.map_change).to eq( [{ location: "Home" }, { location: "Work" }] ) end context "when the attribute changes multiple times" do before do person.map[:lat] = 20.0 end it "returns an array of the original value and new value" do expect(person.send(:attribute_change, "map")).to eq( [{ location: "Home" }, { location: "Work", lat: 20.0 }] ) end end context "when the values are arrays" do let(:map) do { "stack1" => [ 1, 2, 3, 4 ], "stack2" => [ 1, 2, 3, 4 ], "stack3" => [ 1, 2, 3, 4 ] } end before do person.map = map person.move_changes end context "when reordering the arrays inline" do before do person.map["stack1"].reverse! end it "flags the attribute as changed" do expect(person.send(:attribute_change, "map")).to eq( [ { "stack1" => [ 1, 2, 3, 4 ], "stack2" => [ 1, 2, 3, 4 ], "stack3" => [ 1, 2, 3, 4 ] }, { "stack1" => [ 4, 3, 2, 1 ], "stack2" => [ 1, 2, 3, 4 ], "stack3" => [ 1, 2, 3, 4 ] }, ] ) end end end end end context "when the attribute has not changed from the persisted value" do let(:person) do Person.new(title: nil) end it "returns nil" do expect(person.send(:attribute_change, "title")).to be_nil end end context "when the attribute has not changed from the default value" do context "when the attribute differs from the persisted value" do let(:person) do Person.new end it "returns the change" do expect(person.send(:attribute_change, "pets")).to eq([ nil, false ]) end end context "when the attribute does not differ from the persisted value" do let(:person) do Person.instantiate("pets" => false) end it "returns nil" do expect(person.send(:attribute_change, "pets")).to be_nil end end end context "when the attribute has been set with the same value" do let(:person) do Person.new(title: "Grand Poobah").tap(&:move_changes) end before do person.title = "Grand Poobah" end it "returns an empty array" do expect(person.send(:attribute_change, "title")).to be_nil end end context "when the attribute is removed" do let(:person) do Person.new(title: "Grand Poobah").tap(&:move_changes) end before do person.remove_attribute(:title) end it "returns an empty array" do expect(person.send(:attribute_change, "title")).to eq( [ "Grand Poobah", nil ] ) end end end describe "#attribute_changed?" do context "when the attribute has changed from the persisted value" do let(:person) do Person.new(title: "Grand Poobah") end before do person.title = "Captain Obvious" end it "returns true" do expect(person.send(:attribute_changed?, "title")).to be true end it "allows access via (attribute)_changed?" do expect(person.title_changed?).to be true end context "when the field is aliased" do let(:person) do Person.new(test: "Aliased 1") end before do person.test = "Aliased 2" end it "returns true" do expect(person.send(:attribute_changed?, "test")).to be true end it "allows access via (attribute)_changed?" do expect(person.test_changed?).to be true end end end context "when the attribute has changed from the default value" do let(:person) do Person.new end before do person.pets = true end it "returns true" do expect(person.send(:attribute_changed?, "pets")).to be true end it "allows access via (attribute)_changed?" do expect(person.pets_changed?).to be true end end context "when the attribute has not changed the persisted value" do let!(:person) do Person.new(title: "Grand Poobah").tap(&:move_changes) end it "returns false" do expect(person.send(:attribute_changed?, "title")).to be false end end context "when the attribute has not changed from the default value" do context "when the attribute is not enumerable" do context "when the attribute differs from the persisted value" do let!(:person) do Person.new end it "returns true" do expect(person.send(:attribute_changed?, "pets")).to be true end end context "when the attribute does not differ from the persisted value" do let!(:person) do Person.instantiate("pets" => false) end it "returns false" do expect(person.send(:attribute_changed?, "pets")).to be false end end end context "when the attribute is an array" do let!(:person) do Person.new(aliases: [ "Bond" ]) end context "when the array is only accessed" do before do person.move_changes person.aliases end it "returns false" do expect(person).to_not be_aliases_changed end end end context "when the attribute is a hash" do let!(:person) do Person.new(map: { key: "value" }) end context "when the hash is only accessed" do before do person.move_changes person.map end it "returns false" do expect(person).to_not be_map_changed end end end end end describe "#attribute_changed_from_default?" do context "when the attribute differs from the default value" do let(:person) do Person.new(age: 33) end it "returns true" do expect(person).to be_age_changed_from_default end end context "when the attribute is the same as the default" do let(:person) do Person.new end it "returns false" do expect(person).to_not be_age_changed_from_default end end end describe "#attribute_was" do context "when the attribute has changed from the persisted value" do let(:person) do Person.new(title: "Grand Poobah").tap(&:move_changes) end before do person.title = "Captain Obvious" end it "returns the old value" do expect(person.send(:attribute_was, "title")).to eq("Grand Poobah") end it "allows access via (attribute)_was" do expect(person.title_was).to eq("Grand Poobah") end context "when the field is aliased" do let(:person) do Person.new(test: "Aliased 1").tap(&:move_changes) end before do person.test = "Aliased 2" end it "returns the old value" do expect(person.send(:attribute_was, "test")).to eq("Aliased 1") end it "allows access via (attribute)_was" do expect(person.test_was).to eq("Aliased 1") end end end context "when the attribute has not changed from the persisted value" do let!(:person) do Person.new(title: "Grand Poobah").tap(&:move_changes) end it "returns the original value" do expect(person.send(:attribute_was, "title")).to eq("Grand Poobah") end end end describe "#attribute_will_change!" do let(:aliases) do [ "007" ] end let(:person) do Person.new(aliases: aliases, test: "Aliased 1") end before do person.changed_attributes.clear end context "when the value has not changed" do before do person.aliases_will_change! end let(:changes) do person.changes end it "does not return the value in the changes" do expect(changes).to be_empty end it "is not flagged as changed" do expect(person).to_not be_changed end end context "when the value has changed" do before do person.aliases_will_change! person.aliases << "008" end let(:changes) do person.changes end it "returns the value in the changes" do expect(changes).to eq({ "aliases" => [[ "007" ], [ "007", "008" ]] }) end end context "when the value is duplicable" do context "when the attribute has not been cloned" do before do person.aliases_will_change! end let(:changed) do person.changed_attributes end it "clones the value" do expect(changed["aliases"]).to_not equal(aliases) end it "puts the old value in the changes" do expect(changed["aliases"]).to eq(aliases) end end context "when the attribute has been flagged" do before do person.changed_attributes["aliases"] = aliases expect(aliases).to receive(:clone).never person.aliases_will_change! end let(:changed) do person.changed_attributes end it "does not clone the value" do expect(changed["aliases"]).to equal(aliases) end it "retains the first value in the changes" do expect(changed["aliases"]).to eq(aliases) end end end end describe "#changed" do context "when the document has changed" do let(:person) do Person.instantiate(title: "Grand Poobah") end before do person.title = "Captain Obvious" end it "returns an array of changed field names" do expect(person.changed).to include("title") end end context "when the document has not changed" do let(:person) do Person.instantiate({}) end it "does not include non changed fields" do expect(person.changed).to_not include("title") end end context "when the document is embedded" do let(:person) do Person.create end let!(:name) do person.create_name(first_name: "Layne", last_name: "Staley") end context "when changing attributes via []" do before do person.name["a"] = "testing" end it "returns true" do expect(person.name).to be_changed end end end end describe "#changed?" do context "when the document has changed" do let(:person) do Person.new(title: "Grand Poobah") end before do person.title = "Captain Obvious" end it "returns true" do expect(person).to be_changed end end context "when a hash field has been accessed" do context "when the field has not changed" do let(:person) do Person.create(map: { name: "value" }) end before do person.map end it "returns false" do expect(person).to_not be_changed end end context "when the field is changed" do let(:person) do Person.create(map: { name: "value" }) end before do person.map = { name: "another" } end it "returns true" do expect(person).to be_changed end end context "when a dynamic field is changed in place" do let(:person) do Person.create(other_name: { full: {first: 'first', last: 'last'} }) end before do person.other_name[:full][:first] = 'Name' end it "returns true" do expect(person.changes).to_not be_empty expect(person).to be_changed end end end context "when the document has not changed" do let(:acolyte) do Acolyte.instantiate("_id" => BSON::ObjectId.new) end it "returns false" do expect(acolyte).to_not be_changed end end context "when a child has changed" do let(:person) do Person.create end let!(:address) do person.addresses.create(street: "hobrecht") end before do address.number = 10 end it "returns true" do expect(person).to be_changed end end context "when a deeply embedded child has changed" do let(:person) do Person.create end let(:address) do person.addresses.create(street: "hobrecht") end let!(:location) do address.locations.create(name: "home") end before do location.name = "work" end it "returns true" do expect(person).to be_changed end end context "when a child is new" do let(:person) do Person.create end let!(:address) do person.addresses.build(street: "hobrecht") end it "returns true" do expect(person).to be_changed end end context "when a deeply embedded child is new" do let(:person) do Person.create end let(:address) do person.addresses.create(street: "hobrecht") end let!(:location) do address.locations.build(name: "home") end it "returns true" do expect(person).to be_changed end end end describe "#changes" do context "when the document has changed" do let(:person) do Person.instantiate(title: "Grand Poobah") end before do person.title = "Captain Obvious" end it "returns a hash of changes" do expect(person.changes["title"]).to eq( [ nil, "Captain Obvious" ] ) end it "returns a hash with indifferent access" do expect(person.changes["title"]).to eq( [ nil, "Captain Obvious" ] ) end end context "when the document has not changed" do let(:acolyte) do Acolyte.instantiate("_id" => BSON::ObjectId.new) end it "returns an empty hash" do expect(acolyte.changes).to be_empty end end end describe "#setters" do context "when the document has changed" do let(:person) do Person.new(aliases: [ "007" ]).tap do |p| p.new_record = false p.move_changes end end context "when an array field has changed" do context "when the array has values removed" do before do person.aliases.delete_one("007") end let!(:setters) do person.setters end it "contains array changes in the setters" do expect(setters).to eq({ "aliases" => [] }) end end context "when the array has values added" do before do person.aliases << "008" end let!(:setters) do person.setters end it "contains array changes in the setters" do expect(setters).to eq({ "aliases" => [ "007", "008" ] }) end end context "when the array has changed completely" do before do person.aliases << "008" person.aliases.delete_one("007") end let!(:setters) do person.setters end it "does not contain array changes in the setters" do expect(setters).to eq({ "aliases" => [ "008" ]}) end end end context "when the document is a root document" do let(:person) do Person.instantiate(title: "Grand Poobah") end before do person.title = "Captain Obvious" end it "returns a hash of field names and new values" do expect(person.setters["title"]).to eq("Captain Obvious") end end context "when the document is embedded" do let(:person) do Person.instantiate(title: "Grand Poobah") end let(:address) do Address.instantiate(street: "Oxford St") end before do person.addresses << address person.instance_variable_set(:@new_record, false) address.instance_variable_set(:@new_record, false) address.street = "Bond St" end it "returns a hash of field names and new values" do expect(address.setters).to eq( { "addresses.0.street" => "Bond St" } ) end context "when the document is embedded multiple levels" do let(:location) do Location.new(name: "Home") end before do location.instance_variable_set(:@new_record, false) address.locations << location location.name = "Work" end it "returns the proper hash with locations" do expect(location.setters).to eq( { "addresses.0.locations.0.name" => "Work" } ) end end end end context "when the document has not changed" do let(:acolyte) do Acolyte.instantiate("_id" => BSON::ObjectId.new) end it "returns an empty hash" do expect(acolyte.setters).to be_empty end end end describe "#previous_changes" do let(:person) do Person.new(title: "Grand Poobah") end before do person.title = "Captain Obvious" end context "when the document has been saved" do before do person.save! end it "returns the changes before the save" do expect(person.previous_changes["title"]).to eq( [ nil, "Captain Obvious" ] ) end end context "when the document has not been saved" do it "returns an empty hash" do expect(person.previous_changes).to be_empty end end end describe "#move_changes" do let(:person) do Person.new(title: "Sir") end before do person.atomic_pulls["addresses"] = Address.new person.atomic_unsets << Address.new person.delayed_atomic_sets["addresses"] = Address.new person.move_changes end it "clears the atomic pulls" do expect(person.atomic_pulls).to be_empty end it "clears the atomic unsets" do expect(person.atomic_unsets).to be_empty end it "clears the delayed atomic sets" do expect(person.delayed_atomic_sets).to be_empty end it "clears the changed attributes" do expect(person.changed_attributes).to be_empty end end describe "#reset_attribute!" do context "when the attribute has changed" do let(:person) do Person.instantiate(title: "Grand Poobah") end before do person.title = "Captain Obvious" person.send(:reset_attribute!, "title") end it "resets the value to the original" do expect(person.title).to be_nil end it "allows access via reset_(attribute)!" do expect(person.title).to be_nil end it "removes the field from the changes" do expect(person.changed).to_not include("title") end context "when the field is aliased" do let(:person) do Person.instantiate(test: "Aliased 1") end before do person.test = "Aliased 2" person.send(:reset_attribute!, "test") end it "resets the value to the original" do expect(person.test).to be_nil end it "removes the field from the changes" do expect(person.changed).to_not include("test") end end end context "when the attribute has not changed" do let(:person) do Person.instantiate(title: "Grand Poobah") end before do person.send(:reset_attribute!, "title") end it "does nothing" do expect(person.title).to be_nil end end end context "when fields have been defined pre-dirty inclusion" do let(:document) do Dokument.new end it "defines a _change method" do expect(document.updated_at_change).to be_nil end it "defines a _changed? method" do expect(document.updated_at_changed?).to be false end it "defines a _changes method" do expect(document.updated_at_was).to be_nil end end context "when only embedded documents change" do let!(:person) do Person.create end context "when the child is an embeds one" do context "when the child is new" do let!(:name) do person.build_name(first_name: "Gordon", last_name: "Ramsay") end it "flags the parent as changed" do expect(person).to be_changed end end context "when the child is modified" do let!(:name) do person.create_name(first_name: "Gordon", last_name: "Ramsay") end before do name.first_name = "G" end it "flags the parent as changed" do expect(person).to be_changed end end context "when the child is not modified" do let!(:name) do person.create_name(first_name: "Gordon", last_name: "Ramsay") end it "does not flag the parent as changed" do expect(person).to_not be_changed end end end context "when the child is an embeds many" do context "when a child is new" do let!(:address) do person.addresses.build(street: "jakobstr.") end it "flags the parent as changed" do expect(person).to be_changed end end context "when a child is modified" do let!(:address) do person.addresses.create(street: "jakobstr.") end before do address.city = "Berlin" end it "flags the parent as changed" do expect(person).to be_changed end end context "when no child is modified" do let!(:address) do person.addresses.create(street: "skalitzerstr.") end it "does not flag the parent as changed" do expect(person).to_not be_changed end end end end context "when changing a hash of hashes" do let!(:person) do Person.create(map: { "test" => {}}) end before do person.map["test"]["value"] = 10 end it "records the changes" do expect(person.changes).to eq( { "map" => [{ "test" => {}}, { "test" => { "value" => 10 }}]} ) end end context "when modifying a many to many key" do let!(:person) do Person.create end let!(:preference) do Preference.create(name: "dirty") end before do person.update_attributes(preference_ids: [ preference.id ]) end it "records the foreign key dirty changes" do expect(person.previous_changes["preference_ids"]).to eq( [nil, [ preference.id ]] ) end end context "when accessing an array field" do let!(:person) do Person.create end let(:from_db) do Person.find(person.id) end context "when the field is not changed" do before do from_db.preference_ids end it "flags the change" do expect(from_db.changes["preference_ids"]).to eq([ nil, []]) end it "does not include the changes in the setters" do expect(from_db.setters).to be_empty end end end context "when reloading an unchanged document" do let!(:person) do Person.create end let(:from_db) do Person.find(person.id) end before do from_db.reload end it "clears the changed attributes" do expect(from_db.changed_attributes).to be_empty end end context "when fields are getting changed" do let(:person) do Person.create( title: "MC", some_dynamic_field: 'blah' ) end before do person.title = "DJ" person.write_attribute(:ssn, "222-22-2222") person.some_dynamic_field = 'bloop' end it "marks the document as changed" do expect(person).to be_changed end it "marks field changes" do expect(person.changes).to eq({ "title" => [ "MC", "DJ" ], "ssn" => [ nil, "222-22-2222" ], "some_dynamic_field" => [ "blah", "bloop" ] }) end it "marks changed fields" do expect(person.changed).to eq([ "title", "ssn", "some_dynamic_field" ]) end it "marks the field as changed" do expect(person.title_changed?).to be true end it "stores previous field values" do expect(person.title_was).to eq("MC") end it "marks field changes" do expect(person.title_change).to eq([ "MC", "DJ" ]) end it "allows reset of field changes" do person.reset_title! expect(person.title).to eq("MC") expect(person.changed).to eq([ "ssn", "some_dynamic_field" ]) end context "after a save" do before do person.save! end it "clears changes" do expect(person).to_not be_changed end it "stores previous changes" do expect(person.previous_changes["title"]).to eq([ "MC", "DJ" ]) expect(person.previous_changes["ssn"]).to eq([ nil, "222-22-2222" ]) end end context "when the previous value is nil" do before do person.score = 100 person.reset_score! end it "removes the attribute from the document" do expect(person.score).to be_nil end end end context "when accessing dirty attributes in callbacks" do context "when the document is persisted" do let!(:acolyte) do Acolyte.create(name: "callback-test") end before do Acolyte.set_callback(:save, :after, if: :callback_test?) do |doc| doc[:changed_in_callback] = doc.changes.dup end end after do Acolyte._save_callbacks.select do |callback| callback.kind == :after end.each do |callback| Acolyte._save_callbacks.delete(callback) end end it "retains the changes until after all callbacks" do acolyte.update_attribute(:status, "testing") expect(acolyte.changed_in_callback).to eq({ "status" => [ nil, "testing" ] }) end end context "when the document is new" do let!(:acolyte) do Acolyte.new(name: "callback-test") end before do Acolyte.set_callback(:save, :after, if: :callback_test?) do |doc| doc[:changed_in_callback] = doc.changes.dup end end after do Acolyte._save_callbacks.select do |callback| callback.kind == :after end.each do |callback| Acolyte._save_callbacks.delete(callback) end end it "retains the changes until after all callbacks" do acolyte.save expect(acolyte.changed_in_callback["name"]).to eq([ nil, "callback-test" ]) end end end context "when associations are getting changed" do let(:person) do Person.create(addresses: [ Address.new ]) end before do person.addresses = [ Address.new ] end it "does not set the association to nil when hitting the database" do expect(person.setters).to_not eq({ "addresses" => nil }) end end end
brixen/mongoid
spec/mongoid/changeable_spec.rb
Ruby
mit
33,779
/*============================================================================= Copyright (c) 2010 Christopher Schmidt Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #ifndef BOOST_FUSION_INCLUDE_UNFUSED_HPP #define BOOST_FUSION_INCLUDE_UNFUSED_HPP #include <boost/fusion/functional/adapter/unfused.hpp> #endif
beiko-lab/gengis
win32/library3rd/boost_1_47/boost/fusion/include/unfused.hpp
C++
gpl-3.0
520
import { CompileIdentifierMetadata, CompileTokenMetadata } from './compile_metadata'; export interface IdentifierSpec { name: string; moduleUrl: string; runtime: any; } export declare class Identifiers { static ANALYZE_FOR_ENTRY_COMPONENTS: IdentifierSpec; static ElementRef: IdentifierSpec; static NgModuleRef: IdentifierSpec; static ViewContainerRef: IdentifierSpec; static ChangeDetectorRef: IdentifierSpec; static QueryList: IdentifierSpec; static TemplateRef: IdentifierSpec; static CodegenComponentFactoryResolver: IdentifierSpec; static ComponentFactoryResolver: IdentifierSpec; static ComponentFactory: IdentifierSpec; static ComponentRef: IdentifierSpec; static NgModuleFactory: IdentifierSpec; static NgModuleInjector: IdentifierSpec; static RegisterModuleFactoryFn: IdentifierSpec; static Injector: IdentifierSpec; static ViewEncapsulation: IdentifierSpec; static ChangeDetectionStrategy: IdentifierSpec; static SecurityContext: IdentifierSpec; static LOCALE_ID: IdentifierSpec; static TRANSLATIONS_FORMAT: IdentifierSpec; static inlineInterpolate: IdentifierSpec; static interpolate: IdentifierSpec; static EMPTY_ARRAY: IdentifierSpec; static EMPTY_MAP: IdentifierSpec; static Renderer: IdentifierSpec; static viewDef: IdentifierSpec; static elementDef: IdentifierSpec; static anchorDef: IdentifierSpec; static textDef: IdentifierSpec; static directiveDef: IdentifierSpec; static providerDef: IdentifierSpec; static queryDef: IdentifierSpec; static pureArrayDef: IdentifierSpec; static pureObjectDef: IdentifierSpec; static purePipeDef: IdentifierSpec; static pipeDef: IdentifierSpec; static nodeValue: IdentifierSpec; static ngContentDef: IdentifierSpec; static unwrapValue: IdentifierSpec; static createRendererType2: IdentifierSpec; static RendererType2: IdentifierSpec; static ViewDefinition: IdentifierSpec; static createComponentFactory: IdentifierSpec; } export declare function assetUrl(pkg: string, path?: string, type?: string): string; export declare function resolveIdentifier(identifier: IdentifierSpec): any; export declare function createIdentifier(identifier: IdentifierSpec): CompileIdentifierMetadata; export declare function identifierToken(identifier: CompileIdentifierMetadata): CompileTokenMetadata; export declare function createIdentifierToken(identifier: IdentifierSpec): CompileTokenMetadata; export declare function createEnumIdentifier(enumType: IdentifierSpec, name: string): CompileIdentifierMetadata;
DaanKrug/Rocker-Framework
samples/Rocker-Framework-Functional-Show-Case/node_modules/@angular/compiler/src/identifiers.d.ts
TypeScript
gpl-3.0
2,628
/********************************************************************************** * * $Id$ * *********************************************************************************** * * Copyright (c) 2007, 2008 The Sakai Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ package org.sakaiproject.service.gradebook.shared; import java.util.Date; import java.util.Collection; import java.util.List; import java.util.Map; /** * This service is designed for use by external assessment engines. These use * the Gradebook as a passive mirror of their own assignments and scores, * letting Gradebook users see those assignments alongside Gradebook-managed * assignments, and combine them when calculating a course grade. The Gradebook * application itself will not modify externally-managed assignments and scores. * * <b>WARNING</b>: Because the Gradebook project team is not responsible for * defining the external clients' requirements, the Gradebook service does not * attempt to guess at their authorization needs. Our administrative and * external-assessment methods simply follow orders and assume that the caller * has taken the responsibility of "doing the right thing." DO NOT wrap these * methods in an open web service! */ public interface GradebookExternalAssessmentService { /** * @deprecated Replaced by * {@link addExternalAssessment(String, String, String, String, Double, Date, String, Boolean)} */ public void addExternalAssessment(String gradebookUid, String externalId, String externalUrl, String title, double points, Date dueDate, String externalServiceDescription) throws GradebookNotFoundException, ConflictingAssignmentNameException, ConflictingExternalIdException, AssignmentHasIllegalPointsException; /** * Add an externally-managed assessment to a gradebook to be treated as a * read-only assignment. The gradebook application will not modify the * assessment properties or create any scores for the assessment. * Since each assignment in a given gradebook must have a unique name, * conflicts are possible. * * @param gradebookUid * @param externalId * some unique identifier which Samigo uses for the assessment. * The externalId is globally namespaced within the gradebook, so * if other apps decide to put assessments into the gradebook, * they should prefix their externalIds with a well known (and * unique within sakai) string. * @param externalUrl * a link to go to if the instructor or student wants to look at the assessment * in Samigo; if null, no direct link will be provided in the * gradebook, and the user will have to navigate to the assessment * within the other application * @param title * @param points * this is the total amount of points available and must be greater than zero. * it could be null if it's an ungraded item. * @param dueDate * @param externalServiceDescription * @param ungraded * * @param externalServiceDescription * what to display as the source of the assignment (e.g., "from Samigo") * */ public void addExternalAssessment(String gradebookUid, String externalId, String externalUrl, String title, Double points, Date dueDate, String externalServiceDescription, Boolean ungraded) throws GradebookNotFoundException, ConflictingAssignmentNameException, ConflictingExternalIdException, AssignmentHasIllegalPointsException; /** * This method is identical to {@link #addExternalAssessment(String, String, String, String, Double, Date, String, Boolean)} but * allows you to also specify the associated Category for this assignment. If the gradebook is set up for categories and * categoryId is null, assignment category will be unassigned * @param gradebookUid * @param externalId * @param externalUrl * @param title * @param points * @param dueDate * @param externalServiceDescription * @param ungraded * @param categoryId * @throws GradebookNotFoundException * @throws ConflictingAssignmentNameException * @throws ConflictingExternalIdException * @throws AssignmentHasIllegalPointsException * @throws InvalidCategoryException */ public void addExternalAssessment(String gradebookUid, String externalId, String externalUrl, String title, Double points, Date dueDate, String externalServiceDescription, Boolean ungraded, Long categoryId) throws GradebookNotFoundException, ConflictingAssignmentNameException, ConflictingExternalIdException, AssignmentHasIllegalPointsException, InvalidCategoryException; /** * @deprecated Replaced by * {@link updateExternalAssessment(String, String, String, String, Double, Date, Boolean)} */ public void updateExternalAssessment(String gradebookUid, String externalId, String externalUrl, String title, double points, Date dueDate) throws GradebookNotFoundException, AssessmentNotFoundException, ConflictingAssignmentNameException, AssignmentHasIllegalPointsException; /** * Update an external assessment * @param gradebookUid * @param externalId * @param externalUrl * @param title * @param points * @param dueDate * @param ungraded * @throws GradebookNotFoundException * @throws AssessmentNotFoundException * @throws ConflictingAssignmentNameException * @throws AssignmentHasIllegalPointsException */ public void updateExternalAssessment(String gradebookUid, String externalId, String externalUrl, String title, Double points, Date dueDate, Boolean ungraded) throws GradebookNotFoundException, AssessmentNotFoundException, ConflictingAssignmentNameException, AssignmentHasIllegalPointsException; /** * Remove the assessment reference from the gradebook. Although Samigo * doesn't currently delete assessments, an instructor can retract an * assessment to keep it from students. Since such an assessment would * presumably no longer be used to calculate final grades, Samigo should * also remove that assessment from the gradebook. * * @param externalId * the UID of the assessment */ public void removeExternalAssessment(String gradebookUid, String externalId) throws GradebookNotFoundException, AssessmentNotFoundException; /** * Updates an external score for an external assignment in the gradebook. * * @param gradebookUid * The Uid of the gradebook * @param externalId * The external ID of the assignment/assessment * @param studentUid * The unique id of the student * @param points * The number of points earned on this assessment, or null if a score * should be removed */ public void updateExternalAssessmentScore(String gradebookUid, String externalId, String studentUid, String points) throws GradebookNotFoundException, AssessmentNotFoundException; /** * * @param gradebookUid * @param externalId * @param studentUidsToScores * @throws GradebookNotFoundException * @throws AssessmentNotFoundException * * @deprecated Replaced by * {@link updateExternalAssessmentScoresString(String, String, Map<String, String)} */ public void updateExternalAssessmentScores(String gradebookUid, String externalId, Map<String, Double> studentUidsToScores) throws GradebookNotFoundException, AssessmentNotFoundException; /** * Updates a set of external scores for an external assignment in the gradebook. * * @param gradebookUid * The Uid of the gradebook * @param externalId * The external ID of the assignment/assessment * @param studentUidsToScores * A map whose String keys are the unique ID strings of the students and whose * String values are points earned on this assessment or null if the score * should be removed. */ public void updateExternalAssessmentScoresString(String gradebookUid, String externalId, Map<String, String> studentUidsToScores) throws GradebookNotFoundException, AssessmentNotFoundException; /** * Updates an external comment for an external assignment in the gradebook. * * @param gradebookUid * The Uid of the gradebook * @param externalId * The external ID of the assignment/assessment * @param studentUid * The unique id of the student * @param comment * The comment to be added to this grade, or null if a comment * should be removed */ public void updateExternalAssessmentComment(String gradebookUid, String externalId, String studentUid, String comment ) throws GradebookNotFoundException, AssessmentNotFoundException; /** * Updates a set of external comments for an external assignment in the gradebook. * * @param gradebookUid * The Uid of the gradebook * @param externalId * The external ID of the assignment/assessment * @param studentUidsToScores * A map whose String keys are the unique ID strings of the students and whose * String values are comments or null if the comments * should be removed. */ public void updateExternalAssessmentComments(String gradebookUid, String externalId, Map<String, String> studentUidsToComments) throws GradebookNotFoundException, AssessmentNotFoundException; /** * Check to see if an assignment with the given name already exists * in the given gradebook. This will give external assessment systems * a chance to avoid the ConflictingAssignmentNameException. */ public boolean isAssignmentDefined(String gradebookUid, String assignmentTitle) throws GradebookNotFoundException; /** * Check to see if an assignment with the given external id already exists * in the given gradebook. This will give external assessment systems * a chance to avoid the ConflictingExternalIdException. * * @param gradebookUid The gradebook's unique identifier * @param externalId The external assessment's external identifier */ public boolean isExternalAssignmentDefined(String gradebookUid, String externalId) throws GradebookNotFoundException; /** * Check with the appropriate external service if a specific assignment is * available only to groups. * * @param gradebookUid The gradebook's unique identifier * @param externalId The external assessment's external identifier */ public boolean isExternalAssignmentGrouped(String gradebookUid, String externalId) throws GradebookNotFoundException; /** * Check with the appropriate external service if a specific assignment is * available to a specific user (i.e., the user is in an appropriate group). * Note that this method will return true if the assignment exists in the * gradebook and is marked as externally maintained while no provider * recognizes it; this is to maintain a safer default (no change from the * 2.8 release) for tools that have not implemented a provider. * * @param gradebookUid The gradebook's unique identifier * @param externalId The external assessment's external identifier * @param userId The user ID to check */ public boolean isExternalAssignmentVisible(String gradebookUid, String externalId, String userId) throws GradebookNotFoundException; /** * Retrieve all assignments for a gradebook that are marked as externally * maintained and are visible to the current user. Assignments may be included * with a null providerAppKey, indicating that the gradebook references the * assignment, but no provider claims responsibility for it. * * @param gradebookUid The gradebook's unique identifier * @return A map from the externalId of each activity to the providerAppKey */ public Map<String, String> getExternalAssignmentsForCurrentUser(String gradebookUid) throws GradebookNotFoundException; /** * Retrieve a list of all visible, external assignments for a set of users. * * @param gradebookUid The gradebook's unique identifier * @param studentIds The collection of student IDs for which to retrieve assignments * @return A map from the student ID to all visible, external activity IDs */ public Map<String, List<String>> getVisibleExternalAssignments(String gradebookUid, Collection<String> studentIds) throws GradebookNotFoundException; /** * Register a new ExternalAssignmentProvider for handling the integration of external * assessment sources with the sakai gradebook * Registering more than once will overwrite the current with the new one * * @param provider the provider implementation object */ public void registerExternalAssignmentProvider(ExternalAssignmentProvider provider); /** * Remove/unregister any ExternalAssignmentProvider which is currently registered, * does nothing if they provider does not exist * * @param providerAppKey the unique app key for a provider */ public void unregisterExternalAssignmentProvider(String providerAppKey); /** * Checks to see whether a gradebook with the given uid exists. * * @param gradebookUid * The gradebook UID to check * @return Whether the gradebook exists */ public boolean isGradebookDefined(String gradebookUid); /** * Break the connection between an external assessment engine and an assessment which * it created, giving it up to the Gradebook application to control from now on. * * @param gradebookUid * @param externalId */ public void setExternalAssessmentToGradebookAssignment(String gradebookUid, String externalId); /** * Get the category of a gradebook with the externalId given * * @param gradebookUId * @param externalId * @return */ public Long getExternalAssessmentCategoryId(String gradebookUId, String externalId); }
rodriguezdevera/sakai
edu-services/gradebook-service/api/src/java/org/sakaiproject/service/gradebook/shared/GradebookExternalAssessmentService.java
Java
apache-2.0
14,476
declare namespace jsrsasign.KJUR.asn1.csr { /** * ASN.1 CertificationRequestInfo structure class * @param params associative array of parameters (ex. {}) * @description * ``` * // -- DEFINITION OF ASN.1 SYNTAX -- * // CertificationRequestInfo ::= SEQUENCE { * // version INTEGER { v1(0) } (v1,...), * // subject Name, * // subjectPKInfo SubjectPublicKeyInfo{{ PKInfoAlgorithms }}, * // attributes [0] Attributes{{ CRIAttributes }} } * ``` * * @example * csri = new KJUR.asn1.csr.CertificationRequestInfo(); * csri.setSubjectByParam({'str': '/C=US/O=Test/CN=example.com'}); * csri.setSubjectPublicKeyByGetKey(pubKeyObj); */ class CertificationRequestInfo extends ASN1Object { constructor(); _initialize(): void; /** * set subject name field by parameter * @param x500NameParam X500Name parameter * @description * @example * csri.setSubjectByParam({'str': '/C=US/CN=b'}); * @see KJUR.asn1.x509.X500Name */ setSubjectByParam(x500NameParam: StringParam): void; /** * set subject public key info by RSA/ECDSA/DSA key parameter * @param keyParam public key parameter which passed to `KEYUTIL.getKey` argument * @example * csri.setSubjectPublicKeyByGetKeyParam(certPEMString); // or * csri.setSubjectPublicKeyByGetKeyParam(pkcs8PublicKeyPEMString); // or * csir.setSubjectPublicKeyByGetKeyParam(kjurCryptoECDSAKeyObject); // et.al. * @see KJUR.asn1.x509.SubjectPublicKeyInfo * @see KEYUTIL.getKey */ setSubjectPublicKeyByGetKey( keyParam: RSAKey | crypto.ECDSA | crypto.DSA | jws.JWS.JsonWebKey | { n: string; e: string } | string, ): void; /** * append X.509v3 extension to this object by name and parameters * @param name name of X.509v3 Extension object * @param extParams parameters as argument of Extension constructor. * @see KJUR.asn1.x509.Extension * @example * var o = new KJUR.asn1.csr.CertificationRequestInfo(); * o.appendExtensionByName('BasicConstraints', {'cA':true, 'critical': true}); * o.appendExtensionByName('KeyUsage', {'bin':'11'}); * o.appendExtensionByName('CRLDistributionPoints', {uri: 'http://aaa.com/a.crl'}); * o.appendExtensionByName('ExtKeyUsage', {array: [{name: 'clientAuth'}]}); * o.appendExtensionByName('AuthorityKeyIdentifier', {kid: '1234ab..'}); * o.appendExtensionByName('AuthorityInfoAccess', {array: [{accessMethod:{oid:...},accessLocation:{uri:...}}]}); */ appendExtensionByName( name: string, extParams: | { ca: boolean; critical: boolean } | BinParam | x509.UriParam | ArrayParam<{ name: string }> | { kid: string } | ArrayParam<{ accessMethod: { oid: string }; accessLocation: x509.UriParam }>, ): void; getEncodedHex(): string; } }
markogresak/DefinitelyTyped
types/jsrsasign/modules/KJUR/asn1/csr/CertificationRequestInfo.d.ts
TypeScript
mit
3,178
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Tool * @subpackage Framework * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ /** * @see Zend_Tool_Project_Context_Filesystem_Directory */ require_once 'Zend/Tool/Project/Context/Filesystem/Directory.php'; /** * This class is the front most class for utilizing Zend_Tool_Project * * A profile is a hierarchical set of resources that keep track of * items within a specific project. * * @category Zend * @package Zend_Tool * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Tool_Project_Context_Zf_ControllersDirectory extends Zend_Tool_Project_Context_Filesystem_Directory { /** * @var string */ protected $_filesystemName = 'controllers'; /** * getName() * * @return string */ public function getName() { return 'ControllersDirectory'; } }
groundcall/jobeet
vendor/Zend/Tool/Project/Context/Zf/ControllersDirectory.php
PHP
mit
1,595
// Type definitions for jsreport-html-embedded-in-docx 1.0 // Project: https://github.com/jsreport/jsreport-html-embedded-in-docx // Definitions by: taoqf <https://github.com/taoqf> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 import { ExtensionDefinition } from 'jsreport-core'; declare module 'jsreport-core' { interface Template { recipe: 'html-embedded-in-docx' | string; } } declare function JsReportHtmlEmbeddedInDocx(): ExtensionDefinition; export = JsReportHtmlEmbeddedInDocx;
borisyankov/DefinitelyTyped
types/jsreport-html-embedded-in-docx/index.d.ts
TypeScript
mit
542
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2017, Kairo Araujo <kairo@kairo.eti.br> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = r''' --- module: installp author: - Kairo Araujo (@kairoaraujo) short_description: Manage packages on AIX description: - Manage packages using 'installp' on AIX version_added: '2.8' options: accept_license: description: - Whether to accept the license for the package(s). type: bool default: no name: description: - One or more packages to install or remove. - Use C(all) to install all packages available on informed C(repository_path). type: list required: true aliases: [ pkg ] repository_path: description: - Path with AIX packages (required to install). type: path state: description: - Whether the package needs to be present on or absent from the system. type: str choices: [ absent, present ] default: present notes: - If the package is already installed, even the package/fileset is new, the module will not install it. ''' EXAMPLES = r''' - name: Install package foo installp: name: foo repository_path: /repository/AIX71/installp/base package_license: yes state: present - name: Install bos.sysmgt that includes bos.sysmgt.nim.master, bos.sysmgt.nim.spot installp: name: bos.sysmgt repository_path: /repository/AIX71/installp/base package_license: yes state: present - name: Install bos.sysmgt.nim.master only installp: name: bos.sysmgt.nim.master repository_path: /repository/AIX71/installp/base package_license: yes state: present - name: Install bos.sysmgt.nim.master and bos.sysmgt.nim.spot installp: name: bos.sysmgt.nim.master, bos.sysmgt.nim.spot repository_path: /repository/AIX71/installp/base package_license: yes state: present - name: Remove packages bos.sysmgt.nim.master installp: name: bos.sysmgt.nim.master state: absent ''' RETURN = r''' # ''' import os import re from ansible.module_utils.basic import AnsibleModule def _check_new_pkg(module, package, repository_path): """ Check if the package of fileset is correct name and repository path. :param module: Ansible module arguments spec. :param package: Package/fileset name. :param repository_path: Repository package path. :return: Bool, package information. """ if os.path.isdir(repository_path): installp_cmd = module.get_bin_path('installp', True) rc, package_result, err = module.run_command("%s -l -MR -d %s" % (installp_cmd, repository_path)) if rc != 0: module.fail_json(msg="Failed to run installp.", rc=rc, err=err) if package == 'all': pkg_info = "All packages on dir" return True, pkg_info else: pkg_info = {} for line in package_result.splitlines(): if re.findall(package, line): pkg_name = line.split()[0].strip() pkg_version = line.split()[1].strip() pkg_info[pkg_name] = pkg_version return True, pkg_info return False, None else: module.fail_json(msg="Repository path %s is not valid." % repository_path) def _check_installed_pkg(module, package, repository_path): """ Check the package on AIX. It verifies if the package is installed and informations :param module: Ansible module parameters spec. :param package: Package/fileset name. :param repository_path: Repository package path. :return: Bool, package data. """ lslpp_cmd = module.get_bin_path('lslpp', True) rc, lslpp_result, err = module.run_command("%s -lcq %s*" % (lslpp_cmd, package)) if rc == 1: package_state = ' '.join(err.split()[-2:]) if package_state == 'not installed.': return False, None else: module.fail_json(msg="Failed to run lslpp.", rc=rc, err=err) if rc != 0: module.fail_json(msg="Failed to run lslpp.", rc=rc, err=err) pkg_data = {} full_pkg_data = lslpp_result.splitlines() for line in full_pkg_data: pkg_name, fileset, level = line.split(':')[0:3] pkg_data[pkg_name] = fileset, level return True, pkg_data def remove(module, installp_cmd, packages): repository_path = None remove_count = 0 removed_pkgs = [] not_found_pkg = [] for package in packages: pkg_check, dummy = _check_installed_pkg(module, package, repository_path) if pkg_check: if not module.check_mode: rc, remove_out, err = module.run_command("%s -u %s" % (installp_cmd, package)) if rc != 0: module.fail_json(msg="Failed to run installp.", rc=rc, err=err) remove_count += 1 removed_pkgs.append(package) else: not_found_pkg.append(package) if remove_count > 0: if len(not_found_pkg) > 1: not_found_pkg.insert(0, "Package(s) not found: ") changed = True msg = "Packages removed: %s. %s " % (' '.join(removed_pkgs), ' '.join(not_found_pkg)) else: changed = False msg = ("No packages removed, all packages not found: %s" % ' '.join(not_found_pkg)) return changed, msg def install(module, installp_cmd, packages, repository_path, accept_license): installed_pkgs = [] not_found_pkgs = [] already_installed_pkgs = {} accept_license_param = { True: '-Y', False: '', } # Validate if package exists on repository path. for package in packages: pkg_check, pkg_data = _check_new_pkg(module, package, repository_path) # If package exists on repository path, check if package is installed. if pkg_check: pkg_check_current, pkg_info = _check_installed_pkg(module, package, repository_path) # If package is already installed. if pkg_check_current: # Check if package is a package and not a fileset, get version # and add the package into already installed list if package in pkg_info.keys(): already_installed_pkgs[package] = pkg_info[package][1] else: # If the package is not a package but a fileset, confirm # and add the fileset/package into already installed list for key in pkg_info.keys(): if package in pkg_info[key]: already_installed_pkgs[package] = pkg_info[key][1] else: if not module.check_mode: rc, out, err = module.run_command("%s -a %s -X -d %s %s" % (installp_cmd, accept_license_param[accept_license], repository_path, package)) if rc != 0: module.fail_json(msg="Failed to run installp", rc=rc, err=err) installed_pkgs.append(package) else: not_found_pkgs.append(package) if len(installed_pkgs) > 0: installed_msg = (" Installed: %s." % ' '.join(installed_pkgs)) else: installed_msg = '' if len(not_found_pkgs) > 0: not_found_msg = (" Not found: %s." % ' '.join(not_found_pkgs)) else: not_found_msg = '' if len(already_installed_pkgs) > 0: already_installed_msg = (" Already installed: %s." % already_installed_pkgs) else: already_installed_msg = '' if len(installed_pkgs) > 0: changed = True msg = ("%s%s%s" % (installed_msg, not_found_msg, already_installed_msg)) else: changed = False msg = ("No packages installed.%s%s%s" % (installed_msg, not_found_msg, already_installed_msg)) return changed, msg def main(): module = AnsibleModule( argument_spec=dict( name=dict(type='list', required=True, aliases=['pkg']), repository_path=dict(type='path'), accept_license=dict(type='bool', default=False), state=dict(type='str', default='present', choices=['absent', 'present']), ), supports_check_mode=True, ) name = module.params['name'] repository_path = module.params['repository_path'] accept_license = module.params['accept_license'] state = module.params['state'] installp_cmd = module.get_bin_path('installp', True) if state == 'present': if repository_path is None: module.fail_json(msg="repository_path is required to install package") changed, msg = install(module, installp_cmd, name, repository_path, accept_license) elif state == 'absent': changed, msg = remove(module, installp_cmd, name) else: module.fail_json(changed=False, msg="Unexpected state.") module.exit_json(changed=changed, msg=msg) if __name__ == '__main__': main()
andmos/ansible
lib/ansible/modules/packaging/os/installp.py
Python
gpl-3.0
9,242
/** * @author mrdoob / http://mrdoob.com/ */ THREE.XHRLoader = function ( manager ) { this.cache = new THREE.Cache(); this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; }; THREE.XHRLoader.prototype = { constructor: THREE.XHRLoader, load: function ( url, onLoad, onProgress, onError ) { var scope = this; var cached = scope.cache.get( url ); if ( cached !== undefined ) { if ( onLoad ) onLoad( cached ); return; } var request = new XMLHttpRequest(); request.open( 'GET', url, true ); request.addEventListener( 'load', function ( event ) { scope.cache.add( url, this.response ); if ( onLoad ) onLoad( this.response ); scope.manager.itemEnd( url ); }, false ); if ( onProgress !== undefined ) { request.addEventListener( 'progress', function ( event ) { onProgress( event ); }, false ); } if ( onError !== undefined ) { request.addEventListener( 'error', function ( event ) { onError( event ); }, false ); } if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin; if ( this.responseType !== undefined ) request.responseType = this.responseType; request.send( null ); scope.manager.itemStart( url ); }, setResponseType: function ( value ) { this.responseType = value; }, setCrossOrigin: function ( value ) { this.crossOrigin = value; } };
ccclayton/DataWar
static/js/threejs.r70/src/loaders/XHRLoader.js
JavaScript
mit
1,408
import type { INoiseFactor } from "./INoiseFactor"; import type { IOptionLoader } from "../../IOptionLoader"; import type { INoiseDelay } from "./INoiseDelay"; export interface INoise extends IOptionLoader<INoise> { delay: INoiseDelay; enable: boolean; factor: INoiseFactor; }
cdnjs/cdnjs
ajax/libs/tsparticles/1.16.0-alpha.5/Options/Interfaces/Particles/Noise/INoise.d.ts
TypeScript
mit
289
<?php // Heading $_['heading_title'] = 'Return Status'; // Text $_['text_success'] = 'Success: You have modified return statuses!'; // Column $_['column_name'] = 'Return Status Name'; $_['column_action'] = 'Action'; // Entry $_['entry_name'] = 'Return Status Name:'; // Error $_['error_permission'] = 'Warning: You do not have permission to modify return statues!'; $_['error_name'] = 'Return Status Name must be between 3 and 32 characters!'; $_['error_default'] = 'Warning: This return status cannot be deleted as it is currently assigned as the default return status!'; $_['error_return'] = 'Warning: This return status cannot be deleted as it is currently assigned to %s returns!'; ?>
BROcart/2.7.8
www/admin/language/english/localisation/return_status.php
PHP
gpl-3.0
726
"""Local settings and globals.""" import sys from os.path import normpath, join from .base import * # Import secrets -- not needed #sys.path.append( # abspath(join(PROJECT_ROOT, '../secrets/TimelineJS/stg')) #) #from secrets import * # Set static URL STATIC_URL = '/static'
deenjohn/TimelineJS
website/core/settings/loc.py
Python
mpl-2.0
279
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.action; import com.google.common.collect.Lists; import org.elasticsearch.ExceptionsHelper; import org.elasticsearch.action.search.SearchPhaseExecutionException; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.action.search.ShardSearchFailure; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.EsRejectedExecutionException; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.test.ElasticsearchIntegrationTest; import org.elasticsearch.test.ElasticsearchIntegrationTest.ClusterScope; import org.junit.Test; import java.util.Locale; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import static org.hamcrest.Matchers.equalTo; /** */ @ClusterScope(scope = ElasticsearchIntegrationTest.Scope.SUITE, numDataNodes = 2) public class RejectionActionTests extends ElasticsearchIntegrationTest { @Override protected Settings nodeSettings(int nodeOrdinal) { return ImmutableSettings.builder() .put(super.nodeSettings(nodeOrdinal)) .put("threadpool.search.size", 1) .put("threadpool.search.queue_size", 1) .put("threadpool.index.size", 1) .put("threadpool.index.queue_size", 1) .put("threadpool.get.size", 1) .put("threadpool.get.queue_size", 1) .build(); } @Test public void simulateSearchRejectionLoad() throws Throwable { for (int i = 0; i < 10; i++) { client().prepareIndex("test", "type", Integer.toString(i)).setSource("field", "1").get(); } int numberOfAsyncOps = randomIntBetween(200, 700); final CountDownLatch latch = new CountDownLatch(numberOfAsyncOps); final CopyOnWriteArrayList<Object> responses = Lists.newCopyOnWriteArrayList(); for (int i = 0; i < numberOfAsyncOps; i++) { client().prepareSearch("test") .setSearchType(SearchType.QUERY_THEN_FETCH) .setQuery(QueryBuilders.matchQuery("field", "1")) .execute(new ActionListener<SearchResponse>() { @Override public void onResponse(SearchResponse searchResponse) { responses.add(searchResponse); latch.countDown(); } @Override public void onFailure(Throwable e) { responses.add(e); latch.countDown(); } }); } latch.await(); assertThat(responses.size(), equalTo(numberOfAsyncOps)); // validate all responses for (Object response : responses) { if (response instanceof SearchResponse) { SearchResponse searchResponse = (SearchResponse) response; for (ShardSearchFailure failure : searchResponse.getShardFailures()) { assertTrue("got unexpected reason..." + failure.reason(), failure.reason().toLowerCase(Locale.ENGLISH).contains("rejected")); } } else { Throwable t = (Throwable) response; Throwable unwrap = ExceptionsHelper.unwrapCause(t); if (unwrap instanceof SearchPhaseExecutionException) { SearchPhaseExecutionException e = (SearchPhaseExecutionException) unwrap; for (ShardSearchFailure failure : e.shardFailures()) { assertTrue("got unexpected reason..." + failure.reason(), failure.reason().toLowerCase(Locale.ENGLISH).contains("rejected")); } } else if ((unwrap instanceof EsRejectedExecutionException) == false) { throw new AssertionError("unexpected failure", (Throwable) response); } } } } }
dantuffery/elasticsearch
src/test/java/org/elasticsearch/action/RejectionActionTests.java
Java
apache-2.0
4,951
import _ = require("../index"); // tslint:disable-next-line:strict-export-declare-modifiers type GlobalPartial<T> = Partial<T>; declare module "../index" { type PartialObject<T> = GlobalPartial<T>; type Many<T> = T | ReadonlyArray<T>; interface LoDashStatic { /** * Creates a lodash object which wraps value to enable implicit method chain sequences. * Methods that operate on and return arrays, collections, and functions can be chained together. * Methods that retrieve a single value or may return a primitive value will automatically end the * chain sequence and return the unwrapped value. Otherwise, the value must be unwrapped with value(). * * Explicit chain sequences, which must be unwrapped with value(), may be enabled using _.chain. * * The execution of chained methods is lazy, that is, it's deferred until value() is * implicitly or explicitly called. * * Lazy evaluation allows several methods to support shortcut fusion. Shortcut fusion * is an optimization to merge iteratee calls; this avoids the creation of intermediate * arrays and can greatly reduce the number of iteratee executions. Sections of a chain * sequence qualify for shortcut fusion if the section is applied to an array and iteratees * accept only one argument. The heuristic for whether a section qualifies for shortcut * fusion is subject to change. * * Chaining is supported in custom builds as long as the value() method is directly or * indirectly included in the build. * * In addition to lodash methods, wrappers have Array and String methods. * The wrapper Array methods are: * concat, join, pop, push, shift, sort, splice, and unshift. * The wrapper String methods are: * replace and split. * * The wrapper methods that support shortcut fusion are: * at, compact, drop, dropRight, dropWhile, filter, find, findLast, head, initial, last, * map, reject, reverse, slice, tail, take, takeRight, takeRightWhile, takeWhile, and toArray * * The chainable wrapper methods are: * after, ary, assign, assignIn, assignInWith, assignWith, at, before, bind, bindAll, bindKey, * castArray, chain, chunk, commit, compact, concat, conforms, constant, countBy, create, * curry, debounce, defaults, defaultsDeep, defer, delay, difference, differenceBy, differenceWith, * drop, dropRight, dropRightWhile, dropWhile, extend, extendWith, fill, filter, flatMap, * flatMapDeep, flatMapDepth, flatten, flattenDeep, flattenDepth, flip, flow, flowRight, * fromPairs, functions, functionsIn, groupBy, initial, intersection, intersectionBy, intersectionWith, * invert, invertBy, invokeMap, iteratee, keyBy, keys, keysIn, map, mapKeys, mapValues, * matches, matchesProperty, memoize, merge, mergeWith, method, methodOf, mixin, negate, * nthArg, omit, omitBy, once, orderBy, over, overArgs, overEvery, overSome, partial, partialRight, * partition, pick, pickBy, plant, property, propertyOf, pull, pullAll, pullAllBy, pullAllWith, pullAt, * push, range, rangeRight, rearg, reject, remove, rest, reverse, sampleSize, set, setWith, * shuffle, slice, sort, sortBy, sortedUniq, sortedUniqBy, splice, spread, tail, take, * takeRight, takeRightWhile, takeWhile, tap, throttle, thru, toArray, toPairs, toPairsIn, * toPath, toPlainObject, transform, unary, union, unionBy, unionWith, uniq, uniqBy, uniqWith, * unset, unshift, unzip, unzipWith, update, updateWith, values, valuesIn, without, wrap, * xor, xorBy, xorWith, zip, zipObject, zipObjectDeep, and zipWith. * * The wrapper methods that are not chainable by default are: * add, attempt, camelCase, capitalize, ceil, clamp, clone, cloneDeep, cloneDeepWith, cloneWith, * conformsTo, deburr, defaultTo, divide, each, eachRight, endsWith, eq, escape, escapeRegExp, * every, find, findIndex, findKey, findLast, findLastIndex, findLastKey, first, floor, forEach, * forEachRight, forIn, forInRight, forOwn, forOwnRight, get, gt, gte, has, hasIn, head, * identity, includes, indexOf, inRange, invoke, isArguments, isArray, isArrayBuffer, * isArrayLike, isArrayLikeObject, isBoolean, isBuffer, isDate, isElement, isEmpty, isEqual, isEqualWith, * isError, isFinite, isFunction, isInteger, isLength, isMap, isMatch, isMatchWith, isNaN, * isNative, isNil, isNull, isNumber, isObject, isObjectLike, isPlainObject, isRegExp, * isSafeInteger, isSet, isString, isUndefined, isTypedArray, isWeakMap, isWeakSet, join, * kebabCase, last, lastIndexOf, lowerCase, lowerFirst, lt, lte, max, maxBy, mean, meanBy, * min, minBy, multiply, noConflict, noop, now, nth, pad, padEnd, padStart, parseInt, pop, * random, reduce, reduceRight, repeat, result, round, runInContext, sample, shift, size, * snakeCase, some, sortedIndex, sortedIndexBy, sortedLastIndex, sortedLastIndexBy, startCase, * startsWith, stubArray, stubFalse, stubObject, stubString, stubTrue, subtract, sum, sumBy, * template, times, toFinite, toInteger, toJSON, toLength, toLower, toNumber, toSafeInteger, * toString, toUpper, trim, trimEnd, trimStart, truncate, unescape, uniqueId, upperCase, * upperFirst, value, and words. **/ <T>(value: T): LoDashImplicitWrapper<T>; /** * The semantic version number. **/ VERSION: string; /** * By default, the template delimiters used by Lo-Dash are similar to those in embedded Ruby * (ERB). Change the following template settings to use alternative delimiters. **/ templateSettings: TemplateSettings; } /** * By default, the template delimiters used by Lo-Dash are similar to those in embedded Ruby * (ERB). Change the following template settings to use alternative delimiters. **/ interface TemplateSettings { /** * The "escape" delimiter. **/ escape?: RegExp; /** * The "evaluate" delimiter. **/ evaluate?: RegExp; /** * An object to import into the template as local variables. **/ imports?: Dictionary<any>; /** * The "interpolate" delimiter. **/ interpolate?: RegExp; /** * Used to reference the data object in the template text. **/ variable?: string; } /** * Creates a cache object to store key/value pairs. */ interface MapCache { /** * Removes `key` and its value from the cache. * @param key The key of the value to remove. * @return Returns `true` if the entry was removed successfully, else `false`. */ delete(key: any): boolean; /** * Gets the cached value for `key`. * @param key The key of the value to get. * @return Returns the cached value. */ get(key: any): any; /** * Checks if a cached value for `key` exists. * @param key The key of the entry to check. * @return Returns `true` if an entry for `key` exists, else `false`. */ has(key: any): boolean; /** * Sets `value` to `key` of the cache. * @param key The key of the value to cache. * @param value The value to cache. * @return Returns the cache object. */ set(key: any, value: any): this; /** * Removes all key-value entries from the map. */ clear?: () => void; } interface MapCacheConstructor { new (): MapCache; } interface LoDashImplicitWrapper<TValue> extends LoDashWrapper<TValue> { pop<T>(this: LoDashImplicitWrapper<List<T> | null | undefined>): T | undefined; push<T>(this: LoDashImplicitWrapper<List<T> | null | undefined>, ...items: T[]): this; shift<T>(this: LoDashImplicitWrapper<List<T> | null | undefined>): T | undefined; sort<T>(this: LoDashImplicitWrapper<List<T> | null | undefined>, compareFn?: (a: T, b: T) => number): this; splice<T>(this: LoDashImplicitWrapper<List<T> | null | undefined>, start: number, deleteCount?: number, ...items: T[]): this; unshift<T>(this: LoDashImplicitWrapper<List<T> | null | undefined>, ...items: T[]): this; } interface LoDashExplicitWrapper<TValue> extends LoDashWrapper<TValue> { pop<T>(this: LoDashExplicitWrapper<List<T> | null | undefined>): LoDashExplicitWrapper<T | undefined>; push<T>(this: LoDashExplicitWrapper<List<T> | null | undefined>, ...items: T[]): this; shift<T>(this: LoDashExplicitWrapper<List<T> | null | undefined>): LoDashExplicitWrapper<T | undefined>; sort<T>(this: LoDashExplicitWrapper<List<T> | null | undefined>, compareFn?: (a: T, b: T) => number): this; splice<T>(this: LoDashExplicitWrapper<List<T> | null | undefined>, start: number, deleteCount?: number, ...items: T[]): this; unshift<T>(this: LoDashExplicitWrapper<List<T> | null | undefined>, ...items: T[]): this; } type NotVoid = {} | null | undefined; type IterateeShorthand<T> = PropertyName | [PropertyName, any] | PartialDeep<T>; type ArrayIterator<T, TResult> = (value: T, index: number, collection: T[]) => TResult; type ListIterator<T, TResult> = (value: T, index: number, collection: List<T>) => TResult; type ListIteratee<T> = ListIterator<T, NotVoid> | IterateeShorthand<T>; type ListIterateeCustom<T, TResult> = ListIterator<T, TResult> | IterateeShorthand<T>; type ListIteratorTypeGuard<T, S extends T> = (value: T, index: number, collection: List<T>) => value is S; // Note: key should be string, not keyof T, because the actual object may contain extra properties that were not specified in the type. type ObjectIterator<TObject, TResult> = (value: TObject[keyof TObject], key: string, collection: TObject) => TResult; type ObjectIteratee<TObject> = ObjectIterator<TObject, NotVoid> | IterateeShorthand<TObject[keyof TObject]>; type ObjectIterateeCustom<TObject, TResult> = ObjectIterator<TObject, TResult> | IterateeShorthand<TObject[keyof TObject]>; type ObjectIteratorTypeGuard<TObject, S extends TObject[keyof TObject]> = (value: TObject[keyof TObject], key: string, collection: TObject) => value is S; type StringIterator<TResult> = (char: string, index: number, string: string) => TResult; /** @deprecated Use MemoVoidArrayIterator or MemoVoidDictionaryIterator instead. */ type MemoVoidIterator<T, TResult> = (prev: TResult, curr: T, indexOrKey: any, list: T[]) => void; /** @deprecated Use MemoListIterator or MemoObjectIterator instead. */ type MemoIterator<T, TResult> = (prev: TResult, curr: T, indexOrKey: any, list: T[]) => TResult; type MemoListIterator<T, TResult, TList> = (prev: TResult, curr: T, index: number, list: TList) => TResult; type MemoObjectIterator<T, TResult, TList> = (prev: TResult, curr: T, key: string, list: TList) => TResult; type MemoIteratorCapped<T, TResult> = (prev: TResult, curr: T) => TResult; type MemoIteratorCappedRight<T, TResult> = (curr: T, prev: TResult) => TResult; type MemoVoidArrayIterator<T, TResult> = (acc: TResult, curr: T, index: number, arr: T[]) => void; type MemoVoidDictionaryIterator<T, TResult> = (acc: TResult, curr: T, key: string, dict: Dictionary<T>) => void; type MemoVoidIteratorCapped<T, TResult> = (acc: TResult, curr: T) => void; type ValueIteratee<T> = ((value: T) => NotVoid) | IterateeShorthand<T>; type ValueIterateeCustom<T, TResult> = ((value: T) => TResult) | IterateeShorthand<T>; type ValueIteratorTypeGuard<T, S extends T> = (value: T) => value is S; type ValueKeyIteratee<T> = ((value: T, key: string) => NotVoid) | IterateeShorthand<T>; type ValueKeyIterateeTypeGuard<T, S extends T> = (value: T, key: string) => value is S; type Comparator<T> = (a: T, b: T) => boolean; type Comparator2<T1, T2> = (a: T1, b: T2) => boolean; type PropertyName = string | number | symbol; type PropertyPath = Many<PropertyName>; type Omit<T, K extends keyof T> = Pick<T, ({ [P in keyof T]: P } & { [P in K]: never } & { [x: string]: never })[keyof T]>; /** Common interface between Arrays and jQuery objects */ type List<T> = ArrayLike<T>; interface Dictionary<T> { [index: string]: T; } interface NumericDictionary<T> { [index: number]: T; } // Crazy typedef needed get _.omit to work properly with Dictionary and NumericDictionary type AnyKindOfDictionary = | Dictionary<{} | null | undefined> | NumericDictionary<{} | null | undefined>; interface Cancelable { cancel(): void; flush(): void; } type PartialDeep<T> = { [P in keyof T]?: PartialDeep<T[P]>; }; // For backwards compatibility type LoDashImplicitArrayWrapper<T> = LoDashImplicitWrapper<T[]>; type LoDashImplicitNillableArrayWrapper<T> = LoDashImplicitWrapper<T[] | null | undefined>; type LoDashImplicitObjectWrapper<T> = LoDashImplicitWrapper<T>; type LoDashImplicitNillableObjectWrapper<T> = LoDashImplicitWrapper<T | null | undefined>; type LoDashImplicitNumberArrayWrapper = LoDashImplicitWrapper<number[]>; type LoDashImplicitStringWrapper = LoDashImplicitWrapper<string>; type LoDashExplicitArrayWrapper<T> = LoDashExplicitWrapper<T[]>; type LoDashExplicitNillableArrayWrapper<T> = LoDashExplicitWrapper<T[] | null | undefined>; type LoDashExplicitObjectWrapper<T> = LoDashExplicitWrapper<T>; type LoDashExplicitNillableObjectWrapper<T> = LoDashExplicitWrapper<T | null | undefined>; type LoDashExplicitNumberArrayWrapper = LoDashExplicitWrapper<number[]>; type LoDashExplicitStringWrapper = LoDashExplicitWrapper<string>; type DictionaryIterator<T, TResult> = ObjectIterator<Dictionary<T>, TResult>; type DictionaryIteratee<T> = ObjectIteratee<Dictionary<T>>; type DictionaryIteratorTypeGuard<T, S extends T> = ObjectIteratorTypeGuard<Dictionary<T>, S>; // NOTE: keys of objects at run time are always strings, even when a NumericDictionary is being iterated. type NumericDictionaryIterator<T, TResult> = (value: T, key: string, collection: NumericDictionary<T>) => TResult; type NumericDictionaryIteratee<T> = NumericDictionaryIterator<T, NotVoid> | IterateeShorthand<T>; type NumericDictionaryIterateeCustom<T, TResult> = NumericDictionaryIterator<T, TResult> | IterateeShorthand<T>; }
BigBoss424/portfolio
v8/development/node_modules/@types/lodash/common/common.d.ts
TypeScript
apache-2.0
14,825
class Orientdb < Formula desc "Graph database" homepage "https://orientdb.com" url "https://orientdb.com/download.php?email=unknown@unknown.com&file=orientdb-community-2.1.6.tar.gz&os=mac" version "2.1.6" sha256 "c5aa4791b965812362e8faf50ff03e1970de1c81c707b9d0220cdadf8e61d0c1" bottle do cellar :any_skip_relocation sha256 "6f04b2646e4deae8be36ebc18eead46982b11f53aa2652414946ca221f09e3f8" => :el_capitan sha256 "c4a54eddf8503b82fd8452d6c502ca647cfe7469d4bf1a54bbfc9422536c3fc2" => :yosemite sha256 "b83e829bf06ba825b60058f0fd2484b2df3cfbdf7d3c24ed90879e47579c5b1b" => :mavericks end # Fixing OrientDB init scripts patch do url "https://gist.githubusercontent.com/maggiolo00/84835e0b82a94fe9970a/raw/1ed577806db4411fd8b24cd90e516580218b2d53/orientdbsh" sha256 "d8b89ecda7cb78c940b3c3a702eee7b5e0f099338bb569b527c63efa55e6487e" end def install rm_rf Dir["{bin,benchmarks}/*.{bat,exe}"] inreplace %W[bin/orientdb.sh bin/console.sh bin/gremlin.sh], '"YOUR_ORIENTDB_INSTALLATION_PATH"', libexec chmod 0755, Dir["bin/*"] libexec.install Dir["*"] mkpath "#{libexec}/log" touch "#{libexec}/log/orientdb.err" touch "#{libexec}/log/orientdb.log" bin.install_symlink "#{libexec}/bin/orientdb.sh" => "orientdb" bin.install_symlink "#{libexec}/bin/console.sh" => "orientdb-console" bin.install_symlink "#{libexec}/bin/gremlin.sh" => "orientdb-gremlin" end def caveats "Use `orientdb <start | stop | status>`, `orientdb-console` and `orientdb-gremlin`." end end
rokn/Count_Words_2015
fetched_code/ruby/orientdb.rb
Ruby
mit
1,560
require 'fog/openstack/models/model' module Fog module Compute class OpenStack class Flavor < Fog::OpenStack::Model identity :id attribute :name attribute :ram attribute :disk attribute :vcpus attribute :links attribute :swap attribute :rxtx_factor attribute :metadata attribute :ephemeral, :aliases => 'OS-FLV-EXT-DATA:ephemeral' attribute :is_public, :aliases => 'os-flavor-access:is_public' attribute :disabled, :aliases => 'OS-FLV-DISABLED:disabled' def save requires :name, :ram, :vcpus, :disk attributes[:ephemeral] = self.ephemeral || 0 attributes[:is_public] = self.is_public || false attributes[:disabled] = self.disabled || false attributes[:swap] = self.swap || 0 attributes[:rxtx_factor] = self.rxtx_factor || 1.0 merge_attributes(service.create_flavor(self.attributes).body['flavor']) self end def destroy requires :id service.delete_flavor(self.id) true end def metadata service.get_flavor_metadata(self.id).body['extra_specs'] rescue Fog::Compute::OpenStack::NotFound nil end def create_metadata(metadata) service.create_flavor_metadata(self.id, metadata) rescue Fog::Compute::OpenStack::NotFound nil end end end end end
ralzate/Aerosanidad-Correciones
vendor/bundle/ruby/2.2.0/gems/fog-1.35.0/lib/fog/openstack/models/compute/flavor.rb
Ruby
mit
1,492
# 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. """Presubmit script for Chromium browser resources. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for more details about the presubmit API built into depot_tools, and see http://www.chromium.org/developers/web-development-style-guide for the rules we're checking against here. """ import os import struct class InvalidPNGException(Exception): pass class ResourceScaleFactors(object): """Verifier of image dimensions for Chromium resources. This class verifies the image dimensions of resources in the various resource subdirectories. Attributes: paths: An array of tuples giving the folders to check and their relevant scale factors. For example: [(100, 'default_100_percent'), (200, 'default_200_percent')] """ def __init__(self, input_api, output_api, paths): """ Initializes ResourceScaleFactors with paths.""" self.input_api = input_api self.output_api = output_api self.paths = paths def RunChecks(self): """Verifies the scale factors of resources being added or modified. Returns: An array of presubmit errors if any images were detected not having the correct dimensions. """ def ImageSize(filename): with open(filename, 'rb', buffering=0) as f: data = f.read(24) if data[:8] != '\x89PNG\r\n\x1A\n' or data[12:16] != 'IHDR': raise InvalidPNGException return struct.unpack('>ii', data[16:24]) # Returns a list of valid scaled image sizes. The valid sizes are the # floor and ceiling of (base_size * scale_percent / 100). This is equivalent # to requiring that the actual scaled size is less than one pixel away from # the exact scaled size. def ValidSizes(base_size, scale_percent): return sorted(set([(base_size * scale_percent) / 100, (base_size * scale_percent + 99) / 100])) repository_path = self.input_api.os_path.relpath( self.input_api.PresubmitLocalPath(), self.input_api.change.RepositoryRoot()) results = [] # Check for affected files in any of the paths specified. affected_files = self.input_api.AffectedFiles(include_deletes=False) files = [] for f in affected_files: for path_spec in self.paths: path_root = self.input_api.os_path.join( repository_path, path_spec[1]) if (f.LocalPath().endswith('.png') and f.LocalPath().startswith(path_root)): # Only save the relative path from the resource directory. relative_path = self.input_api.os_path.relpath(f.LocalPath(), path_root) if relative_path not in files: files.append(relative_path) corrupt_png_error = ('Corrupt PNG in file %s. Note that binaries are not ' 'correctly uploaded to the code review tool and must be directly ' 'submitted using the dcommit command.') for f in files: base_image = self.input_api.os_path.join(self.paths[0][1], f) if not os.path.exists(base_image): results.append(self.output_api.PresubmitError( 'Base image %s does not exist' % self.input_api.os_path.join( repository_path, base_image))) continue try: base_dimensions = ImageSize(base_image) except InvalidPNGException: results.append(self.output_api.PresubmitError(corrupt_png_error % self.input_api.os_path.join(repository_path, base_image))) continue # Find all scaled versions of the base image and verify their sizes. for i in range(1, len(self.paths)): image_path = self.input_api.os_path.join(self.paths[i][1], f) if not os.path.exists(image_path): continue # Ensure that each image for a particular scale factor is the # correct scale of the base image. try: scaled_dimensions = ImageSize(image_path) except InvalidPNGException: results.append(self.output_api.PresubmitError(corrupt_png_error % self.input_api.os_path.join(repository_path, image_path))) continue for dimension_name, base_size, scaled_size in zip( ('width', 'height'), base_dimensions, scaled_dimensions): valid_sizes = ValidSizes(base_size, self.paths[i][0]) if scaled_size not in valid_sizes: results.append(self.output_api.PresubmitError( 'Image %s has %s %d, expected to be %s' % ( self.input_api.os_path.join(repository_path, image_path), dimension_name, scaled_size, ' or '.join(map(str, valid_sizes))))) return results
guorendong/iridium-browser-ubuntu
ui/resources/resource_check/resource_scale_factors.py
Python
bsd-3-clause
4,859
/*! * inferno v0.7.3 * (c) 2016 Dominic Gannaway * Released under the MPL-2.0 License. */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.Inferno = factory()); }(this, function () { 'use strict'; var babelHelpers = {}; babelHelpers.typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); babelHelpers.extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; babelHelpers; function isNullOrUndefined(obj) { return obj === void 0 || obj === null; } function isAttrAnEvent(attr) { return attr[0] === 'o' && attr[1] === 'n' && attr.length > 3; } function VNode(blueprint) { this.bp = blueprint; this.dom = null; this.instance = null; this.tag = null; this.children = null; this.style = null; this.className = null; this.attrs = null; this.events = null; this.hooks = null; this.key = null; this.clipData = null; } VNode.prototype = { setAttrs: function setAttrs(attrs) { this.attrs = attrs; return this; }, setTag: function setTag(tag) { this.tag = tag; return this; }, setStyle: function setStyle(style) { this.style = style; return this; }, setClassName: function setClassName(className) { this.className = className; return this; }, setChildren: function setChildren(children) { this.children = children; return this; }, setHooks: function setHooks(hooks) { this.hooks = hooks; return this; }, setEvents: function setEvents(events) { this.events = events; return this; }, setKey: function setKey(key) { this.key = key; return this; } }; function createVNode(bp) { return new VNode(bp); } function createBlueprint(shape, childrenType) { var tag = shape.tag || null; var tagIsDynamic = tag && tag.arg !== void 0 ? true : false; var children = !isNullOrUndefined(shape.children) ? shape.children : null; var childrenIsDynamic = children && children.arg !== void 0 ? true : false; var attrs = shape.attrs || null; var attrsIsDynamic = attrs && attrs.arg !== void 0 ? true : false; var hooks = shape.hooks || null; var hooksIsDynamic = hooks && hooks.arg !== void 0 ? true : false; var events = shape.events || null; var eventsIsDynamic = events && events.arg !== void 0 ? true : false; var key = shape.key !== void 0 ? shape.key : null; var keyIsDynamic = !isNullOrUndefined(key) && !isNullOrUndefined(key.arg); var style = shape.style || null; var styleIsDynamic = style && style.arg !== void 0 ? true : false; var className = shape.className !== void 0 ? shape.className : null; var classNameIsDynamic = className && className.arg !== void 0 ? true : false; var blueprint = { lazy: shape.lazy || false, dom: null, pools: { keyed: {}, nonKeyed: [] }, tag: !tagIsDynamic ? tag : null, className: className !== '' && className ? className : null, style: style !== '' && style ? style : null, isComponent: tagIsDynamic, hasAttrs: attrsIsDynamic || (attrs ? true : false), hasHooks: hooksIsDynamic, hasEvents: eventsIsDynamic, hasStyle: styleIsDynamic || (style !== '' && style ? true : false), hasClassName: classNameIsDynamic || (className !== '' && className ? true : false), childrenType: childrenType === void 0 ? children ? 5 : 0 : childrenType, attrKeys: null, eventKeys: null, isSVG: shape.isSVG || false }; return function () { var vNode = new VNode(blueprint); if (tagIsDynamic === true) { vNode.tag = arguments[tag.arg]; } if (childrenIsDynamic === true) { vNode.children = arguments[children.arg]; } if (attrsIsDynamic === true) { vNode.attrs = arguments[attrs.arg]; } else { vNode.attrs = attrs; } if (hooksIsDynamic === true) { vNode.hooks = arguments[hooks.arg]; } if (eventsIsDynamic === true) { vNode.events = arguments[events.arg]; } if (keyIsDynamic === true) { vNode.key = arguments[key.arg]; } if (styleIsDynamic === true) { vNode.style = arguments[style.arg]; } else { vNode.style = blueprint.style; } if (classNameIsDynamic === true) { vNode.className = arguments[className.arg]; } else { vNode.className = blueprint.className; } return vNode; }; } // Runs only once in applications lifetime var isBrowser = typeof window !== 'undefined' && window.document; // Copy of the util from dom/util, otherwise it makes massive bundles function documentCreateElement(tag, isSVG) { var dom = void 0; if (isSVG === true) { dom = document.createElementNS('http://www.w3.org/2000/svg', tag); } else { dom = document.createElement(tag); } return dom; } function createUniversalElement(tag, attrs, isSVG) { if (isBrowser) { var dom = documentCreateElement(tag, isSVG); if (attrs) { createStaticAttributes(attrs, dom); } return dom; } return null; } function createStaticAttributes(attrs, dom) { var attrKeys = Object.keys(attrs); for (var i = 0; i < attrKeys.length; i++) { var attr = attrKeys[i]; var value = attrs[attr]; if (attr === 'className') { dom.className = value; } else { if (value === true) { dom.setAttribute(attr, attr); } else if (!isNullOrUndefined(value) && value !== false && !isAttrAnEvent(attr)) { dom.setAttribute(attr, value); } } } } var index = { createBlueprint: createBlueprint, createVNode: createVNode, universal: { createElement: createUniversalElement } }; return index; }));
sashberd/cdnjs
ajax/libs/inferno/0.7.3/inferno.js
JavaScript
mit
6,896
/** * OpenLayers 3 Layer Switcher Control. * See [the examples](./examples) for usage. * @constructor * @extends {ol.control.Control} * @param {Object} opt_options Control options, extends olx.control.ControlOptions adding: * **`tipLabel`** `String` - the button tooltip. */ ol.control.LayerSwitcher = function(opt_options) { var options = opt_options || {}; var tipLabel = options.tipLabel ? options.tipLabel : 'Legend'; this.mapListeners = []; this.hiddenClassName = 'ol-unselectable ol-control layer-switcher'; this.shownClassName = this.hiddenClassName + ' shown'; var element = document.createElement('div'); element.className = this.hiddenClassName; var button = document.createElement('button'); button.setAttribute('title', tipLabel); element.appendChild(button); this.panel = document.createElement('div'); this.panel.className = 'panel'; element.appendChild(this.panel); var this_ = this; element.onmouseover = function(e) { this_.showPanel(); }; button.onclick = function(e) { this_.showPanel(); }; element.onmouseout = function(e) { e = e || window.event; if (!element.contains(e.toElement)) { this_.hidePanel(); } }; ol.control.Control.call(this, { element: element, target: options.target }); }; ol.inherits(ol.control.LayerSwitcher, ol.control.Control); /** * Show the layer panel. */ ol.control.LayerSwitcher.prototype.showPanel = function() { if (this.element.className != this.shownClassName) { this.element.className = this.shownClassName; this.renderPanel(); } }; /** * Hide the layer panel. */ ol.control.LayerSwitcher.prototype.hidePanel = function() { if (this.element.className != this.hiddenClassName) { this.element.className = this.hiddenClassName; } }; /** * Re-draw the layer panel to represent the current state of the layers. */ ol.control.LayerSwitcher.prototype.renderPanel = function() { this.ensureTopVisibleBaseLayerShown_(); while(this.panel.firstChild) { this.panel.removeChild(this.panel.firstChild); } var ul = document.createElement('ul'); this.panel.appendChild(ul); this.renderLayers_(this.getMap(), ul); }; /** * Set the map instance the control is associated with. * @param {ol.Map} map The map instance. */ ol.control.LayerSwitcher.prototype.setMap = function(map) { // Clean up listeners associated with the previous map for (var i = 0, key; i < this.mapListeners.length; i++) { this.getMap().unByKey(this.mapListeners[i]); } this.mapListeners.length = 0; // Wire up listeners etc. and store reference to new map ol.control.Control.prototype.setMap.call(this, map); if (map) { var this_ = this; this.mapListeners.push(map.on('pointerdown', function() { this_.hidePanel(); })); this.renderPanel(); } }; /** * Ensure only the top-most base layer is visible if more than one is visible. * @private */ ol.control.LayerSwitcher.prototype.ensureTopVisibleBaseLayerShown_ = function() { var lastVisibleBaseLyr; ol.control.LayerSwitcher.forEachRecursive(this.getMap(), function(l, idx, a) { if (l.get('type') === 'base' && l.getVisible()) { lastVisibleBaseLyr = l; } }); if (lastVisibleBaseLyr) this.setVisible_(lastVisibleBaseLyr, true); }; /** * Toggle the visible state of a layer. * Takes care of hiding other layers in the same exclusive group if the layer * is toggle to visible. * @private * @param {ol.layer.Base} The layer whos visibility will be toggled. */ ol.control.LayerSwitcher.prototype.setVisible_ = function(lyr, visible) { var map = this.getMap(); lyr.setVisible(visible); if (visible && lyr.get('type') === 'base') { // Hide all other base layers regardless of grouping ol.control.LayerSwitcher.forEachRecursive(map, function(l, idx, a) { if (l != lyr && l.get('type') === 'base') { l.setVisible(false); } }); } }; /** * Render all layers that are children of a group. * @private * @param {ol.layer.Base} lyr Layer to be rendered (should have a title property). * @param {Number} idx Position in parent group list. */ ol.control.LayerSwitcher.prototype.renderLayer_ = function(lyr, idx) { var this_ = this; var li = document.createElement('li'); var lyrTitle = lyr.get('title'); var lyrId = lyr.get('title').replace(' ', '-') + '_' + idx; var label = document.createElement('label'); if (lyr.getLayers) { li.className = 'group'; label.innerHTML = lyrTitle; li.appendChild(label); var ul = document.createElement('ul'); li.appendChild(ul); this.renderLayers_(lyr, ul); } else { var input = document.createElement('input'); if (lyr.get('type') === 'base') { input.type = 'radio'; input.name = 'base'; } else { input.type = 'checkbox'; } input.id = lyrId; input.checked = lyr.get('visible'); input.onchange = function(e) { this_.setVisible_(lyr, e.target.checked); }; li.appendChild(input); label.htmlFor = lyrId; label.innerHTML = lyrTitle; li.appendChild(label); } return li; }; /** * Render all layers that are children of a group. * @private * @param {ol.layer.Group} lyr Group layer whos children will be rendered. * @param {Element} elm DOM element that children will be appended to. */ ol.control.LayerSwitcher.prototype.renderLayers_ = function(lyr, elm) { var lyrs = lyr.getLayers().getArray().slice().reverse(); for (var i = 0, l; i < lyrs.length; i++) { l = lyrs[i]; if (l.get('title')) { elm.appendChild(this.renderLayer_(l, i)); } } }; /** * **Static** Call the supplied function for each layer in the passed layer group * recursing nested groups. * @param {ol.layer.Group} lyr The layer group to start iterating from. * @param {Function} fn Callback which will be called for each `ol.layer.Base` * found under `lyr`. The signature for `fn` is the same as `ol.Collection#forEach` */ ol.control.LayerSwitcher.forEachRecursive = function(lyr, fn) { lyr.getLayers().forEach(function(lyr, idx, a) { fn(lyr, idx, a); if (lyr.getLayers) { ol.control.LayerSwitcher.forEachRecursive(lyr, fn); } }); };
mwernimont/sparrow-ui
src/main/webapp/js/vendor/ol3-layerswitcher/1.0.2/ol3-layerswitcher.js
JavaScript
cc0-1.0
6,635
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * @package datafield * @subpackage number * @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com) * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); $plugin->version = 2015111600; // The current plugin version (Date: YYYYMMDDXX) $plugin->requires = 2015111000; // Requires this Moodle version $plugin->component = 'datafield_number'; // Full name of the plugin (used for diagnostics)
ernestovi/ups
moodle/mod/data/field/number/version.php
PHP
gpl-3.0
1,176
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.sql.tree; import com.google.common.collect.ImmutableList; import java.util.List; import java.util.Objects; import java.util.Optional; import static java.util.Objects.requireNonNull; public class NotExpression extends Expression { private final Expression value; public NotExpression(Expression value) { this(Optional.empty(), value); } public NotExpression(NodeLocation location, Expression value) { this(Optional.of(location), value); } private NotExpression(Optional<NodeLocation> location, Expression value) { super(location); requireNonNull(value, "value is null"); this.value = value; } public Expression getValue() { return value; } @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitNotExpression(this, context); } @Override public List<Node> getChildren() { return ImmutableList.of(value); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } NotExpression that = (NotExpression) o; return Objects.equals(value, that.value); } @Override public int hashCode() { return value.hashCode(); } }
marsorp/blog
presto166/presto-parser/src/main/java/com/facebook/presto/sql/tree/NotExpression.java
Java
apache-2.0
1,998
/* * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.codeInsight.daemon.impl.quickfix; import com.intellij.codeInsight.ExpectedTypeInfo; import com.intellij.codeInsight.ExpectedTypesProvider; import com.intellij.codeInsight.intention.impl.TypeExpression; import com.intellij.codeInsight.template.TemplateBuilder; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.psi.*; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.IncorrectOperationException; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * @author ven */ public class GuessTypeParameters { private final JVMElementFactory myFactory; private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.daemon.impl.quickfix.GuessTypeParameters"); public GuessTypeParameters(JVMElementFactory factory) { myFactory = factory; } private List<PsiType> matchingTypeParameters (PsiType[] paramVals, PsiTypeParameter[] params, ExpectedTypeInfo info) { PsiType type = info.getType(); int kind = info.getKind(); List<PsiType> result = new ArrayList<PsiType>(); for (int i = 0; i < paramVals.length; i++) { PsiType val = paramVals[i]; if (val != null) { switch (kind) { case ExpectedTypeInfo.TYPE_STRICTLY: if (val.equals(type)) result.add(myFactory.createType(params[i])); break; case ExpectedTypeInfo.TYPE_OR_SUBTYPE: if (type.isAssignableFrom(val)) result.add(myFactory.createType(params[i])); break; case ExpectedTypeInfo.TYPE_OR_SUPERTYPE: if (val.isAssignableFrom(type)) result.add(myFactory.createType(params[i])); break; } } } return result; } public void setupTypeElement (PsiTypeElement typeElement, ExpectedTypeInfo[] infos, PsiSubstitutor substitutor, TemplateBuilder builder, @Nullable PsiElement context, PsiClass targetClass) { LOG.assertTrue(typeElement.isValid()); ApplicationManager.getApplication().assertWriteAccessAllowed(); PsiManager manager = typeElement.getManager(); GlobalSearchScope scope = typeElement.getResolveScope(); Project project = manager.getProject(); if (infos.length == 1 && substitutor != null && substitutor != PsiSubstitutor.EMPTY) { ExpectedTypeInfo info = infos[0]; Map<PsiTypeParameter, PsiType> map = substitutor.getSubstitutionMap(); PsiType[] vals = map.values().toArray(PsiType.createArray(map.size())); PsiTypeParameter[] params = map.keySet().toArray(new PsiTypeParameter[map.size()]); List<PsiType> types = matchingTypeParameters(vals, params, info); if (!types.isEmpty()) { ContainerUtil.addAll(types, ExpectedTypesProvider.processExpectedTypes(infos, new MyTypeVisitor(manager, scope), project)); builder.replaceElement(typeElement, new TypeExpression(project, types.toArray(PsiType.createArray(types.size())))); return; } else { PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory(); PsiType type = info.getType(); PsiType defaultType = info.getDefaultType(); try { PsiTypeElement inplaceTypeElement = ((PsiVariable)factory.createVariableDeclarationStatement("foo", type, null).getDeclaredElements()[0]).getTypeElement(); PsiSubstitutor rawingSubstitutor = getRawingSubstitutor (context, targetClass); int substitionResult = substituteToTypeParameters(typeElement, inplaceTypeElement, vals, params, builder, rawingSubstitutor, true); if (substitionResult != SUBSTITUTED_NONE) { if (substitionResult == SUBSTITUTED_IN_PARAMETERS) { PsiJavaCodeReferenceElement refElement = typeElement.getInnermostComponentReferenceElement(); LOG.assertTrue(refElement != null && refElement.getReferenceNameElement() != null); type = getComponentType(type); LOG.assertTrue(type != null); defaultType = getComponentType(defaultType); LOG.assertTrue(defaultType != null); ExpectedTypeInfo info1 = ExpectedTypesProvider.createInfo(((PsiClassType)defaultType).rawType(), ExpectedTypeInfo.TYPE_STRICTLY, ((PsiClassType)defaultType).rawType(), info.getTailType()); MyTypeVisitor visitor = new MyTypeVisitor(manager, scope); builder.replaceElement(refElement.getReferenceNameElement(), new TypeExpression(project, ExpectedTypesProvider.processExpectedTypes(new ExpectedTypeInfo[]{info1}, visitor, project))); } return; } } catch (IncorrectOperationException e) { LOG.error(e); } } } PsiType[] types = infos.length == 0 ? new PsiType[] {typeElement.getType()} : ExpectedTypesProvider.processExpectedTypes(infos, new MyTypeVisitor(manager, scope), project); builder.replaceElement(typeElement, new TypeExpression(project, types)); } private static PsiSubstitutor getRawingSubstitutor(PsiElement context, PsiClass targetClass) { if (context == null || targetClass == null) return PsiSubstitutor.EMPTY; PsiTypeParameterListOwner currContext = PsiTreeUtil.getParentOfType(context, PsiTypeParameterListOwner.class); PsiManager manager = context.getManager(); PsiSubstitutor substitutor = PsiSubstitutor.EMPTY; while (currContext != null && !manager.areElementsEquivalent(currContext, targetClass)) { PsiTypeParameter[] typeParameters = currContext.getTypeParameters(); substitutor = JavaPsiFacade.getInstance(context.getProject()).getElementFactory().createRawSubstitutor(substitutor, typeParameters); currContext = currContext.getContainingClass(); } return substitutor; } @Nullable private static PsiClassType getComponentType (PsiType type) { type = type.getDeepComponentType(); if (type instanceof PsiClassType) return (PsiClassType)type; return null; } private static final int SUBSTITUTED_NONE = 0; private static final int SUBSTITUTED_IN_REF = 1; private static final int SUBSTITUTED_IN_PARAMETERS = 2; private int substituteToTypeParameters (PsiTypeElement typeElement, PsiTypeElement inplaceTypeElement, PsiType[] paramVals, PsiTypeParameter[] params, TemplateBuilder builder, PsiSubstitutor rawingSubstitutor, boolean toplevel) { PsiType type = inplaceTypeElement.getType(); List<PsiType> types = new ArrayList<PsiType>(); for (int i = 0; i < paramVals.length; i++) { PsiType val = paramVals[i]; if (val == null) return SUBSTITUTED_NONE; if (type.equals(val)) { types.add(myFactory.createType(params[i])); } } if (!types.isEmpty()) { Project project = typeElement.getProject(); PsiType substituted = rawingSubstitutor.substitute(type); if (!CommonClassNames.JAVA_LANG_OBJECT.equals(substituted.getCanonicalText()) && (toplevel || substituted.equals(type))) { types.add(substituted); } builder.replaceElement(typeElement, new TypeExpression(project, types.toArray(PsiType.createArray(types.size())))); return toplevel ? SUBSTITUTED_IN_REF : SUBSTITUTED_IN_PARAMETERS; } boolean substituted = false; PsiJavaCodeReferenceElement ref = typeElement.getInnermostComponentReferenceElement(); PsiJavaCodeReferenceElement inplaceRef = inplaceTypeElement.getInnermostComponentReferenceElement(); if (ref != null) { LOG.assertTrue(inplaceRef != null); PsiTypeElement[] innerTypeElements = ref.getParameterList().getTypeParameterElements(); PsiTypeElement[] inplaceInnerTypeElements = inplaceRef.getParameterList().getTypeParameterElements(); for (int i = 0; i < innerTypeElements.length; i++) { substituted |= substituteToTypeParameters(innerTypeElements[i], inplaceInnerTypeElements[i], paramVals, params, builder, rawingSubstitutor, false) != SUBSTITUTED_NONE; } } return substituted ? SUBSTITUTED_IN_PARAMETERS : SUBSTITUTED_NONE; } public static class MyTypeVisitor extends PsiTypeVisitor<PsiType> { private final GlobalSearchScope myResolveScope; private final PsiManager myManager; public MyTypeVisitor(PsiManager manager, GlobalSearchScope resolveScope) { myManager = manager; myResolveScope = resolveScope; } @Override public PsiType visitType(PsiType type) { if (type.equals(PsiType.NULL)) return PsiType.getJavaLangObject(myManager, myResolveScope); return type; } @Override public PsiType visitCapturedWildcardType(PsiCapturedWildcardType capturedWildcardType) { return capturedWildcardType.getUpperBound().accept(this); } } }
kdwink/intellij-community
java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/GuessTypeParameters.java
Java
apache-2.0
10,162
//===-- PPCPredicates.cpp - PPC Branch Predicate Information --------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file implements the PowerPC branch predicates. // //===----------------------------------------------------------------------===// #include "PPCPredicates.h" #include "llvm/Support/ErrorHandling.h" #include <cassert> using namespace llvm; PPC::Predicate PPC::InvertPredicate(PPC::Predicate Opcode) { switch (Opcode) { case PPC::PRED_EQ: return PPC::PRED_NE; case PPC::PRED_NE: return PPC::PRED_EQ; case PPC::PRED_LT: return PPC::PRED_GE; case PPC::PRED_GE: return PPC::PRED_LT; case PPC::PRED_GT: return PPC::PRED_LE; case PPC::PRED_LE: return PPC::PRED_GT; case PPC::PRED_NU: return PPC::PRED_UN; case PPC::PRED_UN: return PPC::PRED_NU; case PPC::PRED_EQ_MINUS: return PPC::PRED_NE_PLUS; case PPC::PRED_NE_MINUS: return PPC::PRED_EQ_PLUS; case PPC::PRED_LT_MINUS: return PPC::PRED_GE_PLUS; case PPC::PRED_GE_MINUS: return PPC::PRED_LT_PLUS; case PPC::PRED_GT_MINUS: return PPC::PRED_LE_PLUS; case PPC::PRED_LE_MINUS: return PPC::PRED_GT_PLUS; case PPC::PRED_NU_MINUS: return PPC::PRED_UN_PLUS; case PPC::PRED_UN_MINUS: return PPC::PRED_NU_PLUS; case PPC::PRED_EQ_PLUS: return PPC::PRED_NE_MINUS; case PPC::PRED_NE_PLUS: return PPC::PRED_EQ_MINUS; case PPC::PRED_LT_PLUS: return PPC::PRED_GE_MINUS; case PPC::PRED_GE_PLUS: return PPC::PRED_LT_MINUS; case PPC::PRED_GT_PLUS: return PPC::PRED_LE_MINUS; case PPC::PRED_LE_PLUS: return PPC::PRED_GT_MINUS; case PPC::PRED_NU_PLUS: return PPC::PRED_UN_MINUS; case PPC::PRED_UN_PLUS: return PPC::PRED_NU_MINUS; // Simple predicates for single condition-register bits. case PPC::PRED_BIT_SET: return PPC::PRED_BIT_UNSET; case PPC::PRED_BIT_UNSET: return PPC::PRED_BIT_SET; } llvm_unreachable("Unknown PPC branch opcode!"); } PPC::Predicate PPC::getSwappedPredicate(PPC::Predicate Opcode) { switch (Opcode) { case PPC::PRED_EQ: return PPC::PRED_EQ; case PPC::PRED_NE: return PPC::PRED_NE; case PPC::PRED_LT: return PPC::PRED_GT; case PPC::PRED_GE: return PPC::PRED_LE; case PPC::PRED_GT: return PPC::PRED_LT; case PPC::PRED_LE: return PPC::PRED_GE; case PPC::PRED_NU: return PPC::PRED_NU; case PPC::PRED_UN: return PPC::PRED_UN; case PPC::PRED_EQ_MINUS: return PPC::PRED_EQ_MINUS; case PPC::PRED_NE_MINUS: return PPC::PRED_NE_MINUS; case PPC::PRED_LT_MINUS: return PPC::PRED_GT_MINUS; case PPC::PRED_GE_MINUS: return PPC::PRED_LE_MINUS; case PPC::PRED_GT_MINUS: return PPC::PRED_LT_MINUS; case PPC::PRED_LE_MINUS: return PPC::PRED_GE_MINUS; case PPC::PRED_NU_MINUS: return PPC::PRED_NU_MINUS; case PPC::PRED_UN_MINUS: return PPC::PRED_UN_MINUS; case PPC::PRED_EQ_PLUS: return PPC::PRED_EQ_PLUS; case PPC::PRED_NE_PLUS: return PPC::PRED_NE_PLUS; case PPC::PRED_LT_PLUS: return PPC::PRED_GT_PLUS; case PPC::PRED_GE_PLUS: return PPC::PRED_LE_PLUS; case PPC::PRED_GT_PLUS: return PPC::PRED_LT_PLUS; case PPC::PRED_LE_PLUS: return PPC::PRED_GE_PLUS; case PPC::PRED_NU_PLUS: return PPC::PRED_NU_PLUS; case PPC::PRED_UN_PLUS: return PPC::PRED_UN_PLUS; case PPC::PRED_BIT_SET: case PPC::PRED_BIT_UNSET: llvm_unreachable("Invalid use of bit predicate code"); } llvm_unreachable("Unknown PPC branch opcode!"); }
endlessm/chromium-browser
third_party/swiftshader/third_party/llvm-10.0/llvm/lib/Target/PowerPC/MCTargetDesc/PPCPredicates.cpp
C++
bsd-3-clause
3,553
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { __core_private__ as r } from '@angular/core'; export declare type RenderDebugInfo = typeof r._RenderDebugInfo; export declare var RenderDebugInfo: typeof r.RenderDebugInfo; export declare type DirectRenderer = typeof r._DirectRenderer; export declare var ReflectionCapabilities: typeof r.ReflectionCapabilities; export declare type DebugDomRootRenderer = typeof r._DebugDomRootRenderer; export declare var DebugDomRootRenderer: typeof r.DebugDomRootRenderer; export declare var reflector: typeof r.reflector; export declare type NoOpAnimationPlayer = typeof r._NoOpAnimationPlayer; export declare var NoOpAnimationPlayer: typeof r.NoOpAnimationPlayer; export declare type AnimationPlayer = typeof r._AnimationPlayer; export declare var AnimationPlayer: typeof r.AnimationPlayer; export declare type AnimationSequencePlayer = typeof r._AnimationSequencePlayer; export declare var AnimationSequencePlayer: typeof r.AnimationSequencePlayer; export declare type AnimationGroupPlayer = typeof r._AnimationGroupPlayer; export declare var AnimationGroupPlayer: typeof r.AnimationGroupPlayer; export declare type AnimationKeyframe = typeof r._AnimationKeyframe; export declare var AnimationKeyframe: typeof r.AnimationKeyframe; export declare type AnimationStyles = typeof r._AnimationStyles; export declare var AnimationStyles: typeof r.AnimationStyles; export declare var prepareFinalAnimationStyles: typeof r.prepareFinalAnimationStyles; export declare var balanceAnimationKeyframes: typeof r.balanceAnimationKeyframes; export declare var clearStyles: typeof r.clearStyles; export declare var collectAndResolveStyles: typeof r.collectAndResolveStyles;
tspycher/python-raspberry-bugcontrol
static-web/node_modules/@angular/platform-browser/src/private_import_core.d.ts
TypeScript
mit
1,859
(function () { /*** Variables ***/ var win = window, doc = document, attrProto = { setAttribute: Element.prototype.setAttribute, removeAttribute: Element.prototype.removeAttribute }, hasShadow = Element.prototype.createShadowRoot, container = doc.createElement('div'), noop = function(){}, trueop = function(){ return true; }, regexReplaceCommas = /,/g, regexCamelToDash = /([a-z])([A-Z])/g, regexPseudoParens = /\(|\)/g, regexPseudoCapture = /:(\w+)\u276A(.+?(?=\u276B))|:(\w+)/g, regexDigits = /(\d+)/g, keypseudo = { action: function (pseudo, event) { return pseudo.value.match(regexDigits).indexOf(String(event.keyCode)) > -1 == (pseudo.name == 'keypass') || null; } }, /* - The prefix object generated here is added to the xtag object as xtag.prefix later in the code - Prefix provides a variety of prefix variations for the browser in which your code is running - The 4 variations of prefix are as follows: * prefix.dom: the correct prefix case and form when used on DOM elements/style properties * prefix.lowercase: a lowercase version of the prefix for use in various user-code situations * prefix.css: the lowercase, dashed version of the prefix * prefix.js: addresses prefixed APIs present in global and non-Element contexts */ prefix = (function () { var styles = win.getComputedStyle(doc.documentElement, ''), pre = (Array.prototype.slice .call(styles) .join('') .match(/-(moz|webkit|ms)-/) || (styles.OLink === '' && ['', 'o']) )[1]; return { dom: pre == 'ms' ? 'MS' : pre, lowercase: pre, css: '-' + pre + '-', js: pre == 'ms' ? pre : pre[0].toUpperCase() + pre.substr(1) }; })(), matchSelector = Element.prototype.matches || Element.prototype.matchesSelector || Element.prototype[prefix.lowercase + 'MatchesSelector']; /*** Functions ***/ // Utilities /* This is an enhanced typeof check for all types of objects. Where typeof would normaly return 'object' for many common DOM objects (like NodeLists and HTMLCollections). - For example: typeOf(document.children) will correctly return 'htmlcollection' */ var typeCache = {}, typeString = typeCache.toString, typeRegexp = /\s([a-zA-Z]+)/; function typeOf(obj) { var type = typeString.call(obj); return typeCache[type] || (typeCache[type] = type.match(typeRegexp)[1].toLowerCase()); } function clone(item, type){ var fn = clone[type || typeOf(item)]; return fn ? fn(item) : item; } clone.object = function(src){ var obj = {}; for (var key in src) obj[key] = clone(src[key]); return obj; }; clone.array = function(src){ var i = src.length, array = new Array(i); while (i--) array[i] = clone(src[i]); return array; }; /* The toArray() method allows for conversion of any object to a true array. For types that cannot be converted to an array, the method returns a 1 item array containing the passed-in object. */ var unsliceable = { 'undefined': 1, 'null': 1, 'number': 1, 'boolean': 1, 'string': 1, 'function': 1 }; function toArray(obj){ return unsliceable[typeOf(obj)] ? [obj] : Array.prototype.slice.call(obj, 0); } // DOM var str = ''; function query(element, selector){ return (selector || str).length ? toArray(element.querySelectorAll(selector)) : []; } // Pseudos function parsePseudo(fn){fn();} // Mixins function mergeOne(source, key, current){ var type = typeOf(current); if (type == 'object' && typeOf(source[key]) == 'object') xtag.merge(source[key], current); else source[key] = clone(current, type); return source; } function mergeMixin(tag, original, mixin, name) { var key, keys = {}; for (var z in original) keys[z.split(':')[0]] = z; for (z in mixin) { key = keys[z.split(':')[0]]; if (typeof original[key] == 'function') { if (!key.match(':mixins')) { original[key + ':mixins'] = original[key]; delete original[key]; key = key + ':mixins'; } original[key].__mixin__ = xtag.applyPseudos(z + (z.match(':mixins') ? '' : ':mixins'), mixin[z], tag.pseudos, original[key].__mixin__); } else { original[z] = mixin[z]; delete original[key]; } } } var uniqueMixinCount = 0; function addMixin(tag, original, mixin){ for (var z in mixin){ original[z + ':__mixin__(' + (uniqueMixinCount++) + ')'] = xtag.applyPseudos(z, mixin[z], tag.pseudos); } } function resolveMixins(mixins, output){ var index = mixins.length; while (index--){ output.unshift(mixins[index]); if (xtag.mixins[mixins[index]].mixins) resolveMixins(xtag.mixins[mixins[index]].mixins, output); } return output; } function applyMixins(tag) { resolveMixins(tag.mixins, []).forEach(function(name){ var mixin = xtag.mixins[name]; for (var type in mixin) { var item = mixin[type], original = tag[type]; if (!original) tag[type] = item; else { switch (type){ case 'mixins': break; case 'events': addMixin(tag, original, item); break; case 'accessors': case 'prototype': for (var z in item) { if (!original[z]) original[z] = item[z]; else mergeMixin(tag, original[z], item[z], name); } break; default: mergeMixin(tag, original, item, name); } } } }); return tag; } // Events function delegateAction(pseudo, event) { var match, target = event.target, root = event.currentTarget; while (!match && target && target != root) { if (target.tagName && matchSelector.call(target, pseudo.value)) match = target; target = target.parentNode; } if (!match && root.tagName && matchSelector.call(root, pseudo.value)) match = root; return match ? pseudo.listener = pseudo.listener.bind(match) : null; } function touchFilter(event){ return event.button === 0; } function writeProperty(key, event, base, desc){ if (desc) event[key] = base[key]; else Object.defineProperty(event, key, { writable: true, enumerable: true, value: base[key] }); } var skipProps = {}; for (var z in doc.createEvent('CustomEvent')) skipProps[z] = 1; function inheritEvent(event, base){ var desc = Object.getOwnPropertyDescriptor(event, 'target'); for (var z in base) { if (!skipProps[z]) writeProperty(z, event, base, desc); } event.baseEvent = base; } // Accessors function modAttr(element, attr, name, value, method){ attrProto[method].call(element, name, attr && attr.boolean ? '' : value); } function syncAttr(element, attr, name, value, method){ if (attr && (attr.property || attr.selector)) { var nodes = attr.property ? [element.xtag[attr.property]] : attr.selector ? xtag.query(element, attr.selector) : [], index = nodes.length; while (index--) nodes[index][method](name, value); } } function attachProperties(tag, prop, z, accessor, attr, name){ var key = z.split(':'), type = key[0]; if (type == 'get') { key[0] = prop; tag.prototype[prop].get = xtag.applyPseudos(key.join(':'), accessor[z], tag.pseudos, accessor[z]); } else if (type == 'set') { key[0] = prop; var setter = tag.prototype[prop].set = xtag.applyPseudos(key.join(':'), attr ? function(value){ var old, method = 'setAttribute'; if (attr.boolean){ value = !!value; old = this.hasAttribute(name); if (!value) method = 'removeAttribute'; } else { value = attr.validate ? attr.validate.call(this, value) : value; old = this.getAttribute(name); } modAttr(this, attr, name, value, method); accessor[z].call(this, value, old); syncAttr(this, attr, name, value, method); } : accessor[z] ? function(value){ accessor[z].call(this, value); } : null, tag.pseudos, accessor[z]); if (attr) attr.setter = accessor[z]; } else tag.prototype[prop][z] = accessor[z]; } function parseAccessor(tag, prop){ tag.prototype[prop] = {}; var accessor = tag.accessors[prop], attr = accessor.attribute, name; if (attr) { name = attr.name = (attr ? (attr.name || prop.replace(regexCamelToDash, '$1-$2')) : prop).toLowerCase(); attr.key = prop; tag.attributes[name] = attr; } for (var z in accessor) attachProperties(tag, prop, z, accessor, attr, name); if (attr) { if (!tag.prototype[prop].get) { var method = (attr.boolean ? 'has' : 'get') + 'Attribute'; tag.prototype[prop].get = function(){ return this[method](name); }; } if (!tag.prototype[prop].set) tag.prototype[prop].set = function(value){ value = attr.boolean ? !!value : attr.validate ? attr.validate.call(this, value) : value; var method = attr.boolean ? (value ? 'setAttribute' : 'removeAttribute') : 'setAttribute'; modAttr(this, attr, name, value, method); syncAttr(this, attr, name, value, method); }; } } var unwrapComment = /\/\*!?(?:\@preserve)?[ \t]*(?:\r\n|\n)([\s\S]*?)(?:\r\n|\n)\s*\*\//; function parseMultiline(fn){ return typeof fn == 'function' ? unwrapComment.exec(fn.toString())[1] : fn; } /*** X-Tag Object Definition ***/ var xtag = { tags: {}, defaultOptions: { pseudos: [], mixins: [], events: {}, methods: {}, accessors: {}, lifecycle: {}, attributes: {}, 'prototype': { xtag: { get: function(){ return this.__xtag__ ? this.__xtag__ : (this.__xtag__ = { data: {} }); } } } }, register: function (name, options) { var _name; if (typeof name == 'string') _name = name.toLowerCase(); else throw 'First argument must be a Custom Element string name'; xtag.tags[_name] = options || {}; var basePrototype = options.prototype; delete options.prototype; var tag = xtag.tags[_name].compiled = applyMixins(xtag.merge({}, xtag.defaultOptions, options)); var proto = tag.prototype; var lifecycle = tag.lifecycle; for (var z in tag.events) tag.events[z] = xtag.parseEvent(z, tag.events[z]); for (z in lifecycle) lifecycle[z.split(':')[0]] = xtag.applyPseudos(z, lifecycle[z], tag.pseudos, lifecycle[z]); for (z in tag.methods) proto[z.split(':')[0]] = { value: xtag.applyPseudos(z, tag.methods[z], tag.pseudos, tag.methods[z]), enumerable: true }; for (z in tag.accessors) parseAccessor(tag, z); if (tag.shadow) tag.shadow = tag.shadow.nodeName ? tag.shadow : xtag.createFragment(tag.shadow); if (tag.content) tag.content = tag.content.nodeName ? tag.content.innerHTML : parseMultiline(tag.content); var created = lifecycle.created; var finalized = lifecycle.finalized; proto.createdCallback = { enumerable: true, value: function(){ var element = this; if (tag.shadow && hasShadow) this.createShadowRoot().appendChild(tag.shadow.cloneNode(true)); if (tag.content) this.appendChild(document.createElement('div')).outerHTML = tag.content; var output = created ? created.apply(this, arguments) : null; xtag.addEvents(this, tag.events); for (var name in tag.attributes) { var attr = tag.attributes[name], hasAttr = this.hasAttribute(name), hasDefault = attr.def !== undefined; if (hasAttr || attr.boolean || hasDefault) { this[attr.key] = attr.boolean ? hasAttr : !hasAttr && hasDefault ? attr.def : this.getAttribute(name); } } tag.pseudos.forEach(function(obj){ obj.onAdd.call(element, obj); }); this.xtagComponentReady = true; if (finalized) finalized.apply(this, arguments); return output; } }; var inserted = lifecycle.inserted; var removed = lifecycle.removed; if (inserted || removed) { proto.attachedCallback = { value: function(){ if (removed) this.xtag.__parentNode__ = this.parentNode; if (inserted) return inserted.apply(this, arguments); }, enumerable: true }; } if (removed) { proto.detachedCallback = { value: function(){ var args = toArray(arguments); args.unshift(this.xtag.__parentNode__); var output = removed.apply(this, args); delete this.xtag.__parentNode__; return output; }, enumerable: true }; } if (lifecycle.attributeChanged) proto.attributeChangedCallback = { value: lifecycle.attributeChanged, enumerable: true }; proto.setAttribute = { writable: true, enumerable: true, value: function (name, value){ var old; var _name = name.toLowerCase(); var attr = tag.attributes[_name]; if (attr) { old = this.getAttribute(_name); value = attr.boolean ? '' : attr.validate ? attr.validate.call(this, value) : value; } modAttr(this, attr, _name, value, 'setAttribute'); if (attr) { if (attr.setter) attr.setter.call(this, attr.boolean ? true : value, old); syncAttr(this, attr, _name, value, 'setAttribute'); } } }; proto.removeAttribute = { writable: true, enumerable: true, value: function (name){ var _name = name.toLowerCase(); var attr = tag.attributes[_name]; var old = this.hasAttribute(_name); modAttr(this, attr, _name, '', 'removeAttribute'); if (attr) { if (attr.setter) attr.setter.call(this, attr.boolean ? false : undefined, old); syncAttr(this, attr, _name, '', 'removeAttribute'); } } }; var definition = {}; var instance = basePrototype instanceof win.HTMLElement; var extended = tag['extends'] && (definition['extends'] = tag['extends']); if (basePrototype) Object.getOwnPropertyNames(basePrototype).forEach(function(z){ var prop = proto[z]; var desc = instance ? Object.getOwnPropertyDescriptor(basePrototype, z) : basePrototype[z]; if (prop) { for (var y in desc) { if (typeof desc[y] == 'function' && prop[y]) prop[y] = xtag.wrap(desc[y], prop[y]); else prop[y] = desc[y]; } } proto[z] = prop || desc; }); definition['prototype'] = Object.create( extended ? Object.create(doc.createElement(extended).constructor).prototype : win.HTMLElement.prototype, proto ); return doc.registerElement(_name, definition); }, /* Exposed Variables */ mixins: {}, prefix: prefix, captureEvents: { focus: 1, blur: 1, scroll: 1, DOMMouseScroll: 1 }, customEvents: { animationstart: { attach: [prefix.dom + 'AnimationStart'] }, animationend: { attach: [prefix.dom + 'AnimationEnd'] }, transitionend: { attach: [prefix.dom + 'TransitionEnd'] }, move: { attach: ['pointermove'] }, enter: { attach: ['pointerenter'] }, leave: { attach: ['pointerleave'] }, scrollwheel: { attach: ['DOMMouseScroll', 'mousewheel'], condition: function(event){ event.delta = event.wheelDelta ? event.wheelDelta / 40 : Math.round(event.detail / 3.5 * -1); return true; } }, tap: { attach: ['pointerdown', 'pointerup'], condition: function(event, custom){ if (event.type == 'pointerdown') { custom.startX = event.clientX; custom.startY = event.clientY; } else if (event.button === 0 && Math.abs(custom.startX - event.clientX) < 10 && Math.abs(custom.startY - event.clientY) < 10) return true; } }, tapstart: { attach: ['pointerdown'], condition: touchFilter }, tapend: { attach: ['pointerup'], condition: touchFilter }, tapmove: { attach: ['pointerdown'], condition: function(event, custom){ if (event.type == 'pointerdown') { var listener = custom.listener.bind(this); if (!custom.tapmoveListeners) custom.tapmoveListeners = xtag.addEvents(document, { pointermove: listener, pointerup: listener, pointercancel: listener }); } else if (event.type == 'pointerup' || event.type == 'pointercancel') { xtag.removeEvents(document, custom.tapmoveListeners); custom.tapmoveListeners = null; } return true; } }, taphold: { attach: ['pointerdown', 'pointerup'], condition: function(event, custom){ if (event.type == 'pointerdown') { (custom.pointers = custom.pointers || {})[event.pointerId] = setTimeout( xtag.fireEvent.bind(null, this, 'taphold'), custom.duration || 1000 ); } else if (event.type == 'pointerup') { if (custom.pointers) { clearTimeout(custom.pointers[event.pointerId]); delete custom.pointers[event.pointerId]; } } else return true; } } }, pseudos: { __mixin__: {}, mixins: { onCompiled: function(fn, pseudo){ var mixin = pseudo.source && pseudo.source.__mixin__ || pseudo.source; if (mixin) switch (pseudo.value) { case null: case '': case 'before': return function(){ mixin.apply(this, arguments); return fn.apply(this, arguments); }; case 'after': return function(){ var returns = fn.apply(this, arguments); mixin.apply(this, arguments); return returns; }; case 'none': return fn; } else return fn; } }, keypass: keypseudo, keyfail: keypseudo, delegate: { action: delegateAction }, preventable: { action: function (pseudo, event) { return !event.defaultPrevented; } }, duration: { onAdd: function(pseudo){ pseudo.source.duration = Number(pseudo.value); } }, capture: { onCompiled: function(fn, pseudo){ if (pseudo.source) pseudo.source.capture = true; } } }, /* UTILITIES */ clone: clone, typeOf: typeOf, toArray: toArray, wrap: function (original, fn) { return function(){ var output = original.apply(this, arguments); fn.apply(this, arguments); return output; }; }, /* Recursively merges one object with another. The first argument is the destination object, all other objects passed in as arguments are merged from right to left, conflicts are overwritten */ merge: function(source, k, v){ if (typeOf(k) == 'string') return mergeOne(source, k, v); for (var i = 1, l = arguments.length; i < l; i++){ var object = arguments[i]; for (var key in object) mergeOne(source, key, object[key]); } return source; }, /* ----- This should be simplified! ----- Generates a random ID string */ uid: function(){ return Math.random().toString(36).substr(2,10); }, /* DOM */ query: query, skipTransition: function(element, fn, bind){ var prop = prefix.js + 'TransitionProperty'; element.style[prop] = element.style.transitionProperty = 'none'; var callback = fn ? fn.call(bind || element) : null; return xtag.skipFrame(function(){ element.style[prop] = element.style.transitionProperty = ''; if (callback) callback.call(bind || element); }); }, requestFrame: (function(){ var raf = win.requestAnimationFrame || win[prefix.lowercase + 'RequestAnimationFrame'] || function(fn){ return win.setTimeout(fn, 20); }; return function(fn){ return raf(fn); }; })(), cancelFrame: (function(){ var cancel = win.cancelAnimationFrame || win[prefix.lowercase + 'CancelAnimationFrame'] || win.clearTimeout; return function(id){ return cancel(id); }; })(), skipFrame: function(fn){ var id = xtag.requestFrame(function(){ id = xtag.requestFrame(fn); }); return id; }, matchSelector: function (element, selector) { return matchSelector.call(element, selector); }, set: function (element, method, value) { element[method] = value; if (window.CustomElements) CustomElements.upgradeAll(element); }, innerHTML: function(el, html){ xtag.set(el, 'innerHTML', html); }, hasClass: function (element, klass) { return element.className.split(' ').indexOf(klass.trim())>-1; }, addClass: function (element, klass) { var list = element.className.trim().split(' '); klass.trim().split(' ').forEach(function (name) { if (!~list.indexOf(name)) list.push(name); }); element.className = list.join(' ').trim(); return element; }, removeClass: function (element, klass) { var classes = klass.trim().split(' '); element.className = element.className.trim().split(' ').filter(function (name) { return name && !~classes.indexOf(name); }).join(' '); return element; }, toggleClass: function (element, klass) { return xtag[xtag.hasClass(element, klass) ? 'removeClass' : 'addClass'].call(null, element, klass); }, /* Runs a query on only the children of an element */ queryChildren: function (element, selector) { var id = element.id, attr = '#' + (element.id = id || 'x_' + xtag.uid()) + ' > ', parent = element.parentNode || !container.appendChild(element); selector = attr + (selector + '').replace(regexReplaceCommas, ',' + attr); var result = element.parentNode.querySelectorAll(selector); if (!id) element.removeAttribute('id'); if (!parent) container.removeChild(element); return toArray(result); }, /* Creates a document fragment with the content passed in - content can be a string of HTML, an element, or an array/collection of elements */ createFragment: function(content) { var template = document.createElement('template'); if (content) { if (content.nodeName) toArray(arguments).forEach(function(e){ template.content.appendChild(e); }); else template.innerHTML = parseMultiline(content); } return document.importNode(template.content, true); }, /* Removes an element from the DOM for more performant node manipulation. The element is placed back into the DOM at the place it was taken from. */ manipulate: function(element, fn){ var next = element.nextSibling, parent = element.parentNode, returned = fn.call(element) || element; if (next) parent.insertBefore(returned, next); else parent.appendChild(returned); }, /* PSEUDOS */ applyPseudos: function(key, fn, target, source) { var listener = fn, pseudos = {}; if (key.match(':')) { var matches = [], valueFlag = 0; key.replace(regexPseudoParens, function(match){ if (match == '(') return ++valueFlag == 1 ? '\u276A' : '('; return !--valueFlag ? '\u276B' : ')'; }).replace(regexPseudoCapture, function(z, name, value, solo){ matches.push([name || solo, value]); }); var i = matches.length; while (i--) parsePseudo(function(){ var name = matches[i][0], value = matches[i][1]; if (!xtag.pseudos[name]) throw "pseudo not found: " + name + " " + value; value = (value === '' || typeof value == 'undefined') ? null : value; var pseudo = pseudos[i] = Object.create(xtag.pseudos[name]); pseudo.key = key; pseudo.name = name; pseudo.value = value; pseudo['arguments'] = (value || '').split(','); pseudo.action = pseudo.action || trueop; pseudo.source = source; pseudo.onAdd = pseudo.onAdd || noop; pseudo.onRemove = pseudo.onRemove || noop; var original = pseudo.listener = listener; listener = function(){ var output = pseudo.action.apply(this, [pseudo].concat(toArray(arguments))); if (output === null || output === false) return output; output = pseudo.listener.apply(this, arguments); pseudo.listener = original; return output; }; if (!target) pseudo.onAdd.call(fn, pseudo); else target.push(pseudo); }); } for (var z in pseudos) { if (pseudos[z].onCompiled) listener = pseudos[z].onCompiled(listener, pseudos[z]) || listener; } return listener; }, removePseudos: function(target, pseudos){ pseudos.forEach(function(obj){ obj.onRemove.call(target, obj); }); }, /*** Events ***/ parseEvent: function(type, fn) { var pseudos = type.split(':'), key = pseudos.shift(), custom = xtag.customEvents[key], event = xtag.merge({ type: key, stack: noop, condition: trueop, capture: xtag.captureEvents[key], attach: [], _attach: [], pseudos: '', _pseudos: [], onAdd: noop, onRemove: noop }, custom || {}); event.attach = toArray(event.base || event.attach); event.chain = key + (event.pseudos.length ? ':' + event.pseudos : '') + (pseudos.length ? ':' + pseudos.join(':') : ''); var stack = xtag.applyPseudos(event.chain, fn, event._pseudos, event); event.stack = function(e){ e.currentTarget = e.currentTarget || this; var detail = e.detail || {}; if (!detail.__stack__) return stack.apply(this, arguments); else if (detail.__stack__ == stack) { e.stopPropagation(); e.cancelBubble = true; return stack.apply(this, arguments); } }; event.listener = function(e){ var args = toArray(arguments), output = event.condition.apply(this, args.concat([event])); if (!output) return output; // The second condition in this IF is to address the following Blink regression: https://code.google.com/p/chromium/issues/detail?id=367537 // Remove this when affected browser builds with this regression fall below 5% marketshare if (e.type != key && (e.baseEvent && e.type != e.baseEvent.type)) { xtag.fireEvent(e.target, key, { baseEvent: e, detail: output !== true && (output.__stack__ = stack) ? output : { __stack__: stack } }); } else return event.stack.apply(this, args); }; event.attach.forEach(function(name) { event._attach.push(xtag.parseEvent(name, event.listener)); }); return event; }, addEvent: function (element, type, fn, capture) { var event = typeof fn == 'function' ? xtag.parseEvent(type, fn) : fn; event._pseudos.forEach(function(obj){ obj.onAdd.call(element, obj); }); event._attach.forEach(function(obj) { xtag.addEvent(element, obj.type, obj); }); event.onAdd.call(element, event, event.listener); element.addEventListener(event.type, event.stack, capture || event.capture); return event; }, addEvents: function (element, obj) { var events = {}; for (var z in obj) { events[z] = xtag.addEvent(element, z, obj[z]); } return events; }, removeEvent: function (element, type, event) { event = event || type; event.onRemove.call(element, event, event.listener); xtag.removePseudos(element, event._pseudos); event._attach.forEach(function(obj) { xtag.removeEvent(element, obj); }); element.removeEventListener(event.type, event.stack); }, removeEvents: function(element, obj){ for (var z in obj) xtag.removeEvent(element, obj[z]); }, fireEvent: function(element, type, options){ var event = doc.createEvent('CustomEvent'); options = options || {}; event.initCustomEvent(type, options.bubbles !== false, options.cancelable !== false, options.detail ); if (options.baseEvent) inheritEvent(event, options.baseEvent); element.dispatchEvent(event); } }; if (typeof define === 'function' && define.amd) define(xtag); else if (typeof module !== 'undefined' && module.exports) module.exports = xtag; else win.xtag = xtag; doc.addEventListener('WebComponentsReady', function(){ xtag.fireEvent(doc.body, 'DOMComponentsLoaded'); }); })();
rlugojr/cdnjs
ajax/libs/x-tag/1.5.10/x-tag-no-polyfills.js
JavaScript
mit
30,690
/* Copyright (c) 2007-2015 Contributors as noted in the AUTHORS file This file is part of libzmq, the ZeroMQ core engine in C++. libzmq is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. As a special exception, the Contributors give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you must extend this exception to your version of the library. libzmq is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "testutil.hpp" const char *bind_address = 0; const char *connect_address = 0; void test_round_robin_out (void *ctx) { void *dealer = zmq_socket (ctx, ZMQ_DEALER); assert (dealer); int rc = zmq_bind (dealer, bind_address); assert (rc == 0); const size_t services = 5; void *rep [services]; for (size_t peer = 0; peer < services; ++peer) { rep [peer] = zmq_socket (ctx, ZMQ_REP); assert (rep [peer]); int timeout = 250; rc = zmq_setsockopt (rep [peer], ZMQ_RCVTIMEO, &timeout, sizeof (int)); assert (rc == 0); rc = zmq_connect (rep [peer], connect_address); assert (rc == 0); } // Wait for connections. rc = zmq_poll (0, 0, 100); assert (rc == 0); // Send all requests for (size_t i = 0; i < services; ++i) s_send_seq (dealer, 0, "ABC", SEQ_END); // Expect every REP got one message zmq_msg_t msg; zmq_msg_init (&msg); for (size_t peer = 0; peer < services; ++peer) s_recv_seq (rep [peer], "ABC", SEQ_END); rc = zmq_msg_close (&msg); assert (rc == 0); close_zero_linger (dealer); for (size_t peer = 0; peer < services; ++peer) close_zero_linger (rep [peer]); // Wait for disconnects. rc = zmq_poll (0, 0, 100); assert (rc == 0); } void test_fair_queue_in (void *ctx) { void *receiver = zmq_socket (ctx, ZMQ_DEALER); assert (receiver); int timeout = 250; int rc = zmq_setsockopt (receiver, ZMQ_RCVTIMEO, &timeout, sizeof (int)); assert (rc == 0); rc = zmq_bind (receiver, bind_address); assert (rc == 0); const size_t services = 5; void *senders [services]; for (size_t peer = 0; peer < services; ++peer) { senders [peer] = zmq_socket (ctx, ZMQ_DEALER); assert (senders [peer]); rc = zmq_setsockopt (senders [peer], ZMQ_RCVTIMEO, &timeout, sizeof (int)); assert (rc == 0); rc = zmq_connect (senders [peer], connect_address); assert (rc == 0); } zmq_msg_t msg; rc = zmq_msg_init (&msg); assert (rc == 0); s_send_seq (senders [0], "A", SEQ_END); s_recv_seq (receiver, "A", SEQ_END); s_send_seq (senders [0], "A", SEQ_END); s_recv_seq (receiver, "A", SEQ_END); // send our requests for (size_t peer = 0; peer < services; ++peer) s_send_seq (senders [peer], "B", SEQ_END); // Wait for data. rc = zmq_poll (0, 0, 50); assert (rc == 0); // handle the requests for (size_t peer = 0; peer < services; ++peer) s_recv_seq (receiver, "B", SEQ_END); rc = zmq_msg_close (&msg); assert (rc == 0); close_zero_linger (receiver); for (size_t peer = 0; peer < services; ++peer) close_zero_linger (senders [peer]); // Wait for disconnects. rc = zmq_poll (0, 0, 100); assert (rc == 0); } void test_destroy_queue_on_disconnect (void *ctx) { void *A = zmq_socket (ctx, ZMQ_DEALER); assert (A); int rc = zmq_bind (A, bind_address); assert (rc == 0); void *B = zmq_socket (ctx, ZMQ_DEALER); assert (B); rc = zmq_connect (B, connect_address); assert (rc == 0); // Send a message in both directions s_send_seq (A, "ABC", SEQ_END); s_send_seq (B, "DEF", SEQ_END); rc = zmq_disconnect (B, connect_address); assert (rc == 0); // Disconnect may take time and need command processing. zmq_pollitem_t poller [2] = { { A, 0, 0, 0 }, { B, 0, 0, 0 } }; rc = zmq_poll (poller, 2, 100); assert (rc == 0); rc = zmq_poll (poller, 2, 100); assert (rc == 0); // No messages should be available, sending should fail. zmq_msg_t msg; zmq_msg_init (&msg); rc = zmq_send (A, 0, 0, ZMQ_DONTWAIT); assert (rc == -1); assert (errno == EAGAIN); rc = zmq_msg_recv (&msg, A, ZMQ_DONTWAIT); assert (rc == -1); assert (errno == EAGAIN); // After a reconnect of B, the messages should still be gone rc = zmq_connect (B, connect_address); assert (rc == 0); rc = zmq_msg_recv (&msg, A, ZMQ_DONTWAIT); assert (rc == -1); assert (errno == EAGAIN); rc = zmq_msg_recv (&msg, B, ZMQ_DONTWAIT); assert (rc == -1); assert (errno == EAGAIN); rc = zmq_msg_close (&msg); assert (rc == 0); close_zero_linger (A); close_zero_linger (B); // Wait for disconnects. rc = zmq_poll (0, 0, 100); assert (rc == 0); } void test_block_on_send_no_peers (void *ctx) { void *sc = zmq_socket (ctx, ZMQ_DEALER); assert (sc); int timeout = 250; int rc = zmq_setsockopt (sc, ZMQ_SNDTIMEO, &timeout, sizeof (timeout)); assert (rc == 0); rc = zmq_send (sc, 0, 0, ZMQ_DONTWAIT); assert (rc == -1); assert (errno == EAGAIN); rc = zmq_send (sc, 0, 0, 0); assert (rc == -1); assert (errno == EAGAIN); rc = zmq_close (sc); assert (rc == 0); } int main (void) { setup_test_environment(); void *ctx = zmq_ctx_new (); assert (ctx); const char *binds [] = { "inproc://a", "tcp://127.0.0.1:5555" }; const char *connects [] = { "inproc://a", "tcp://localhost:5555" }; for (int transports = 0; transports < 2; ++transports) { bind_address = binds [transports]; connect_address = connects [transports]; // SHALL route outgoing messages to available peers using a round-robin // strategy. test_round_robin_out (ctx); // SHALL receive incoming messages from its peers using a fair-queuing // strategy. test_fair_queue_in (ctx); // SHALL block on sending, or return a suitable error, when it has no connected peers. test_block_on_send_no_peers (ctx); // SHALL create a double queue when a peer connects to it. If this peer // disconnects, the DEALER socket SHALL destroy its double queue and SHALL // discard any messages it contains. // *** Test disabled until libzmq does this properly *** // test_destroy_queue_on_disconnect (ctx); } int rc = zmq_ctx_term (ctx); assert (rc == 0); return 0 ; }
madpilot78/ntopng
third-party/zeromq-4.1.7/tests/test_spec_dealer.cpp
C++
gpl-3.0
7,543
// 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. /** * @fileoverview New tab page * This is the main code for the new tab page used by touch-enabled Chrome * browsers. For now this is still a prototype. */ // Use an anonymous function to enable strict mode just for this file (which // will be concatenated with other files when embedded in Chrome cr.define('ntp', function() { 'use strict'; /** * NewTabView instance. * @type {!Object|undefined} */ var newTabView; /** * The 'notification-container' element. * @type {!Element|undefined} */ var notificationContainer; /** * If non-null, an info bubble for showing messages to the user. It points at * the Most Visited label, and is used to draw more attention to the * navigation dot UI. * @type {!Element|undefined} */ var promoBubble; /** * If non-null, an bubble confirming that the user has signed into sync. It * points at the login status at the top of the page. * @type {!Element|undefined} */ var loginBubble; /** * true if |loginBubble| should be shown. * @type {boolean} */ var shouldShowLoginBubble = false; /** * The 'other-sessions-menu-button' element. * @type {!Element|undefined} */ var otherSessionsButton; /** * The time when all sections are ready. * @type {number|undefined} * @private */ var startTime; /** * The time in milliseconds for most transitions. This should match what's * in new_tab.css. Unfortunately there's no better way to try to time * something to occur until after a transition has completed. * @type {number} * @const */ var DEFAULT_TRANSITION_TIME = 500; /** * See description for these values in ntp_stats.h. * @enum {number} */ var NtpFollowAction = { CLICKED_TILE: 11, CLICKED_OTHER_NTP_PANE: 12, OTHER: 13 }; /** * Creates a NewTabView object. NewTabView extends PageListView with * new tab UI specific logics. * @constructor * @extends {PageListView} */ function NewTabView() { var pageSwitcherStart = null; var pageSwitcherEnd = null; if (loadTimeData.getValue('showApps')) { pageSwitcherStart = getRequiredElement('page-switcher-start'); pageSwitcherEnd = getRequiredElement('page-switcher-end'); } this.initialize(getRequiredElement('page-list'), getRequiredElement('dot-list'), getRequiredElement('card-slider-frame'), getRequiredElement('trash'), pageSwitcherStart, pageSwitcherEnd); } NewTabView.prototype = { __proto__: ntp.PageListView.prototype, /** @override */ appendTilePage: function(page, title, titleIsEditable, opt_refNode) { ntp.PageListView.prototype.appendTilePage.apply(this, arguments); if (promoBubble) window.setTimeout(promoBubble.reposition.bind(promoBubble), 0); } }; /** * Invoked at startup once the DOM is available to initialize the app. */ function onLoad() { sectionsToWaitFor = 0; if (loadTimeData.getBoolean('showMostvisited')) sectionsToWaitFor++; if (loadTimeData.getBoolean('showApps')) { sectionsToWaitFor++; if (loadTimeData.getBoolean('showAppLauncherPromo')) { $('app-launcher-promo-close-button').addEventListener('click', function() { chrome.send('stopShowingAppLauncherPromo'); }); $('apps-promo-learn-more').addEventListener('click', function() { chrome.send('onLearnMore'); }); } } if (loadTimeData.getBoolean('isDiscoveryInNTPEnabled')) sectionsToWaitFor++; measureNavDots(); // Load the current theme colors. themeChanged(); newTabView = new NewTabView(); notificationContainer = getRequiredElement('notification-container'); notificationContainer.addEventListener( 'webkitTransitionEnd', onNotificationTransitionEnd); if (loadTimeData.getBoolean('showRecentlyClosed')) { cr.ui.decorate($('recently-closed-menu-button'), ntp.RecentMenuButton); chrome.send('getRecentlyClosedTabs'); } else { $('recently-closed-menu-button').hidden = true; } if (loadTimeData.getBoolean('showOtherSessionsMenu')) { otherSessionsButton = getRequiredElement('other-sessions-menu-button'); cr.ui.decorate(otherSessionsButton, ntp.OtherSessionsMenuButton); otherSessionsButton.initialize(loadTimeData.getBoolean('isUserSignedIn')); } else { getRequiredElement('other-sessions-menu-button').hidden = true; } if (loadTimeData.getBoolean('showMostvisited')) { var mostVisited = new ntp.MostVisitedPage(); // Move the footer into the most visited page if we are in "bare minimum" // mode. if (document.body.classList.contains('bare-minimum')) mostVisited.appendFooter(getRequiredElement('footer')); newTabView.appendTilePage(mostVisited, loadTimeData.getString('mostvisited'), false); chrome.send('getMostVisited'); } if (loadTimeData.getBoolean('isDiscoveryInNTPEnabled')) { var suggestionsScript = document.createElement('script'); suggestionsScript.src = 'suggestions_page.js'; suggestionsScript.onload = function() { newTabView.appendTilePage(new ntp.SuggestionsPage(), loadTimeData.getString('suggestions'), false, (newTabView.appsPages.length > 0) ? newTabView.appsPages[0] : null); chrome.send('getSuggestions'); cr.dispatchSimpleEvent(document, 'sectionready', true, true); }; document.querySelector('head').appendChild(suggestionsScript); } if (!loadTimeData.getBoolean('showWebStoreIcon')) { var webStoreIcon = $('chrome-web-store-link'); // Not all versions of the NTP have a footer, so this may not exist. if (webStoreIcon) webStoreIcon.hidden = true; } else { var webStoreLink = loadTimeData.getString('webStoreLink'); var url = appendParam(webStoreLink, 'utm_source', 'chrome-ntp-launcher'); $('chrome-web-store-link').href = url; $('chrome-web-store-link').addEventListener('click', onChromeWebStoreButtonClick); } // We need to wait for all the footer menu setup to be completed before // we can compute its layout. layoutFooter(); if (loadTimeData.getString('login_status_message')) { loginBubble = new cr.ui.Bubble; loginBubble.anchorNode = $('login-container'); loginBubble.arrowLocation = cr.ui.ArrowLocation.TOP_END; loginBubble.bubbleAlignment = cr.ui.BubbleAlignment.BUBBLE_EDGE_TO_ANCHOR_EDGE; loginBubble.deactivateToDismissDelay = 2000; loginBubble.closeButtonVisible = false; $('login-status-advanced').onclick = function() { chrome.send('showAdvancedLoginUI'); }; $('login-status-dismiss').onclick = loginBubble.hide.bind(loginBubble); var bubbleContent = $('login-status-bubble-contents'); loginBubble.content = bubbleContent; // The anchor node won't be updated until updateLogin is called so don't // show the bubble yet. shouldShowLoginBubble = true; } if (loadTimeData.valueExists('bubblePromoText')) { promoBubble = new cr.ui.Bubble; promoBubble.anchorNode = getRequiredElement('promo-bubble-anchor'); promoBubble.arrowLocation = cr.ui.ArrowLocation.BOTTOM_START; promoBubble.bubbleAlignment = cr.ui.BubbleAlignment.ENTIRELY_VISIBLE; promoBubble.deactivateToDismissDelay = 2000; promoBubble.content = parseHtmlSubset( loadTimeData.getString('bubblePromoText'), ['BR']); var bubbleLink = promoBubble.querySelector('a'); if (bubbleLink) { bubbleLink.addEventListener('click', function(e) { chrome.send('bubblePromoLinkClicked'); }); } promoBubble.handleCloseEvent = function() { promoBubble.hide(); chrome.send('bubblePromoClosed'); }; promoBubble.show(); chrome.send('bubblePromoViewed'); } var loginContainer = getRequiredElement('login-container'); loginContainer.addEventListener('click', showSyncLoginUI); if (loadTimeData.getBoolean('shouldShowSyncLogin')) chrome.send('initializeSyncLogin'); doWhenAllSectionsReady(function() { // Tell the slider about the pages. newTabView.updateSliderCards(); // Mark the current page. newTabView.cardSlider.currentCardValue.navigationDot.classList.add( 'selected'); if (loadTimeData.valueExists('notificationPromoText')) { var promoText = loadTimeData.getString('notificationPromoText'); var tags = ['IMG']; var attrs = { src: function(node, value) { return node.tagName == 'IMG' && /^data\:image\/(?:png|gif|jpe?g)/.test(value); }, }; var promo = parseHtmlSubset(promoText, tags, attrs); var promoLink = promo.querySelector('a'); if (promoLink) { promoLink.addEventListener('click', function(e) { chrome.send('notificationPromoLinkClicked'); }); } showNotification(promo, [], function() { chrome.send('notificationPromoClosed'); }, 60000); chrome.send('notificationPromoViewed'); } cr.dispatchSimpleEvent(document, 'ntpLoaded', true, true); document.documentElement.classList.remove('starting-up'); startTime = Date.now(); }); preventDefaultOnPoundLinkClicks(); // From webui/js/util.js. cr.ui.FocusManager.disableMouseFocusOnButtons(); } /** * Launches the chrome web store app with the chrome-ntp-launcher * source. * @param {Event} e The click event. */ function onChromeWebStoreButtonClick(e) { chrome.send('recordAppLaunchByURL', [encodeURIComponent(this.href), ntp.APP_LAUNCH.NTP_WEBSTORE_FOOTER]); } /* * The number of sections to wait on. * @type {number} */ var sectionsToWaitFor = -1; /** * Queued callbacks which lie in wait for all sections to be ready. * @type {array} */ var readyCallbacks = []; /** * Fired as each section of pages becomes ready. * @param {Event} e Each page's synthetic DOM event. */ document.addEventListener('sectionready', function(e) { if (--sectionsToWaitFor <= 0) { while (readyCallbacks.length) { readyCallbacks.shift()(); } } }); /** * This is used to simulate a fire-once event (i.e. $(document).ready() in * jQuery or Y.on('domready') in YUI. If all sections are ready, the callback * is fired right away. If all pages are not ready yet, the function is queued * for later execution. * @param {function} callback The work to be done when ready. */ function doWhenAllSectionsReady(callback) { assert(typeof callback == 'function'); if (sectionsToWaitFor > 0) readyCallbacks.push(callback); else window.setTimeout(callback, 0); // Do soon after, but asynchronously. } /** * Measure the width of a nav dot with a given title. * @param {string} id The loadTimeData ID of the desired title. * @return {number} The width of the nav dot. */ function measureNavDot(id) { var measuringDiv = $('fontMeasuringDiv'); measuringDiv.textContent = loadTimeData.getString(id); // The 4 is for border and padding. return Math.max(measuringDiv.clientWidth * 1.15 + 4, 80); } /** * Fills in an invisible div with the longest dot title string so that * its length may be measured and the nav dots sized accordingly. */ function measureNavDots() { var pxWidth = measureNavDot('appDefaultPageName'); if (loadTimeData.getBoolean('showMostvisited')) pxWidth = Math.max(measureNavDot('mostvisited'), pxWidth); var styleElement = document.createElement('style'); styleElement.type = 'text/css'; // max-width is used because if we run out of space, the nav dots will be // shrunk. styleElement.textContent = '.dot { max-width: ' + pxWidth + 'px; }'; document.querySelector('head').appendChild(styleElement); } /** * Layout the footer so that the nav dots stay centered. */ function layoutFooter() { // We need the image to be loaded. var logo = $('logo-img'); var logoImg = logo.querySelector('img'); if (!logoImg.complete) { logoImg.onload = layoutFooter; return; } var menu = $('footer-menu-container'); if (menu.clientWidth > logoImg.width) logo.style.WebkitFlex = '0 1 ' + menu.clientWidth + 'px'; else menu.style.WebkitFlex = '0 1 ' + logoImg.width + 'px'; } function themeChanged(opt_hasAttribution) { $('themecss').href = 'chrome://theme/css/new_tab_theme.css?' + Date.now(); if (typeof opt_hasAttribution != 'undefined') { document.documentElement.setAttribute('hasattribution', opt_hasAttribution); } updateAttribution(); } function setBookmarkBarAttached(attached) { document.documentElement.setAttribute('bookmarkbarattached', attached); } /** * Attributes the attribution image at the bottom left. */ function updateAttribution() { var attribution = $('attribution'); if (document.documentElement.getAttribute('hasattribution') == 'true') { attribution.hidden = false; } else { attribution.hidden = true; } } /** * Timeout ID. * @type {number} */ var notificationTimeout = 0; /** * Shows the notification bubble. * @param {string|Node} message The notification message or node to use as * message. * @param {Array.<{text: string, action: function()}>} links An array of * records describing the links in the notification. Each record should * have a 'text' attribute (the display string) and an 'action' attribute * (a function to run when the link is activated). * @param {Function} opt_closeHandler The callback invoked if the user * manually dismisses the notification. */ function showNotification(message, links, opt_closeHandler, opt_timeout) { window.clearTimeout(notificationTimeout); var span = document.querySelector('#notification > span'); if (typeof message == 'string') { span.textContent = message; } else { span.textContent = ''; // Remove all children. span.appendChild(message); } var linksBin = $('notificationLinks'); linksBin.textContent = ''; for (var i = 0; i < links.length; i++) { var link = linksBin.ownerDocument.createElement('div'); link.textContent = links[i].text; link.action = links[i].action; link.onclick = function() { this.action(); hideNotification(); }; link.setAttribute('role', 'button'); link.setAttribute('tabindex', 0); link.className = 'link-button'; linksBin.appendChild(link); } function closeFunc(e) { if (opt_closeHandler) opt_closeHandler(); hideNotification(); } document.querySelector('#notification button').onclick = closeFunc; document.addEventListener('dragstart', closeFunc); notificationContainer.hidden = false; showNotificationOnCurrentPage(); newTabView.cardSlider.frame.addEventListener( 'cardSlider:card_change_ended', onCardChangeEnded); var timeout = opt_timeout || 10000; notificationTimeout = window.setTimeout(hideNotification, timeout); } /** * Hide the notification bubble. */ function hideNotification() { notificationContainer.classList.add('inactive'); newTabView.cardSlider.frame.removeEventListener( 'cardSlider:card_change_ended', onCardChangeEnded); } /** * Happens when 1 or more consecutive card changes end. * @param {Event} e The cardSlider:card_change_ended event. */ function onCardChangeEnded(e) { // If we ended on the same page as we started, ignore. if (newTabView.cardSlider.currentCardValue.notification) return; // Hide the notification the old page. notificationContainer.classList.add('card-changed'); showNotificationOnCurrentPage(); } /** * Move and show the notification on the current page. */ function showNotificationOnCurrentPage() { var page = newTabView.cardSlider.currentCardValue; doWhenAllSectionsReady(function() { if (page != newTabView.cardSlider.currentCardValue) return; // NOTE: This moves the notification to inside of the current page. page.notification = notificationContainer; // Reveal the notification and instruct it to hide itself if ignored. notificationContainer.classList.remove('inactive'); // Gives the browser time to apply this rule before we remove it (causing // a transition). window.setTimeout(function() { notificationContainer.classList.remove('card-changed'); }, 0); }); } /** * When done fading out, set hidden to true so the notification can't be * tabbed to or clicked. * @param {Event} e The webkitTransitionEnd event. */ function onNotificationTransitionEnd(e) { if (notificationContainer.classList.contains('inactive')) notificationContainer.hidden = true; } function setRecentlyClosedTabs(dataItems) { $('recently-closed-menu-button').dataItems = dataItems; layoutFooter(); } function setMostVisitedPages(data, hasBlacklistedUrls) { newTabView.mostVisitedPage.data = data; cr.dispatchSimpleEvent(document, 'sectionready', true, true); } function setSuggestionsPages(data, hasBlacklistedUrls) { newTabView.suggestionsPage.data = data; } /** * Set the dominant color for a node. This will be called in response to * getFaviconDominantColor. The node represented by |id| better have a setter * for stripeColor. * @param {string} id The ID of a node. * @param {string} color The color represented as a CSS string. */ function setFaviconDominantColor(id, color) { var node = $(id); if (node) node.stripeColor = color; } /** * Updates the text displayed in the login container. If there is no text then * the login container is hidden. * @param {string} loginHeader The first line of text. * @param {string} loginSubHeader The second line of text. * @param {string} iconURL The url for the login status icon. If this is null then the login status icon is hidden. * @param {boolean} isUserSignedIn Indicates if the user is signed in or not. */ function updateLogin(loginHeader, loginSubHeader, iconURL, isUserSignedIn) { if (loginHeader || loginSubHeader) { $('login-container').hidden = false; $('login-status-header').innerHTML = loginHeader; $('login-status-sub-header').innerHTML = loginSubHeader; $('card-slider-frame').classList.add('showing-login-area'); if (iconURL) { $('login-status-header-container').style.backgroundImage = url(iconURL); $('login-status-header-container').classList.add('login-status-icon'); } else { $('login-status-header-container').style.backgroundImage = 'none'; $('login-status-header-container').classList.remove( 'login-status-icon'); } } else { $('login-container').hidden = true; $('card-slider-frame').classList.remove('showing-login-area'); } if (shouldShowLoginBubble) { window.setTimeout(loginBubble.show.bind(loginBubble), 0); chrome.send('loginMessageSeen'); shouldShowLoginBubble = false; } else if (loginBubble) { loginBubble.reposition(); } if (otherSessionsButton) { otherSessionsButton.updateSignInState(isUserSignedIn); layoutFooter(); } } /** * Show the sync login UI. * @param {Event} e The click event. */ function showSyncLoginUI(e) { var rect = e.currentTarget.getBoundingClientRect(); chrome.send('showSyncLoginUI', [rect.left, rect.top, rect.width, rect.height]); } /** * Logs the time to click for the specified item. * @param {string} item The item to log the time-to-click. */ function logTimeToClick(item) { var timeToClick = Date.now() - startTime; chrome.send('logTimeToClick', ['NewTabPage.TimeToClick' + item, timeToClick]); } /** * Wrappers to forward the callback to corresponding PageListView member. */ function appAdded() { return newTabView.appAdded.apply(newTabView, arguments); } function appMoved() { return newTabView.appMoved.apply(newTabView, arguments); } function appRemoved() { return newTabView.appRemoved.apply(newTabView, arguments); } function appsPrefChangeCallback() { return newTabView.appsPrefChangedCallback.apply(newTabView, arguments); } function appLauncherPromoPrefChangeCallback() { return newTabView.appLauncherPromoPrefChangeCallback.apply(newTabView, arguments); } function appsReordered() { return newTabView.appsReordered.apply(newTabView, arguments); } function enterRearrangeMode() { return newTabView.enterRearrangeMode.apply(newTabView, arguments); } function setForeignSessions(sessionList, isTabSyncEnabled) { if (otherSessionsButton) { otherSessionsButton.setForeignSessions(sessionList, isTabSyncEnabled); layoutFooter(); } } function getAppsCallback() { return newTabView.getAppsCallback.apply(newTabView, arguments); } function getAppsPageIndex() { return newTabView.getAppsPageIndex.apply(newTabView, arguments); } function getCardSlider() { return newTabView.cardSlider; } function leaveRearrangeMode() { return newTabView.leaveRearrangeMode.apply(newTabView, arguments); } function saveAppPageName() { return newTabView.saveAppPageName.apply(newTabView, arguments); } function setAppToBeHighlighted(appId) { newTabView.highlightAppId = appId; } // Return an object with all the exports return { appAdded: appAdded, appMoved: appMoved, appRemoved: appRemoved, appsPrefChangeCallback: appsPrefChangeCallback, appLauncherPromoPrefChangeCallback: appLauncherPromoPrefChangeCallback, enterRearrangeMode: enterRearrangeMode, getAppsCallback: getAppsCallback, getAppsPageIndex: getAppsPageIndex, getCardSlider: getCardSlider, onLoad: onLoad, leaveRearrangeMode: leaveRearrangeMode, logTimeToClick: logTimeToClick, NtpFollowAction: NtpFollowAction, saveAppPageName: saveAppPageName, setAppToBeHighlighted: setAppToBeHighlighted, setBookmarkBarAttached: setBookmarkBarAttached, setForeignSessions: setForeignSessions, setMostVisitedPages: setMostVisitedPages, setSuggestionsPages: setSuggestionsPages, setRecentlyClosedTabs: setRecentlyClosedTabs, setFaviconDominantColor: setFaviconDominantColor, showNotification: showNotification, themeChanged: themeChanged, updateLogin: updateLogin }; }); document.addEventListener('DOMContentLoaded', ntp.onLoad); var toCssPx = cr.ui.toCssPx;
s20121035/rk3288_android5.1_repo
external/chromium_org/chrome/browser/resources/ntp4/new_tab.js
JavaScript
gpl-3.0
23,568
/*-----------------------------------------------------------------------------+ Copyright (c) 2007-2012: Joachim Faulhaber Copyright (c) 1999-2006: Cortex Software GmbH, Kantstrasse 57, Berlin +------------------------------------------------------------------------------+ Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENCE.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +-----------------------------------------------------------------------------*/ #ifndef BOOST_ICL_INTERVAL_BASE_MAP_HPP_JOFA_990223 #define BOOST_ICL_INTERVAL_BASE_MAP_HPP_JOFA_990223 #include <limits> #include <boost/type_traits/ice.hpp> #include <boost/mpl/and.hpp> #include <boost/mpl/or.hpp> #include <boost/mpl/not.hpp> #include <boost/icl/detail/notate.hpp> #include <boost/icl/detail/design_config.hpp> #include <boost/icl/detail/on_absorbtion.hpp> #include <boost/icl/detail/interval_map_algo.hpp> #include <boost/icl/associative_interval_container.hpp> #include <boost/icl/type_traits/is_interval_splitter.hpp> #include <boost/icl/map.hpp> namespace boost{namespace icl { template<class DomainT, class CodomainT> struct mapping_pair { DomainT key; CodomainT data; mapping_pair():key(), data(){} mapping_pair(const DomainT& key_value, const CodomainT& data_value) :key(key_value), data(data_value){} mapping_pair(const std::pair<DomainT,CodomainT>& std_pair) :key(std_pair.first), data(std_pair.second){} }; /** \brief Implements a map as a map of intervals (base class) */ template < class SubType, typename DomainT, typename CodomainT, class Traits = icl::partial_absorber, ICL_COMPARE Compare = ICL_COMPARE_INSTANCE(ICL_COMPARE_DEFAULT, DomainT), ICL_COMBINE Combine = ICL_COMBINE_INSTANCE(icl::inplace_plus, CodomainT), ICL_SECTION Section = ICL_SECTION_INSTANCE(icl::inter_section, CodomainT), ICL_INTERVAL(ICL_COMPARE) Interval = ICL_INTERVAL_INSTANCE(ICL_INTERVAL_DEFAULT, DomainT, Compare), ICL_ALLOC Alloc = std::allocator > class interval_base_map { public: //========================================================================== //= Associated types //========================================================================== typedef interval_base_map<SubType,DomainT,CodomainT, Traits,Compare,Combine,Section,Interval,Alloc> type; /// The designated \e derived or \e sub_type of this base class typedef SubType sub_type; /// Auxilliary type for overloadresolution typedef type overloadable_type; /// Traits of an itl map typedef Traits traits; //-------------------------------------------------------------------------- //- Associated types: Related types //-------------------------------------------------------------------------- /// The atomized type representing the corresponding container of elements typedef typename icl::map<DomainT,CodomainT, Traits,Compare,Combine,Section,Alloc> atomized_type; //-------------------------------------------------------------------------- //- Associated types: Data //-------------------------------------------------------------------------- /// Domain type (type of the keys) of the map typedef DomainT domain_type; typedef typename boost::call_traits<DomainT>::param_type domain_param; /// Domain type (type of the keys) of the map typedef CodomainT codomain_type; /// Auxiliary type to help the compiler resolve ambiguities when using std::make_pair typedef mapping_pair<domain_type,codomain_type> domain_mapping_type; /// Conceptual is a map a set of elements of type \c element_type typedef domain_mapping_type element_type; /// The interval type of the map typedef ICL_INTERVAL_TYPE(Interval,DomainT,Compare) interval_type; /// Auxiliary type for overload resolution typedef std::pair<interval_type,CodomainT> interval_mapping_type; /// Type of an interval containers segment, that is spanned by an interval typedef std::pair<interval_type,CodomainT> segment_type; //-------------------------------------------------------------------------- //- Associated types: Size //-------------------------------------------------------------------------- /// The difference type of an interval which is sometimes different form the domain_type typedef typename difference_type_of<domain_type>::type difference_type; /// The size type of an interval which is mostly std::size_t typedef typename size_type_of<domain_type>::type size_type; //-------------------------------------------------------------------------- //- Associated types: Functors //-------------------------------------------------------------------------- /// Comparison functor for domain values typedef ICL_COMPARE_DOMAIN(Compare,DomainT) domain_compare; typedef ICL_COMPARE_DOMAIN(Compare,segment_type) segment_compare; /// Combine functor for codomain value aggregation typedef ICL_COMBINE_CODOMAIN(Combine,CodomainT) codomain_combine; /// Inverse Combine functor for codomain value aggregation typedef typename inverse<codomain_combine>::type inverse_codomain_combine; /// Intersection functor for codomain values typedef typename mpl::if_ <has_set_semantics<codomain_type> , ICL_SECTION_CODOMAIN(Section,CodomainT) , codomain_combine >::type codomain_intersect; /// Inverse Combine functor for codomain value intersection typedef typename inverse<codomain_intersect>::type inverse_codomain_intersect; /// Comparison functor for intervals which are keys as well typedef exclusive_less_than<interval_type> interval_compare; /// Comparison functor for keys typedef exclusive_less_than<interval_type> key_compare; //-------------------------------------------------------------------------- //- Associated types: Implementation and stl related //-------------------------------------------------------------------------- /// The allocator type of the set typedef Alloc<std::pair<const interval_type, codomain_type> > allocator_type; /// Container type for the implementation typedef ICL_IMPL_SPACE::map<interval_type,codomain_type, key_compare,allocator_type> ImplMapT; /// key type of the implementing container typedef typename ImplMapT::key_type key_type; /// value type of the implementing container typedef typename ImplMapT::value_type value_type; /// data type of the implementing container typedef typename ImplMapT::value_type::second_type data_type; /// pointer type typedef typename ImplMapT::pointer pointer; /// const pointer type typedef typename ImplMapT::const_pointer const_pointer; /// reference type typedef typename ImplMapT::reference reference; /// const reference type typedef typename ImplMapT::const_reference const_reference; /// iterator for iteration over intervals typedef typename ImplMapT::iterator iterator; /// const_iterator for iteration over intervals typedef typename ImplMapT::const_iterator const_iterator; /// iterator for reverse iteration over intervals typedef typename ImplMapT::reverse_iterator reverse_iterator; /// const_iterator for iteration over intervals typedef typename ImplMapT::const_reverse_iterator const_reverse_iterator; /// element iterator: Depreciated, see documentation. typedef boost::icl::element_iterator<iterator> element_iterator; /// const element iterator: Depreciated, see documentation. typedef boost::icl::element_iterator<const_iterator> element_const_iterator; /// element reverse iterator: Depreciated, see documentation. typedef boost::icl::element_iterator<reverse_iterator> element_reverse_iterator; /// element const reverse iterator: Depreciated, see documentation. typedef boost::icl::element_iterator<const_reverse_iterator> element_const_reverse_iterator; typedef typename on_absorbtion<type, codomain_combine, Traits::absorbs_identities>::type on_codomain_absorbtion; public: BOOST_STATIC_CONSTANT(bool, is_total_invertible = ( Traits::is_total && has_inverse<codomain_type>::value)); BOOST_STATIC_CONSTANT(int, fineness = 0); public: //========================================================================== //= Construct, copy, destruct //========================================================================== /** Default constructor for the empty object */ interval_base_map() { BOOST_CONCEPT_ASSERT((DefaultConstructibleConcept<DomainT>)); BOOST_CONCEPT_ASSERT((LessThanComparableConcept<DomainT>)); BOOST_CONCEPT_ASSERT((DefaultConstructibleConcept<CodomainT>)); BOOST_CONCEPT_ASSERT((EqualComparableConcept<CodomainT>)); } /** Copy constructor */ interval_base_map(const interval_base_map& src): _map(src._map) { BOOST_CONCEPT_ASSERT((DefaultConstructibleConcept<DomainT>)); BOOST_CONCEPT_ASSERT((LessThanComparableConcept<DomainT>)); BOOST_CONCEPT_ASSERT((DefaultConstructibleConcept<CodomainT>)); BOOST_CONCEPT_ASSERT((EqualComparableConcept<CodomainT>)); } /** Copy assignment operator */ interval_base_map& operator = (const interval_base_map& src) { this->_map = src._map; return *this; } # ifndef BOOST_NO_RVALUE_REFERENCES //========================================================================== //= Move semantics //========================================================================== /** Move constructor */ interval_base_map(interval_base_map&& src): _map(boost::move(src._map)) { BOOST_CONCEPT_ASSERT((DefaultConstructibleConcept<DomainT>)); BOOST_CONCEPT_ASSERT((LessThanComparableConcept<DomainT>)); BOOST_CONCEPT_ASSERT((DefaultConstructibleConcept<CodomainT>)); BOOST_CONCEPT_ASSERT((EqualComparableConcept<CodomainT>)); } /** Move assignment operator */ interval_base_map& operator = (interval_base_map&& src) { this->_map = boost::move(src._map); return *this; } //========================================================================== # endif // BOOST_NO_RVALUE_REFERENCES /** swap the content of containers */ void swap(interval_base_map& object) { _map.swap(object._map); } //========================================================================== //= Containedness //========================================================================== /** clear the map */ void clear() { icl::clear(*that()); } /** is the map empty? */ bool empty()const { return icl::is_empty(*that()); } //========================================================================== //= Size //========================================================================== /** An interval map's size is it's cardinality */ size_type size()const { return icl::cardinality(*that()); } /** Size of the iteration over this container */ std::size_t iterative_size()const { return _map.size(); } //========================================================================== //= Selection //========================================================================== /** Find the interval value pair, that contains \c key */ const_iterator find(const domain_type& key_value)const { return icl::find(*this, key_value); } /** Find the first interval value pair, that collides with interval \c key_interval */ const_iterator find(const interval_type& key_interval)const { return _map.find(key_interval); } /** Total select function. */ codomain_type operator()(const domain_type& key_value)const { const_iterator it_ = icl::find(*this, key_value); return it_==end() ? identity_element<codomain_type>::value() : (*it_).second; } //========================================================================== //= Addition //========================================================================== /** Addition of a key value pair to the map */ SubType& add(const element_type& key_value_pair) { return icl::add(*that(), key_value_pair); } /** Addition of an interval value pair to the map. */ SubType& add(const segment_type& interval_value_pair) { this->template _add<codomain_combine>(interval_value_pair); return *that(); } /** Addition of an interval value pair \c interval_value_pair to the map. Iterator \c prior_ is a hint to the position \c interval_value_pair can be inserted after. */ iterator add(iterator prior_, const segment_type& interval_value_pair) { return this->template _add<codomain_combine>(prior_, interval_value_pair); } //========================================================================== //= Subtraction //========================================================================== /** Subtraction of a key value pair from the map */ SubType& subtract(const element_type& key_value_pair) { return icl::subtract(*that(), key_value_pair); } /** Subtraction of an interval value pair from the map. */ SubType& subtract(const segment_type& interval_value_pair) { on_invertible<type, is_total_invertible> ::subtract(*that(), interval_value_pair); return *that(); } //========================================================================== //= Insertion //========================================================================== /** Insertion of a \c key_value_pair into the map. */ SubType& insert(const element_type& key_value_pair) { return icl::insert(*that(), key_value_pair); } /** Insertion of an \c interval_value_pair into the map. */ SubType& insert(const segment_type& interval_value_pair) { _insert(interval_value_pair); return *that(); } /** Insertion of an \c interval_value_pair into the map. Iterator \c prior_. serves as a hint to insert after the element \c prior point to. */ iterator insert(iterator prior, const segment_type& interval_value_pair) { return _insert(prior, interval_value_pair); } /** With <tt>key_value_pair = (k,v)</tt> set value \c v for key \c k */ SubType& set(const element_type& key_value_pair) { return icl::set_at(*that(), key_value_pair); } /** With <tt>interval_value_pair = (I,v)</tt> set value \c v for all keys in interval \c I in the map. */ SubType& set(const segment_type& interval_value_pair) { return icl::set_at(*that(), interval_value_pair); } //========================================================================== //= Erasure //========================================================================== /** Erase a \c key_value_pair from the map. */ SubType& erase(const element_type& key_value_pair) { icl::erase(*that(), key_value_pair); return *that(); } /** Erase an \c interval_value_pair from the map. */ SubType& erase(const segment_type& interval_value_pair); /** Erase a key value pair for \c key. */ SubType& erase(const domain_type& key) { return icl::erase(*that(), key); } /** Erase all value pairs within the range of the interval <tt>inter_val</tt> from the map. */ SubType& erase(const interval_type& inter_val); /** Erase all value pairs within the range of the interval that iterator \c position points to. */ void erase(iterator position){ this->_map.erase(position); } /** Erase all value pairs for a range of iterators <tt>[first,past)</tt>. */ void erase(iterator first, iterator past){ this->_map.erase(first, past); } //========================================================================== //= Intersection //========================================================================== /** The intersection of \c interval_value_pair and \c *this map is added to \c section. */ void add_intersection(SubType& section, const segment_type& interval_value_pair)const { on_definedness<SubType, Traits::is_total> ::add_intersection(section, *that(), interval_value_pair); } //========================================================================== //= Symmetric difference //========================================================================== /** If \c *this map contains \c key_value_pair it is erased, otherwise it is added. */ SubType& flip(const element_type& key_value_pair) { return icl::flip(*that(), key_value_pair); } /** If \c *this map contains \c interval_value_pair it is erased, otherwise it is added. */ SubType& flip(const segment_type& interval_value_pair) { on_total_absorbable<SubType, Traits::is_total, Traits::absorbs_identities> ::flip(*that(), interval_value_pair); return *that(); } //========================================================================== //= Iterator related //========================================================================== iterator lower_bound(const key_type& interval) { return _map.lower_bound(interval); } iterator upper_bound(const key_type& interval) { return _map.upper_bound(interval); } const_iterator lower_bound(const key_type& interval)const { return _map.lower_bound(interval); } const_iterator upper_bound(const key_type& interval)const { return _map.upper_bound(interval); } std::pair<iterator,iterator> equal_range(const key_type& interval) { return std::pair<iterator,iterator> (lower_bound(interval), upper_bound(interval)); } std::pair<const_iterator,const_iterator> equal_range(const key_type& interval)const { return std::pair<const_iterator,const_iterator> (lower_bound(interval), upper_bound(interval)); } iterator begin() { return _map.begin(); } iterator end() { return _map.end(); } const_iterator begin()const { return _map.begin(); } const_iterator end()const { return _map.end(); } reverse_iterator rbegin() { return _map.rbegin(); } reverse_iterator rend() { return _map.rend(); } const_reverse_iterator rbegin()const { return _map.rbegin(); } const_reverse_iterator rend()const { return _map.rend(); } private: template<class Combiner> iterator _add(const segment_type& interval_value_pair); template<class Combiner> iterator _add(iterator prior_, const segment_type& interval_value_pair); template<class Combiner> void _subtract(const segment_type& interval_value_pair); iterator _insert(const segment_type& interval_value_pair); iterator _insert(iterator prior_, const segment_type& interval_value_pair); private: template<class Combiner> void add_segment(const interval_type& inter_val, const CodomainT& co_val, iterator& it_); template<class Combiner> void add_main(interval_type& inter_val, const CodomainT& co_val, iterator& it_, const iterator& last_); template<class Combiner> void add_rear(const interval_type& inter_val, const CodomainT& co_val, iterator& it_); void add_front(const interval_type& inter_val, iterator& first_); private: void subtract_front(const interval_type& inter_val, iterator& first_); template<class Combiner> void subtract_main(const CodomainT& co_val, iterator& it_, const iterator& last_); template<class Combiner> void subtract_rear(interval_type& inter_val, const CodomainT& co_val, iterator& it_); private: void insert_main(const interval_type&, const CodomainT&, iterator&, const iterator&); void erase_rest ( interval_type&, const CodomainT&, iterator&, const iterator&); template<class FragmentT> void total_add_intersection(SubType& section, const FragmentT& fragment)const { section += *that(); section.add(fragment); } void partial_add_intersection(SubType& section, const segment_type& operand)const { interval_type inter_val = operand.first; if(icl::is_empty(inter_val)) return; std::pair<const_iterator, const_iterator> exterior = equal_range(inter_val); if(exterior.first == exterior.second) return; for(const_iterator it_=exterior.first; it_ != exterior.second; it_++) { interval_type common_interval = (*it_).first & inter_val; if(!icl::is_empty(common_interval)) { section.template _add<codomain_combine> (value_type(common_interval, (*it_).second) ); section.template _add<codomain_intersect>(value_type(common_interval, operand.second)); } } } void partial_add_intersection(SubType& section, const element_type& operand)const { partial_add_intersection(section, make_segment<type>(operand)); } protected: template <class Combiner> iterator gap_insert(iterator prior_, const interval_type& inter_val, const codomain_type& co_val ) { // inter_val is not conained in this map. Insertion will be successful BOOST_ASSERT(this->_map.find(inter_val) == this->_map.end()); BOOST_ASSERT((!on_absorbtion<type,Combiner,Traits::absorbs_identities>::is_absorbable(co_val))); return this->_map.insert(prior_, value_type(inter_val, version<Combiner>()(co_val))); } template <class Combiner> std::pair<iterator, bool> add_at(const iterator& prior_, const interval_type& inter_val, const codomain_type& co_val ) { // Never try to insert an identity element into an identity element absorber here: BOOST_ASSERT((!(on_absorbtion<type,Combiner,Traits::absorbs_identities>::is_absorbable(co_val)))); iterator inserted_ = this->_map.insert(prior_, value_type(inter_val, Combiner::identity_element())); if((*inserted_).first == inter_val && (*inserted_).second == Combiner::identity_element()) { Combiner()((*inserted_).second, co_val); return std::pair<iterator,bool>(inserted_, true); } else return std::pair<iterator,bool>(inserted_, false); } std::pair<iterator, bool> insert_at(const iterator& prior_, const interval_type& inter_val, const codomain_type& co_val ) { iterator inserted_ = this->_map.insert(prior_, value_type(inter_val, co_val)); if(inserted_ == prior_) return std::pair<iterator,bool>(inserted_, false); else if((*inserted_).first == inter_val) return std::pair<iterator,bool>(inserted_, true); else return std::pair<iterator,bool>(inserted_, false); } protected: sub_type* that() { return static_cast<sub_type*>(this); } const sub_type* that()const { return static_cast<const sub_type*>(this); } protected: ImplMapT _map; private: //-------------------------------------------------------------------------- template<class Type, bool is_total_invertible> struct on_invertible; template<class Type> struct on_invertible<Type, true> { typedef typename Type::segment_type segment_type; typedef typename Type::inverse_codomain_combine inverse_codomain_combine; static void subtract(Type& object, const segment_type& operand) { object.template _add<inverse_codomain_combine>(operand); } }; template<class Type> struct on_invertible<Type, false> { typedef typename Type::segment_type segment_type; typedef typename Type::inverse_codomain_combine inverse_codomain_combine; static void subtract(Type& object, const segment_type& operand) { object.template _subtract<inverse_codomain_combine>(operand); } }; friend struct on_invertible<type, true>; friend struct on_invertible<type, false>; //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- template<class Type, bool is_total> struct on_definedness; template<class Type> struct on_definedness<Type, true> { static void add_intersection(Type& section, const Type& object, const segment_type& operand) { object.total_add_intersection(section, operand); } }; template<class Type> struct on_definedness<Type, false> { static void add_intersection(Type& section, const Type& object, const segment_type& operand) { object.partial_add_intersection(section, operand); } }; friend struct on_definedness<type, true>; friend struct on_definedness<type, false>; //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- template<class Type, bool has_set_semantics> struct on_codomain_model; template<class Type> struct on_codomain_model<Type, true> { typedef typename Type::interval_type interval_type; typedef typename Type::codomain_type codomain_type; typedef typename Type::segment_type segment_type; typedef typename Type::codomain_combine codomain_combine; typedef typename Type::inverse_codomain_intersect inverse_codomain_intersect; static void add(Type& intersection, interval_type& common_interval, const codomain_type& flip_value, const codomain_type& co_value) { codomain_type common_value = flip_value; inverse_codomain_intersect()(common_value, co_value); intersection.template _add<codomain_combine>(segment_type(common_interval, common_value)); } }; template<class Type> struct on_codomain_model<Type, false> { typedef typename Type::interval_type interval_type; typedef typename Type::codomain_type codomain_type; typedef typename Type::segment_type segment_type; typedef typename Type::codomain_combine codomain_combine; static void add(Type& intersection, interval_type& common_interval, const codomain_type&, const codomain_type&) { intersection.template _add<codomain_combine>(segment_type(common_interval, identity_element<codomain_type>::value())); } }; friend struct on_codomain_model<type, true>; friend struct on_codomain_model<type, false>; //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- template<class Type, bool is_total, bool absorbs_identities> struct on_total_absorbable; template<class Type> struct on_total_absorbable<Type, true, true> { static void flip(Type& object, const typename Type::segment_type&) { icl::clear(object); } }; #ifdef BOOST_MSVC #pragma warning(push) #pragma warning(disable:4127) // conditional expression is constant #endif template<class Type> struct on_total_absorbable<Type, true, false> { typedef typename Type::segment_type segment_type; typedef typename Type::codomain_type codomain_type; static void flip(Type& object, const segment_type& operand) { object += operand; ICL_FORALL(typename Type, it_, object) (*it_).second = identity_element<codomain_type>::value(); if(mpl::not_<is_interval_splitter<Type> >::value) icl::join(object); } }; #ifdef BOOST_MSVC #pragma warning(pop) #endif template<class Type, bool absorbs_identities> struct on_total_absorbable<Type, false, absorbs_identities> { typedef typename Type::segment_type segment_type; typedef typename Type::codomain_type codomain_type; typedef typename Type::interval_type interval_type; typedef typename Type::value_type value_type; typedef typename Type::const_iterator const_iterator; typedef typename Type::set_type set_type; typedef typename Type::inverse_codomain_intersect inverse_codomain_intersect; static void flip(Type& object, const segment_type& interval_value_pair) { // That which is common shall be subtracted // That which is not shall be added // So interval_value_pair has to be 'complementary added' or flipped interval_type span = interval_value_pair.first; std::pair<const_iterator, const_iterator> exterior = object.equal_range(span); const_iterator first_ = exterior.first; const_iterator end_ = exterior.second; interval_type covered, left_over, common_interval; const codomain_type& x_value = interval_value_pair.second; const_iterator it_ = first_; set_type eraser; Type intersection; while(it_ != end_ ) { const codomain_type& co_value = (*it_).second; covered = (*it_++).first; //[a ... : span // [b ... : covered //[a b) : left_over left_over = right_subtract(span, covered); //That which is common ... common_interval = span & covered; if(!icl::is_empty(common_interval)) { // ... shall be subtracted icl::add(eraser, common_interval); on_codomain_model<Type, has_set_semantics<codomain_type>::value> ::add(intersection, common_interval, x_value, co_value); } icl::add(object, value_type(left_over, x_value)); //That which is not shall be added // Because this is a collision free addition I don't have to distinguish codomain_types. //... d) : span //... c) : covered // [c d) : span' span = left_subtract(span, covered); } //If span is not empty here, it is not in the set so it shall be added icl::add(object, value_type(span, x_value)); //finally rewrite the common segments icl::erase(object, eraser); object += intersection; } }; //-------------------------------------------------------------------------- } ; //============================================================================== //= Addition detail //============================================================================== template <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc> inline void interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> ::add_front(const interval_type& inter_val, iterator& first_) { // If the collision sequence has a left residual 'left_resid' it will // be split, to provide a standardized start of algorithms: // The addend interval 'inter_val' covers the beginning of the collision sequence. // only for the first there can be a left_resid: a part of *first_ left of inter_val interval_type left_resid = right_subtract((*first_).first, inter_val); if(!icl::is_empty(left_resid)) { // [------------ . . . // [left_resid---first_ --- . . . iterator prior_ = cyclic_prior(*this, first_); const_cast<interval_type&>((*first_).first) = left_subtract((*first_).first, left_resid); //NOTE: Only splitting this->_map.insert(prior_, segment_type(left_resid, (*first_).second)); } //POST: // [----- inter_val ---- . . . // ...[-- first_ --... } template <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc> template<class Combiner> inline void interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> ::add_segment(const interval_type& inter_val, const CodomainT& co_val, iterator& it_) { interval_type lead_gap = right_subtract(inter_val, (*it_).first); if(!icl::is_empty(lead_gap)) { // [lead_gap--- . . . // [-- it_ ... iterator prior_ = prior(it_); iterator inserted_ = this->template gap_insert<Combiner>(prior_, lead_gap, co_val); that()->handle_inserted(prior_, inserted_); } // . . . --------- . . . addend interval // [-- it_ --) has a common part with the first overval Combiner()((*it_).second, co_val); that()->template handle_left_combined<Combiner>(it_++); } template <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc> template<class Combiner> inline void interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> ::add_main(interval_type& inter_val, const CodomainT& co_val, iterator& it_, const iterator& last_) { interval_type cur_interval; while(it_!=last_) { cur_interval = (*it_).first ; add_segment<Combiner>(inter_val, co_val, it_); // shrink interval inter_val = left_subtract(inter_val, cur_interval); } } template <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc> template<class Combiner> inline void interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> ::add_rear(const interval_type& inter_val, const CodomainT& co_val, iterator& it_) { iterator prior_ = cyclic_prior(*that(), it_); interval_type cur_itv = (*it_).first ; interval_type lead_gap = right_subtract(inter_val, cur_itv); if(!icl::is_empty(lead_gap)) { // [lead_gap--- . . . // [prior) [-- it_ ... iterator inserted_ = this->template gap_insert<Combiner>(prior_, lead_gap, co_val); that()->handle_inserted(prior_, inserted_); } interval_type end_gap = left_subtract(inter_val, cur_itv); if(!icl::is_empty(end_gap)) { // [----------------end_gap) // . . . -- it_ --) Combiner()((*it_).second, co_val); that()->template gap_insert_at<Combiner>(it_, prior_, end_gap, co_val); } else { // only for the last there can be a right_resid: a part of *it_ right of x interval_type right_resid = left_subtract(cur_itv, inter_val); if(icl::is_empty(right_resid)) { // [---------------) // [-- it_ ---) Combiner()((*it_).second, co_val); that()->template handle_preceeded_combined<Combiner>(prior_, it_); } else { // [--------------) // [-- it_ --right_resid) const_cast<interval_type&>((*it_).first) = right_subtract((*it_).first, right_resid); //NOTE: This is NOT an insertion that has to take care for correct application of // the Combiner functor. It only reestablished that state after splitting the // 'it_' interval value pair. Using _map_insert<Combiner> does not work here. iterator insertion_ = this->_map.insert(it_, value_type(right_resid, (*it_).second)); that()->handle_reinserted(insertion_); Combiner()((*it_).second, co_val); that()->template handle_preceeded_combined<Combiner>(insertion_, it_); } } } //============================================================================== //= Addition //============================================================================== template <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc> template<class Combiner> inline typename interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc>::iterator interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> ::_add(const segment_type& addend) { typedef typename on_absorbtion<type,Combiner, absorbs_identities<type>::value>::type on_absorbtion_; const interval_type& inter_val = addend.first; if(icl::is_empty(inter_val)) return this->_map.end(); const codomain_type& co_val = addend.second; if(on_absorbtion_::is_absorbable(co_val)) return this->_map.end(); std::pair<iterator,bool> insertion = this->_map.insert(value_type(inter_val, version<Combiner>()(co_val))); if(insertion.second) return that()->handle_inserted(insertion.first); else { // Detect the first and the end iterator of the collision sequence iterator first_ = this->_map.lower_bound(inter_val), last_ = insertion.first; //assert(end_ == this->_map.upper_bound(inter_val)); iterator it_ = first_; interval_type rest_interval = inter_val; add_front (rest_interval, it_ ); add_main<Combiner>(rest_interval, co_val, it_, last_); add_rear<Combiner>(rest_interval, co_val, it_ ); return it_; } } template <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc> template<class Combiner> inline typename interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc>::iterator interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> ::_add(iterator prior_, const segment_type& addend) { typedef typename on_absorbtion<type,Combiner, absorbs_identities<type>::value>::type on_absorbtion_; const interval_type& inter_val = addend.first; if(icl::is_empty(inter_val)) return prior_; const codomain_type& co_val = addend.second; if(on_absorbtion_::is_absorbable(co_val)) return prior_; std::pair<iterator,bool> insertion = add_at<Combiner>(prior_, inter_val, co_val); if(insertion.second) return that()->handle_inserted(insertion.first); else { // Detect the first and the end iterator of the collision sequence std::pair<iterator,iterator> overlap = equal_range(inter_val); iterator it_ = overlap.first, last_ = prior(overlap.second); interval_type rest_interval = inter_val; add_front (rest_interval, it_ ); add_main<Combiner>(rest_interval, co_val, it_, last_); add_rear<Combiner>(rest_interval, co_val, it_ ); return it_; } } //============================================================================== //= Subtraction detail //============================================================================== template <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc> inline void interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> ::subtract_front(const interval_type& inter_val, iterator& it_) { interval_type left_resid = right_subtract((*it_).first, inter_val); if(!icl::is_empty(left_resid)) // [--- inter_val ---) { //[prior_) [left_resid)[--- it_ . . . iterator prior_ = cyclic_prior(*this, it_); const_cast<interval_type&>((*it_).first) = left_subtract((*it_).first, left_resid); this->_map.insert(prior_, value_type(left_resid, (*it_).second)); // The segemnt *it_ is split at inter_val.first(), so as an invariant // segment *it_ is always "under" inter_val and a left_resid is empty. } } template <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc> template<class Combiner> inline void interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> ::subtract_main(const CodomainT& co_val, iterator& it_, const iterator& last_) { while(it_ != last_) { Combiner()((*it_).second, co_val); that()->template handle_left_combined<Combiner>(it_++); } } template <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc> template<class Combiner> inline void interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> ::subtract_rear(interval_type& inter_val, const CodomainT& co_val, iterator& it_) { interval_type right_resid = left_subtract((*it_).first, inter_val); if(icl::is_empty(right_resid)) { Combiner()((*it_).second, co_val); that()->template handle_combined<Combiner>(it_); } else { const_cast<interval_type&>((*it_).first) = right_subtract((*it_).first, right_resid); iterator next_ = this->_map.insert(it_, value_type(right_resid, (*it_).second)); Combiner()((*it_).second, co_val); that()->template handle_succeeded_combined<Combiner>(it_, next_); } } //============================================================================== //= Subtraction //============================================================================== template <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc> template<class Combiner> inline void interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> ::_subtract(const segment_type& minuend) { interval_type inter_val = minuend.first; if(icl::is_empty(inter_val)) return; const codomain_type& co_val = minuend.second; if(on_absorbtion<type,Combiner,Traits::absorbs_identities>::is_absorbable(co_val)) return; std::pair<iterator, iterator> exterior = equal_range(inter_val); if(exterior.first == exterior.second) return; iterator last_ = prior(exterior.second); iterator it_ = exterior.first; subtract_front (inter_val, it_ ); subtract_main <Combiner>( co_val, it_, last_); subtract_rear <Combiner>(inter_val, co_val, it_ ); } //============================================================================== //= Insertion //============================================================================== template <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc> inline void interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> ::insert_main(const interval_type& inter_val, const CodomainT& co_val, iterator& it_, const iterator& last_) { iterator end_ = boost::next(last_); iterator prior_ = it_, inserted_; if(prior_ != this->_map.end()) --prior_; interval_type rest_interval = inter_val, left_gap, cur_itv; interval_type last_interval = last_ ->first; while(it_ != end_ ) { cur_itv = (*it_).first ; left_gap = right_subtract(rest_interval, cur_itv); if(!icl::is_empty(left_gap)) { inserted_ = this->_map.insert(prior_, value_type(left_gap, co_val)); it_ = that()->handle_inserted(inserted_); } // shrink interval rest_interval = left_subtract(rest_interval, cur_itv); prior_ = it_; ++it_; } //insert_rear(rest_interval, co_val, last_): interval_type end_gap = left_subtract(rest_interval, last_interval); if(!icl::is_empty(end_gap)) { inserted_ = this->_map.insert(prior_, value_type(end_gap, co_val)); it_ = that()->handle_inserted(inserted_); } else it_ = prior_; } template <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc> inline typename interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc>::iterator interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> ::_insert(const segment_type& addend) { interval_type inter_val = addend.first; if(icl::is_empty(inter_val)) return this->_map.end(); const codomain_type& co_val = addend.second; if(on_codomain_absorbtion::is_absorbable(co_val)) return this->_map.end(); std::pair<iterator,bool> insertion = this->_map.insert(addend); if(insertion.second) return that()->handle_inserted(insertion.first); else { // Detect the first and the end iterator of the collision sequence iterator first_ = this->_map.lower_bound(inter_val), last_ = insertion.first; //assert((++last_) == this->_map.upper_bound(inter_val)); iterator it_ = first_; insert_main(inter_val, co_val, it_, last_); return it_; } } template <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc> inline typename interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc>::iterator interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> ::_insert(iterator prior_, const segment_type& addend) { interval_type inter_val = addend.first; if(icl::is_empty(inter_val)) return prior_; const codomain_type& co_val = addend.second; if(on_codomain_absorbtion::is_absorbable(co_val)) return prior_; std::pair<iterator,bool> insertion = insert_at(prior_, inter_val, co_val); if(insertion.second) return that()->handle_inserted(insertion.first); { // Detect the first and the end iterator of the collision sequence std::pair<iterator,iterator> overlap = equal_range(inter_val); iterator it_ = overlap.first, last_ = prior(overlap.second); insert_main(inter_val, co_val, it_, last_); return it_; } } //============================================================================== //= Erasure segment_type //============================================================================== template <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc> inline void interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> ::erase_rest(interval_type& inter_val, const CodomainT& co_val, iterator& it_, const iterator& last_) { // For all intervals within loop: (*it_).first are contained_in inter_val while(it_ != last_) if((*it_).second == co_val) this->_map.erase(it_++); else it_++; //erase_rear: if((*it_).second == co_val) { interval_type right_resid = left_subtract((*it_).first, inter_val); if(icl::is_empty(right_resid)) this->_map.erase(it_); else const_cast<interval_type&>((*it_).first) = right_resid; } } template <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc> inline SubType& interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> ::erase(const segment_type& minuend) { interval_type inter_val = minuend.first; if(icl::is_empty(inter_val)) return *that(); const codomain_type& co_val = minuend.second; if(on_codomain_absorbtion::is_absorbable(co_val)) return *that(); std::pair<iterator,iterator> exterior = equal_range(inter_val); if(exterior.first == exterior.second) return *that(); iterator first_ = exterior.first, end_ = exterior.second, last_ = cyclic_prior(*this, end_); iterator second_= first_; ++second_; if(first_ == last_) { // [----inter_val----) // .....first_==last_..... // only for the last there can be a right_resid: a part of *it_ right of minuend interval_type right_resid = left_subtract((*first_).first, inter_val); if((*first_).second == co_val) { interval_type left_resid = right_subtract((*first_).first, inter_val); if(!icl::is_empty(left_resid)) // [----inter_val----) { // [left_resid)..first_==last_...... const_cast<interval_type&>((*first_).first) = left_resid; if(!icl::is_empty(right_resid)) this->_map.insert(first_, value_type(right_resid, co_val)); } else if(!icl::is_empty(right_resid)) const_cast<interval_type&>((*first_).first) = right_resid; else this->_map.erase(first_); } } else { // first AND NOT last if((*first_).second == co_val) { interval_type left_resid = right_subtract((*first_).first, inter_val); if(icl::is_empty(left_resid)) this->_map.erase(first_); else const_cast<interval_type&>((*first_).first) = left_resid; } erase_rest(inter_val, co_val, second_, last_); } return *that(); } //============================================================================== //= Erasure key_type //============================================================================== template <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc> inline SubType& interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> ::erase(const interval_type& minuend) { if(icl::is_empty(minuend)) return *that(); std::pair<iterator, iterator> exterior = equal_range(minuend); if(exterior.first == exterior.second) return *that(); iterator first_ = exterior.first, end_ = exterior.second, last_ = prior(end_); interval_type left_resid = right_subtract((*first_).first, minuend); interval_type right_resid = left_subtract(last_ ->first, minuend); if(first_ == last_ ) if(!icl::is_empty(left_resid)) { const_cast<interval_type&>((*first_).first) = left_resid; if(!icl::is_empty(right_resid)) this->_map.insert(first_, value_type(right_resid, (*first_).second)); } else if(!icl::is_empty(right_resid)) const_cast<interval_type&>((*first_).first) = left_subtract((*first_).first, minuend); else this->_map.erase(first_); else { // [-------- minuend ---------) // [left_resid fst) . . . . [lst right_resid) iterator second_= first_; ++second_; iterator start_ = icl::is_empty(left_resid)? first_: second_; iterator stop_ = icl::is_empty(right_resid)? end_ : last_ ; this->_map.erase(start_, stop_); //erase [start_, stop_) if(!icl::is_empty(left_resid)) const_cast<interval_type&>((*first_).first) = left_resid; if(!icl::is_empty(right_resid)) const_cast<interval_type&>(last_ ->first) = right_resid; } return *that(); } //----------------------------------------------------------------------------- // type traits //----------------------------------------------------------------------------- template < class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc > struct is_map<icl::interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> > { typedef is_map<icl::interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> > type; BOOST_STATIC_CONSTANT(bool, value = true); }; template < class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc > struct has_inverse<icl::interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> > { typedef has_inverse<icl::interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> > type; BOOST_STATIC_CONSTANT(bool, value = (has_inverse<CodomainT>::value)); }; template < class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc > struct is_interval_container<icl::interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> > { typedef is_interval_container<icl::interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> > type; BOOST_STATIC_CONSTANT(bool, value = true); }; template < class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc > struct absorbs_identities<icl::interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> > { typedef absorbs_identities<icl::interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> > type; BOOST_STATIC_CONSTANT(bool, value = (Traits::absorbs_identities)); }; template < class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc > struct is_total<icl::interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> > { typedef is_total<icl::interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> > type; BOOST_STATIC_CONSTANT(bool, value = (Traits::is_total)); }; }} // namespace icl boost #endif
Stevenwork/Innov_code
v0.9/innovApp/libboost_1_49_0/include/boost/icl/interval_base_map.hpp
C++
lgpl-3.0
56,535
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.repair.consistent; import java.net.UnknownHostException; import java.util.Set; import java.util.UUID; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.junit.Ignore; import org.apache.cassandra.config.DatabaseDescriptor; import org.apache.cassandra.db.ColumnFamilyStore; import org.apache.cassandra.dht.Range; import org.apache.cassandra.dht.Token; import org.apache.cassandra.locator.InetAddressAndPort; import org.apache.cassandra.streaming.PreviewKind; import org.apache.cassandra.service.ActiveRepairService; import org.apache.cassandra.utils.ByteBufferUtil; import org.apache.cassandra.utils.UUIDGen; @Ignore public abstract class AbstractConsistentSessionTest { protected static final InetAddressAndPort COORDINATOR; protected static final InetAddressAndPort PARTICIPANT1; protected static final InetAddressAndPort PARTICIPANT2; protected static final InetAddressAndPort PARTICIPANT3; static { try { COORDINATOR = InetAddressAndPort.getByName("10.0.0.1"); PARTICIPANT1 = InetAddressAndPort.getByName("10.0.0.1"); PARTICIPANT2 = InetAddressAndPort.getByName("10.0.0.2"); PARTICIPANT3 = InetAddressAndPort.getByName("10.0.0.3"); } catch (UnknownHostException e) { throw new AssertionError(e); } DatabaseDescriptor.daemonInitialization(); } protected static final Set<InetAddressAndPort> PARTICIPANTS = ImmutableSet.of(PARTICIPANT1, PARTICIPANT2, PARTICIPANT3); protected static Token t(int v) { return DatabaseDescriptor.getPartitioner().getToken(ByteBufferUtil.bytes(v)); } protected static final Range<Token> RANGE1 = new Range<>(t(1), t(2)); protected static final Range<Token> RANGE2 = new Range<>(t(2), t(3)); protected static final Range<Token> RANGE3 = new Range<>(t(4), t(5)); protected static UUID registerSession(ColumnFamilyStore cfs) { UUID sessionId = UUIDGen.getTimeUUID(); ActiveRepairService.instance.registerParentRepairSession(sessionId, COORDINATOR, Lists.newArrayList(cfs), Sets.newHashSet(RANGE1, RANGE2, RANGE3), true, System.currentTimeMillis(), true, PreviewKind.NONE); return sessionId; } }
pauloricardomg/cassandra
test/unit/org/apache/cassandra/repair/consistent/AbstractConsistentSessionTest.java
Java
apache-2.0
3,628
/* * Copyright (c) 2015-present, Parse, LLC. * 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. */ package com.parse; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * An operation that removes every instance of an element from an array field. */ /** package */ class ParseRemoveOperation implements ParseFieldOperation { protected final HashSet<Object> objects = new HashSet<>(); public ParseRemoveOperation(Collection<?> coll) { objects.addAll(coll); } @Override public JSONObject encode(ParseEncoder objectEncoder) throws JSONException { JSONObject output = new JSONObject(); output.put("__op", "Remove"); output.put("objects", objectEncoder.encode(new ArrayList<>(objects))); return output; } @Override public ParseFieldOperation mergeWithPrevious(ParseFieldOperation previous) { if (previous == null) { return this; } else if (previous instanceof ParseDeleteOperation) { return new ParseSetOperation(objects); } else if (previous instanceof ParseSetOperation) { Object value = ((ParseSetOperation) previous).getValue(); if (value instanceof JSONArray || value instanceof List) { return new ParseSetOperation(this.apply(value, null)); } else { throw new IllegalArgumentException("You can only add an item to a List or JSONArray."); } } else if (previous instanceof ParseRemoveOperation) { HashSet<Object> result = new HashSet<>(((ParseRemoveOperation) previous).objects); result.addAll(objects); return new ParseRemoveOperation(result); } else { throw new IllegalArgumentException("Operation is invalid after previous operation."); } } @Override public Object apply(Object oldValue, String key) { if (oldValue == null) { return new ArrayList<>(); } else if (oldValue instanceof JSONArray) { ArrayList<Object> old = ParseFieldOperations.jsonArrayAsArrayList((JSONArray) oldValue); @SuppressWarnings("unchecked") ArrayList<Object> newValue = (ArrayList<Object>) this.apply(old, key); return new JSONArray(newValue); } else if (oldValue instanceof List) { ArrayList<Object> result = new ArrayList<>((List<?>) oldValue); result.removeAll(objects); // Remove the removed objects from "objects" -- the items remaining // should be ones that weren't removed by object equality. ArrayList<Object> objectsToBeRemoved = new ArrayList<>(objects); objectsToBeRemoved.removeAll(result); // Build up set of object IDs for any ParseObjects in the remaining objects-to-be-removed HashSet<String> objectIds = new HashSet<>(); for (Object obj : objectsToBeRemoved) { if (obj instanceof ParseObject) { objectIds.add(((ParseObject) obj).getObjectId()); } } // And iterate over "result" to see if any other ParseObjects need to be removed Iterator<Object> resultIterator = result.iterator(); while (resultIterator.hasNext()) { Object obj = resultIterator.next(); if (obj instanceof ParseObject && objectIds.contains(((ParseObject) obj).getObjectId())) { resultIterator.remove(); } } return result; } else { throw new IllegalArgumentException("Operation is invalid after previous operation."); } } }
MSchantz/Parse-SDK-Android
Parse/src/main/java/com/parse/ParseRemoveOperation.java
Java
bsd-3-clause
3,725
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Loader; use Symfony\Component\Config\Resource\FileResource; /** * PhpFileLoader loads service definitions from a PHP file. * * The PHP file is required and the $container variable can be * used within the file to change the container. * * @author Fabien Potencier <fabien@symfony.com> */ class PhpFileLoader extends FileLoader { /** * Loads a PHP file. * * @param mixed $file The resource * @param string $type The resource type */ public function load($file, $type = null) { // the container and loader variables are exposed to the included file below $container = $this->container; $loader = $this; $path = $this->locator->locate($file); $this->setCurrentDir(dirname($path)); $this->container->addResource(new FileResource($path)); include $path; } /** * Returns true if this class supports the given resource. * * @param mixed $resource A resource * @param string $type The resource type * * @return bool true if this class supports the given resource, false otherwise */ public function supports($resource, $type = null) { return is_string($resource) && 'php' === pathinfo($resource, PATHINFO_EXTENSION); } }
ozshel/theseus
web_service/vendor/symfony/symfony/src/Symfony/Component/DependencyInjection/Loader/PhpFileLoader.php
PHP
bsd-3-clause
1,576
/** * version: 1.1.3 */ angular.module('ngWig', ['ngwig-app-templates']); angular.module('ngWig').directive('ngWig', function () { return { scope: { content: '=ngWig' }, restrict: 'A', replace: true, templateUrl: 'ng-wig/views/ng-wig.html', link: function (scope, element, attrs) { scope.originalHeight = element.outerHeight(); scope.editMode = false; scope.autoexpand = !('autoexpand' in attrs) || attrs['autoexpand'] !== 'off'; scope.cssPath = scope.cssPath ? scope.cssPath : 'css/ng-wig.css'; scope.toggleEditMode = function() { scope.editMode = !scope.editMode; }; scope.execCommand = function (command, options) { if(command ==='createlink'){ options = prompt('Please enter the URL', 'http://'); } scope.$emit('execCommand', {command: command, options: options}); }; } } } ); angular.module('ngWig').directive('ngWigEditable', function () { function init(scope, $element, attrs, ctrl) { var document = $element[0].ownerDocument; $element.attr('contenteditable', true); //model --> view ctrl.$render = function () { $element.html(ctrl.$viewValue || ''); }; //view --> model function viewToModel() { ctrl.$setViewValue($element.html()); } $element.bind('blur keyup change paste', viewToModel); scope.$on('execCommand', function (event, params) { $element[0].focus(); var ieStyleTextSelection = document.selection, command = params.command, options = params.options; if (ieStyleTextSelection) { var textRange = ieStyleTextSelection.createRange(); } document.execCommand(command, false, options); if (ieStyleTextSelection) { textRange.collapse(false); textRange.select(); } viewToModel(); }); } return { restrict: 'A', require: 'ngModel', replace: true, link: init } } ); /** * No box-sizing, such a shame * * 1.Calculate outer height * @param bool Include margin * @returns Number Height in pixels * * 2. Set outer height * @param Number Height in pixels * @param bool Include margin * @returns angular.element Collection */ if (typeof angular.element.prototype.outerHeight !== 'function') { angular.element.prototype.outerHeight = function() { function parsePixels(cssString) { if (cssString.slice(-2) === 'px') { return parseFloat(cssString.slice(0, -2)); } return 0; } var includeMargin = false, height, $element = this.eq(0), element = $element[0]; if (arguments[0] === true || arguments[0] === false || arguments[0] === undefined) { if (!$element.length) { return 0; } includeMargin = arguments[0] && true || false; if (element.outerHeight) { height = element.outerHeight; } else { height = element.offsetHeight; } if (includeMargin) { height += parsePixels($element.css('marginTop')) + parsePixels($element.css('marginBottom')); } return height; } else { if (!$element.length) { return this; } height = parseFloat(arguments[0]); includeMargin = arguments[1] && true || false; if (includeMargin) { height -= parsePixels($element.css('marginTop')) + parsePixels($element.css('marginBottom')); } height -= parsePixels($element.css('borderTopWidth')) + parsePixels($element.css('borderBottomWidth')) + parsePixels($element.css('paddingTop')) + parsePixels($element.css('paddingBottom')); $element.css('height', height + 'px'); return this; } }; } angular.module('ngwig-app-templates', ['ng-wig/views/ng-wig.html']); angular.module("ng-wig/views/ng-wig.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("ng-wig/views/ng-wig.html", "<div class=\"ng-wig\">\n" + " <ul class=\"nw-toolbar\">\n" + " <li class=\"nw-toolbar__item\">\n" + " <button type=\"button\" class=\"nw-button nw-button--header-one\" title=\"Header\" ng-click=\"execCommand('formatblock', '<h1>')\"></button>\n" + " </li><!--\n" + " --><li class=\"nw-toolbar__item\">\n" + " <button type=\"button\" class=\"nw-button nw-button--paragraph\" title=\"Paragraph\" ng-click=\"execCommand('formatblock', '<p>')\"></button>\n" + " </li><!--\n" + " --><li class=\"nw-toolbar__item\">\n" + " <button type=\"button\" class=\"nw-button nw-button--unordered-list\" title=\"Unordered List\" ng-click=\"execCommand('insertunorderedlist')\"></button>\n" + " </li><!--\n" + " --><li class=\"nw-toolbar__item\">\n" + " <button type=\"button\" class=\"nw-button nw-button--ordered-list\" title=\"Ordered List\" ng-click=\"execCommand('insertorderedlist')\"></button>\n" + " </li><!--\n" + " --><li class=\"nw-toolbar__item\">\n" + " <button type=\"button\" class=\"nw-button nw-button--bold\" title=\"Bold\" ng-click=\"execCommand('bold')\"></button>\n" + " </li><!--\n" + " --><li class=\"nw-toolbar__item\">\n" + " <button type=\"button\" class=\"nw-button nw-button--italic\" title=\"Italic\" ng-click=\"execCommand('italic')\"></button>\n" + " </li><!--\n" + " --><li class=\"nw-toolbar__item\">\n" + " <button type=\"button\" class=\"nw-button nw-button--link\" title=\"link\" ng-click=\"execCommand('createlink')\"></button>\n" + " </li><!--\n" + " --><li class=\"nw-toolbar__item\">\n" + " <button type=\"button\" class=\"nw-button nw-button--source\" ng-class=\"{ 'nw-button--active': editMode }\" ng-click=\"toggleEditMode()\"></button>\n" + " </li>\n" + " </ul>\n" + "\n" + " <div class=\"nw-editor-container\">\n" + " <div class=\"nw-editor\">\n" + " <textarea class=\"nw-editor__src\" ng-show=\"editMode\" ng-model=\"content\"></textarea>\n" + " <div ng-class=\"{'nw-invisible': editMode, 'nw-autoexpand': autoexpand}\" class=\"nw-editor__res\" ng-model=\"content\" ng-wig-editable></div>\n" + " </div>\n" + " </div>\n" + "</div>\n" + ""); }]);
dhenson02/cdnjs
ajax/libs/ng-wig/1.1.3/ng-wig.js
JavaScript
mit
6,452
// Copyright (C) 2001-2015 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. #include "1.h" #include <list> int main() { cons01<std::list< A<B> > >(); return 0; }
crystax/android-toolchain-gcc-5
libstdc++-v3/testsuite/23_containers/list/cons/1.cc
C++
gpl-2.0
855
// Type definitions for galleria.js v1.4.2 // Project: https://github.com/aino/galleria // Definitions by: Robert Imig <https://github.com/rimig> // Definitions: https://github.com/borisyankov/DefinitelyTyped declare module GalleriaJS { interface GalleriaOptions { dataSource: GalleriaEntry[]; autoplay?: boolean; lightbox?: boolean; } interface GalleriaEntry { image?: string; thumbnail?: string; title?: string; description?: string; } interface GalleriaFactory { run(): GalleriaFactory; run(selector: String): GalleriaFactory; run(selector: String, options: GalleriaOptions): GalleriaFactory; loadTheme(url : String): GalleriaFactory; configure(options: GalleriaOptions): GalleriaFactory; ready( method: () => any): void; refreshImage(): GalleriaFactory; resize(): GalleriaFactory; load( data: GalleriaEntry[]): GalleriaFactory; setOptions( options: GalleriaOptions): GalleriaFactory; } } declare var Galleria: GalleriaJS.GalleriaFactory;
rodzewich/playground
types/jquery-galleria/jquery-galleria.d.ts
TypeScript
mit
1,084
/** * Arabic translation (Syrian Localization, it may differ if you aren't from Syria or any Country in Middle East) * @author Tawfek Daghistani <tawfekov@gmail.com> * @version 2011-07-09 */ if (elFinder && elFinder.prototype && typeof(elFinder.prototype.i18) == 'object') { elFinder.prototype.i18.ar = { translator : 'Tawfek Daghistani &lt;tawfekov@gmail.com&gt;', language : 'العربية', direction : 'rtl', messages : { /********************************** errors **********************************/ 'error' : 'خطأ', 'errUnknown' : 'خطأ غير معروف .', 'errUnknownCmd' : 'أمر غير معروف .', 'errJqui' : 'إعدادات jQuery UI غير كاملة الرجاء التأكد من وجود كل من selectable, draggable and droppable', 'errNode' : '. موجود DOM إلى عنصر elFinder تحتاج ', 'errURL' : 'إعدادات خاطئة , عليك وضع الرابط ضمن الإعدادات', 'errAccess' : 'وصول مرفوض .', 'errConnect' : 'غير قادر على الاتصال بالخادم الخلفي (backend)', 'errAbort' : 'تم فصل الإتصال', 'errTimeout' : 'مهلة الإتصال قد إنتهت .', 'errNotFound' : 'الخادم الخلفي غير موجود .', 'errResponse' : 'رد غير مقبول من الخادم الخلفي', 'errConf' : 'خطأ في الإعدادات الخاصة بالخادم الخلفي ', 'errJSON' : 'الميزة PHP JSON module غير موجودة ', 'errNoVolumes' : 'لا يمكن القراءة من أي من الوسائط الموجودة ', 'errCmdParams' : 'البيانات المرسلة للأمر غير مقبولة "$1".', 'errDataNotJSON' : 'المعلومات المرسلة ليست من نوع JSON ', 'errDataEmpty' : 'لا يوجد معلومات مرسلة', 'errCmdReq' : 'الخادم الخلفي يطلب وجود اسم الأمر ', 'errOpen' : 'غير قادر على فتح "$1".', 'errNotFolder' : 'العنصر المختار ليس مجلد', 'errNotFile' : 'العنصر المختار ليس ملف', 'errRead' : 'غير قادر على القراءة "$1".', 'errWrite' : 'غير قادر على الكتابة "$1".', 'errPerm' : 'وصول مرفوض ', 'errLocked' : ' محمي و لا يمكن التعديل أو النقل أو إعادة التسمية"$1"', 'errExists' : ' موجود مسبقاً "$1"', 'errInvName' : 'الاسم مرفوض', 'errFolderNotFound' : 'المجلد غير موجود', 'errFileNotFound' : 'الملف غير موجود', 'errTrgFolderNotFound' : 'الملف الهدف "$1" غير موجود ', 'errPopup' : 'يمنعني المتصفح من إنشاء نافذة منبثقة , الرجاء تعديل الخيارات الخاصة من إعدادات المتصفح ', 'errMkdir' : ' غير قادر على إنشاء مجلد جديد "$1".', 'errMkfile' : ' غير قادر على إنشاء ملف جديد"$1".', 'errRename' : 'غير قادر على إعادة تسمية ال "$1".', 'errCopyFrom' : 'نسخ الملفات من الوسط المحدد "$1"غير مسموح.', 'errCopyTo' : 'نسخ الملفات إلى الوسط المحدد "$1" غير مسموح .', 'errUploadCommon' : 'خطأ أثناء عملية الرفع', 'errUpload' : 'غير قادر على رفع "$1".', 'errUploadNoFiles' : 'لم يتم رفع أي ملف ', 'errMaxSize' : 'حجم البيانات أكبر من الحجم المسموح به ', 'errFileMaxSize' : 'حجم الملف أكبر من الحجم المسموح به', 'errUploadMime' : 'نوع ملف غير مسموح ', 'errUploadTransfer' : '"$1" خطأ أثناء عملية النقل', 'errSave' : 'غير قادر على الحفظ في "$1".', 'errCopy' : 'غير قادر على النسخ إلى"$1".', 'errMove' : 'غير قادر على القص إلى "$1".', 'errCopyInItself' : 'غير قادر على نسخ الملف "$1" ضمن الملف نفسه.', 'errRm' : 'غير قادر على الحذف "$1".', 'errExtract' : 'غير قادر على استخراج الملفات من "$1".', 'errArchive' : 'غير قادر على إنشاء ملف مضغوط', 'errArcType' : 'نوع الملف المضغوط غير مدعومة', 'errNoArchive' : 'هذا الملف ليس ملف مضغوط أو ذو صسغة غير مدعومة ', 'errCmdNoSupport' : 'الخادم الخلفي لا يدعم هذا الأمر ', 'errReplByChild' : 'The folder “$1” can’t be replaced by an item it contains.', 'errArcSymlinks' : 'For security reason denied to unpack archives contains symlinks.', 'errArcMaxSize' : 'Archive files exceeds maximum allowed size.', /******************************* commands names ********************************/ 'cmdarchive' : 'أنشئ مجلد مضغوط', 'cmdback' : 'الخلف', 'cmdcopy' : 'نسخ', 'cmdcut' : 'قص', 'cmddownload' : 'تحميل', 'cmdduplicate' : 'تكرار', 'cmdedit' : 'تعديل الملف', 'cmdextract' : 'استخراج الملفات', 'cmdforward' : 'الأمام', 'cmdgetfile' : 'أختيار الملفات', 'cmdhelp' : 'عن هذا المشروع', 'cmdhome' : 'المجلد الرئيسي', 'cmdinfo' : 'معلومات ', 'cmdmkdir' : 'مجلد جديد', 'cmdmkfile' : 'ملف نصي جديد', 'cmdopen' : 'فتح', 'cmdpaste' : 'لصق', 'cmdquicklook' : 'معاينة', 'cmdreload' : 'إعادة تحميل', 'cmdrename' : 'إعادة تسمية', 'cmdrm' : 'حذف', 'cmdsearch' : 'بحث عن ملفات', 'cmdup' : 'تغيير المسار إلى مستوى أعلى', 'cmdupload' : 'رفع ملفات', 'cmdview' : 'عرض', /*********************************** buttons ***********************************/ 'btnClose' : 'إغلاق', 'btnSave' : 'حفظ', 'btnRm' : 'إزالة', 'btnCancel' : 'إلغاء', 'btnNo' : 'لا', 'btnYes' : 'نعم', /******************************** notifications ********************************/ 'ntfopen' : 'فتح مجلد', 'ntffile' : 'فتح ملف', 'ntfreload' : 'إعادة عرض محتويات المجلد ', 'ntfmkdir' : 'ينشئ المجلدات', 'ntfmkfile' : 'ينشئ الملفات', 'ntfrm' : 'حذف الملفات', 'ntfcopy' : 'نسخ الملفات', 'ntfmove' : 'نقل الملفات', 'ntfprepare' : 'تحضير لنسخ الملفات', 'ntfrename' : 'إعادة تسمية الملفات', 'ntfupload' : 'رفع الملفات', 'ntfdownload' : 'تحميل الملفات', 'ntfsave' : 'حفظ الملفات', 'ntfarchive' : 'ينشئ ملف مضغوط', 'ntfextract' : 'استخراج ملفات من الملف المضغوط ', 'ntfsearch' : 'يبحث عن ملفات', 'ntfsmth' : 'يحضر لشيء ما >_<', /************************************ dates **********************************/ 'dateUnknown' : 'غير معلوم', 'Today' : 'اليوم', 'Yesterday' : 'البارحة', 'Jan' : 'كانون الثاني', 'Feb' : 'شباط', 'Mar' : 'آذار', 'Apr' : 'نيسان', 'May' : 'أيار', 'Jun' : 'حزيران', 'Jul' : 'تموز', 'Aug' : 'آب', 'Sep' : 'أيلول', 'Oct' : 'تشرين الأول', 'Nov' : 'تشرين الثاني', 'Dec' : 'كانون الأول ', /********************************** messages **********************************/ 'confirmReq' : 'يرجى التأكيد', 'confirmRm' : 'هل انت متأكد من انك تريد الحذف<br/>لا يمكن التراجع عن هذه العملية ', 'confirmRepl' : 'استبدال الملف القديم بملف جديد ؟', 'apllyAll' : 'تطبيق على الكل', 'name' : 'الأسم', 'size' : 'الحجم', 'perms' : 'الصلاحيات', 'modify' : 'أخر تعديل', 'kind' : 'نوع الملف', 'read' : 'قراءة', 'write' : 'كتابة', 'noaccess' : 'وصول ممنوع', 'and' : 'و', 'unknown' : 'غير معروف', 'selectall' : 'تحديد كل الملفات', 'selectfiles' : 'تحديد ملفات', 'selectffile' : 'تحديد الملف الاول', 'selectlfile' : 'تحديد الملف الأخير', 'viewlist' : 'اعرض ك قائمة', 'viewicons' : 'اعرض ك ايقونات', 'places' : 'المواقع', 'calc' : 'حساب', 'path' : 'مسار', 'aliasfor' : 'Alias for', 'locked' : 'مقفول', 'dim' : 'الابعاد', 'files' : 'ملفات', 'folders' : 'مجلدات', 'items' : 'عناصر', 'yes' : 'نعم', 'no' : 'لا', 'link' : 'اربتاط', 'searcresult' : 'نتائج البحث', 'selected' : 'العناصر المحددة', 'about' : 'عن البرنامج', 'shortcuts' : 'الاختصارات', 'help' : 'مساعدة', 'webfm' : 'مدير ملفات الويب', 'ver' : 'رقم الإصدار', 'protocol' : 'اصدار البرتوكول', 'homepage' : 'الصفحة الرئيسية', 'docs' : 'التعليمات', 'github' : 'شاركنا بتطوير المشروع على Github', 'twitter' : 'تابعنا على تويتر', 'facebook' : 'انضم إلينا على الفيس بوك', 'team' : 'الفريق', 'chiefdev' : 'رئيس المبرمجين', 'developer' : 'مبرمح', 'contributor' : 'مبرمح', 'maintainer' : 'مشارك', 'translator' : 'مترجم', 'icons' : 'أيقونات', 'dontforget' : 'and don\'t forget to take your towel', 'shortcutsof' : 'الاختصارات غير مفعلة', 'dropFiles' : 'لصق الملفات هنا', 'or' : 'أو', 'selectForUpload' : 'اختر الملفات التي تريد رفعها', 'moveFiles' : 'قص الملفات', 'copyFiles' : 'نسخ الملفات', 'rmFromPlaces' : 'Remove from places', 'untitled folder' : 'untitled folder', 'untitled file.txt' : 'untitled file.txt', /********************************** mimetypes **********************************/ 'kindUnknown' : 'غير معروف', 'kindFolder' : 'مجلد', 'kindAlias' : 'اختصار', 'kindAliasBroken' : 'اختصار غير صالح', // applications 'kindApp' : 'برنامج', 'kindPostscript' : 'Postscript ملف', 'kindMsOffice' : 'Microsoft Office ملف', 'kindMsWord' : 'Microsoft Word ملف', 'kindMsExcel' : 'Microsoft Excel ملف', 'kindMsPP' : 'Microsoft Powerpoint عرض تقديمي ', 'kindOO' : 'Open Office ملف', 'kindAppFlash' : 'تطبيق فلاش', 'kindPDF' : 'ملف (PDF)', 'kindTorrent' : 'Bittorrent ملف', 'kind7z' : '7z ملف', 'kindTAR' : 'TAR ملف', 'kindGZIP' : 'GZIP ملف', 'kindBZIP' : 'BZIP ملف', 'kindZIP' : 'ZIP ملف', 'kindRAR' : 'RAR ملف', 'kindJAR' : 'Java JAR ملف', 'kindTTF' : 'True Type خط ', 'kindOTF' : 'Open Type خط ', 'kindRPM' : 'RPM ملف تنصيب', // texts 'kindText' : 'Text ملف', 'kindTextPlain' : 'مستند نصي', 'kindPHP' : 'PHP ملف نصي برمجي لـ', 'kindCSS' : 'Cascading style sheet', 'kindHTML' : 'HTML ملف', 'kindJS' : 'Javascript ملف نصي برمجي لـ', 'kindRTF' : 'Rich Text Format', 'kindC' : 'C ملف نصي برمجي لـ', 'kindCHeader' : 'C header ملف نصي برمجي لـ', 'kindCPP' : 'C++ ملف نصي برمجي لـ', 'kindCPPHeader' : 'C++ header ملف نصي برمجي لـ', 'kindShell' : 'Unix shell script', 'kindPython' : 'Python ملف نصي برمجي لـ', 'kindJava' : 'Java ملف نصي برمجي لـ', 'kindRuby' : 'Ruby ملف نصي برمجي لـ', 'kindPerl' : 'Perl script', 'kindSQL' : 'SQL ملف نصي برمجي لـ', 'kindXML' : 'XML ملف', 'kindAWK' : 'AWK ملف نصي برمجي لـ', 'kindCSV' : 'ملف CSV', 'kindDOCBOOK' : 'Docbook XML ملف', // images 'kindصورة' : 'صورة', 'kindBMP' : 'BMP صورة', 'kindJPEG' : 'JPEG صورة', 'kindGIF' : 'GIF صورة', 'kindPNG' : 'PNG صورة', 'kindTIFF' : 'TIFF صورة', 'kindTGA' : 'TGA صورة', 'kindPSD' : 'Adobe Photoshop صورة', 'kindXBITMAP' : 'X bitmap صورة', 'kindPXM' : 'Pixelmator صورة', // media 'kindAudio' : 'ملف صوتي', 'kindAudioMPEG' : 'MPEG ملف صوتي', 'kindAudioMPEG4' : 'MPEG-4 ملف صوتي', 'kindAudioMIDI' : 'MIDI ملف صوتي', 'kindAudioOGG' : 'Ogg Vorbis ملف صوتي', 'kindAudioWAV' : 'WAV ملف صوتي', 'AudioPlaylist' : 'MP3 قائمة تشغيل', 'kindVideo' : 'ملف فيديو', 'kindVideoDV' : 'DV ملف فيديو', 'kindVideoMPEG' : 'MPEG ملف فيديو', 'kindVideoMPEG4' : 'MPEG-4 ملف فيديو', 'kindVideoAVI' : 'AVI ملف فيديو', 'kindVideoMOV' : 'Quick Time ملف فيديو', 'kindVideoWM' : 'Windows Media ملف فيديو', 'kindVideoFlash' : 'Flash ملف فيديو', 'kindVideoMKV' : 'Matroska ملف فيديو', 'kindVideoOGG' : 'Ogg ملف فيديو' } } }
tokenly/tokenly-cms
www/themes/tokentalk/js/i18n/elfinder.ar.js
JavaScript
gpl-2.0
14,935
using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace Umbraco.Web.Models.ContentEditing { [DataContract(Name = "relation", Namespace = "")] public class Relation { public Relation() { RelationType = new RelationType(); } /// <summary> /// Gets or sets the Parent Id of the Relation (Source) /// </summary> [DataMember(Name = "parentId")] public int ParentId { get; set; } /// <summary> /// Gets or sets the Child Id of the Relation (Destination) /// </summary> [DataMember(Name = "childId")] public int ChildId { get; set; } /// <summary> /// Gets or sets the <see cref="RelationType"/> for the Relation /// </summary> [DataMember(Name = "relationType", IsRequired = true)] public RelationType RelationType { get; set; } /// <summary> /// Gets or sets a comment for the Relation /// </summary> [DataMember(Name = "comment")] public string Comment { get; set; } } }
Nicholas-Westby/Umbraco-CMS
src/Umbraco.Web/Models/ContentEditing/Relation.cs
C#
mit
1,181
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v4.1.5 * @link http://www.ag-grid.com/ * @license MIT */ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var context_1 = require("./context/context"); var rowNode_1 = require("./entities/rowNode"); var renderedRow_1 = require("./rendering/renderedRow"); var utils_1 = require('./utils'); var SelectionRendererFactory = (function () { function SelectionRendererFactory() { } SelectionRendererFactory.prototype.createSelectionCheckbox = function (rowNode, addRenderedRowEventListener) { var eCheckbox = document.createElement('input'); eCheckbox.type = "checkbox"; eCheckbox.name = "name"; eCheckbox.className = 'ag-selection-checkbox'; utils_1.Utils.setCheckboxState(eCheckbox, rowNode.isSelected()); eCheckbox.addEventListener('click', function (event) { return event.stopPropagation(); }); eCheckbox.addEventListener('change', function () { var newValue = eCheckbox.checked; if (newValue) { rowNode.setSelected(newValue); } else { rowNode.setSelected(newValue); } }); var selectionChangedCallback = function () { return utils_1.Utils.setCheckboxState(eCheckbox, rowNode.isSelected()); }; rowNode.addEventListener(rowNode_1.RowNode.EVENT_ROW_SELECTED, selectionChangedCallback); addRenderedRowEventListener(renderedRow_1.RenderedRow.EVENT_RENDERED_ROW_REMOVED, function () { rowNode.removeEventListener(rowNode_1.RowNode.EVENT_ROW_SELECTED, selectionChangedCallback); }); return eCheckbox; }; SelectionRendererFactory = __decorate([ context_1.Bean('selectionRendererFactory'), __metadata('design:paramtypes', []) ], SelectionRendererFactory); return SelectionRendererFactory; })(); exports.SelectionRendererFactory = SelectionRendererFactory;
Eurofunk/ag-grid
dist/lib/selectionRendererFactory.js
JavaScript
mit
2,720
/* Spellbook Class Extension */ if (!Array.prototype.remove) { Array.prototype.remove = function (obj) { var self = this; if (typeof obj !== "object" && !obj instanceof Array) { obj = [obj]; } return self.filter(function(e){ if(obj.indexOf(e)<0) { return e } }); }; } if (!Array.prototype.clear) { Array.prototype.clear = function() { this.splice(0, this.length); }; } if (!Array.prototype.random) { Array.prototype.random = function() { self = this; var index = Math.floor(Math.random() * (this.length)); return self[index]; }; } if (!Array.prototype.shuffle) { Array.prototype.shuffle = function() { var input = this; for (var i = input.length-1; i >=0; i--) { var randomIndex = Math.floor(Math.random()*(i+1)); var itemAtIndex = input[randomIndex]; input[randomIndex] = input[i]; input[i] = itemAtIndex; } return input; } } if (!Array.prototype.first) { Array.prototype.first = function() { return this[0]; } } if (!Array.prototype.last) { Array.prototype.last = function() { return this[this.length - 1]; } } if (!Array.prototype.inArray) { Array.prototype.inArray = function (value) { return !!~this.indexOf(value); }; } if (!Array.prototype.contains) { Array.prototype.contains = function (value) { return !!~this.indexOf(value); }; } if (!Array.prototype.each) { Array.prototype.each = function (interval, callback, response) { var self = this; var i = 0; if (typeof interval !== "function" ) { var inter = setInterval(function () { callback(self[i], i); i++; if (i === self.length) { clearInterval(inter); if (typeof response === "function") response(); } }, interval); } else { for (var i = 0; i < self.length; i++) { interval(self[i], i); if (typeof callback === "function") { if (i === self.length - 1) callback(); } } } } } if (!Array.prototype.eachEnd) { Array.prototype.eachEnd = function (callback, response) { var self = this; var i = 0; var done = function () { if (i < self.length -1) { i++; callback(self[i], i, done); } else { if (typeof response === 'function') { response(); } } } callback(self[i], i, done); } } if (!Object.prototype.extend) { Object.prototype.extend = function(obj) { for (var i in obj) { if (obj.hasOwnProperty(i)) { this[i] = obj[i]; }; }; }; } if (!Object.prototype.remove) { Object.prototype.remove = function(keys) { var self = this; if (typeof obj === "object" && obj instanceof Array) { arr.forEach(function(key){ delete(self[key]); }); } else { delete(self[keys]); }; }; } if (!Object.prototype.getKeys) { Object.prototype.getKeys = function(keys) { var self = this; if (typeof obj === "object" && obj instanceof Array) { var obj = {}; keys.forEach(function(key){ obj[key] = self[key]; }); } else { obj[keys] = self[keys]; } return obj; }; } if (!String.prototype.repeatify) { String.prototype.repeatify = function(num) { var strArray = []; for (var i = 0; i < num; i++) { strArray.push(this.normalize()); } return strArray; }; } if (!Number.prototype.times) { Number.prototype.times = function (callback) { if (this % 1 === 0) for (var i = 0; i < this; i++) { callback() } }; } if (!Number.prototype.isInteger) { Number.prototype.isInteger = function () { this.isInteger = function (num) { return num % 1 === 0; } } } if (!Array.prototype.isArray) { this.isArray = function () { return typeof this === "object" && this instanceof Array; }; } if (!Function.prototype.isFunction) { this.isFunction = function () { return typeof this === 'function'; }; } if (!Object.prototype.isObject) { this.isObject = function () { return typeof this === "object" && (isArray(this) === false ); }; } if (!String.prototype.isString) { this.isString = function () { return typeof this === "string" || this instanceof String; }; } if (!Boolean.prototype.isBoolean) { this.isBoolean = function () { return typeof this === "boolean"; }; } /* Spellbook Utils */ var Spellbook = function () { this.test = function () { return "Testing Spellbook"; }; this.range = function(a, b, step) { var A= []; if(typeof a == 'number'){ A[0]= a; step = step || 1; while(a+step<= b) { A[A.length]= a+= step; } } else { var s = 'abcdefghijklmnopqrstuvwxyz'; if(a=== a.toUpperCase()) { b=b.toUpperCase(); s= s.toUpperCase(); } s= s.substring(s.indexOf(a), s.indexOf(b)+ 1); A= s.split(''); } return A; }; this.isFunction = function (fn) { return typeof fn === 'function'; }; this.isArray = function (obj) { return typeof obj === "object" && obj instanceof Array; }; this.isObject = function (obj) { return typeof obj === "object" && (isArray(obj) === false ); }; this.isNumber = function (obj) { return typeof obj === "number" || obj instanceof Number; }; this.isString = function (obj ) { return typeof obj === "string" || obj instanceof String; }; this.isBoolean = function (obj) { return typeof obj === "boolean"; }; this.isInteger = function (obj) { return obj % 1 === 0; } this.random = function (min, max) { if (typeof min === "number" && typeof max === "number") { return Math.floor(Math.random() * (max - min)) + min; } else { return 0; } }; this.clone = function (obj) { if(obj === null || typeof(obj) !== 'object' || 'isActiveClone' in obj) return obj; var temp = obj.constructor(); for(var key in obj) { if(Object.prototype.hasOwnProperty.call(obj, key)) { obj['isActiveClone'] = null; temp[key] = clone(obj[key]); delete obj['isActiveClone']; } } return temp; }; this.assign = function (obj) { return this.clone(obj); }; this.remove = function (array, obj) { if (typeof obj !== "object" && !obj instanceof Array) { obj = [obj]; } return array.filter(function(e){ if(obj.indexOf(e)<0) { return e } }); }; this.clear = function (array) { array.splice(0, array.length); }; this.inArray = function (a, b) { return !!~a.indexOf(b); }; this.contains = function (a, b) { return !!~a.indexOf(b); }; this.times = function (number, callback) { if (typeof number === 'number' && number > 0) { if ( typeof callback === 'function') { for (var i = 0; i < number; i++) { callback(); } } } }; this.each = function (array, interval, callback, response) { var i = 0; if (typeof interval !== "function" ) { var inter = setInterval(function () { callback(array[i], i); i++; if (i === array.length) { clearInterval(inter); if (typeof response === "function") response(); } }, interval); } else { for (var i = 0; i < array.length; i++) { interval(array[i], i); if (typeof callback === "function") { if (i === array.length - 1) callback(); } } } } this.eachEnd = function (array, callback, response) { var i = 0; var done = function () { if (i < array.length -1) { i++; callback(array[i], i, done); } else { if (typeof response === 'function') { response(); } } } callback(array[i], i, done); } this.checkDate = function (value, userFormat) { userFormat = userFormat || 'mm/dd/yyyy'; var delimiter = /[^mdy]/.exec(userFormat)[0]; var theFormat = userFormat.split(delimiter); var theDate = value.split(delimiter); function isDate(date, format) { var m, d, y, i = 0, len = format.length, f; for (i; i < len; i++) { f = format[i]; if (/m/.test(f)) m = date[i]; if (/d/.test(f)) d = date[i]; if (/y/.test(f)) y = date[i]; } return ( m > 0 && m < 13 && y && y.length === 4 && d > 0 && d <= (new Date(y, m, 0)).getDate() ); }; return isDate(theDate, theFormat); }; this.excerpt = function (str, nwords) { var words = str.split(' '); words.splice(nwords, words.length-1); return words.join(' '); } }; if (typeof process === 'object') { module.exports = new Spellbook; } else { Spellbook.prototype.get = function (url, callback) { var xhr = new XMLHttpRequest(); xhr.open('GET', encodeURI(url)); xhr.onload = function() { if (xhr.status === 200) { callback(false, xhr.responseText); } else { callback("Request failed. Returned status of " + status); } }; xhr.send(); } Spellbook.prototype.post = function (url, data, header, callback) { function param(object) { var encodedString = ''; for (var prop in object) { if (object.hasOwnProperty(prop)) { if (encodedString.length > 0) { encodedString += '&'; } encodedString += encodeURI(prop + '=' + object[prop]); } } return encodedString; } if (typeof header === "function") { callback = header; header = "application/json"; var finaldata = JSON.stringify(data); } else { var finaldata = param(data); } xhr = new XMLHttpRequest(); xhr.open('POST', encodeURI(url)); xhr.setRequestHeader('Content-Type', header); xhr.onload = function() { if (xhr.status === 200 && xhr.responseText !== undefined) { callback(null, xhr.responseText); } else if (xhr.status !== 200) { callback('Request failed. Returned status of ' + xhr.status); } }; xhr.send(finaldata); } var sb = new Spellbook(); }
viskin/cdnjs
ajax/libs/spellbook/0.0.28/spellbook.js
JavaScript
mit
9,757
#include "ex14_49.h" int main() { Date date(12, 4, 2015); if (static_cast<bool>(date)) std::cout << date << std::endl; }
wy7980/Cpp-Primer
ch14/ex14_49_TEST.cpp
C++
cc0-1.0
138
/* * * Copyright 2018 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package grpc // Version is the current grpc version. const Version = "1.38.0"
thaJeztah/cli
vendor/google.golang.org/grpc/version.go
GO
apache-2.0
683
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ /* jslint sloppy:true */ /* global Windows:true, setImmediate */ var cordova = require('cordova'), urlutil = require('cordova/urlutil'); var browserWrap, popup, navigationButtonsDiv, navigationButtonsDivInner, backButton, forwardButton, closeButton, bodyOverflowStyle, navigationEventsCallback; // x-ms-webview is available starting from Windows 8.1 (platformId is 'windows') // http://msdn.microsoft.com/en-us/library/windows/apps/dn301831.aspx var isWebViewAvailable = cordova.platformId === 'windows'; function attachNavigationEvents(element, callback) { if (isWebViewAvailable) { element.addEventListener("MSWebViewNavigationStarting", function (e) { callback({ type: "loadstart", url: e.uri}, {keepCallback: true} ); }); element.addEventListener("MSWebViewNavigationCompleted", function (e) { if (e.isSuccess) { callback({ type: "loadstop", url: e.uri }, { keepCallback: true }); } else { callback({ type: "loaderror", url: e.uri, code: e.webErrorStatus, message: "Navigation failed with error code " + e.webErrorStatus}, { keepCallback: true }); } }); element.addEventListener("MSWebViewUnviewableContentIdentified", function (e) { // WebView found the content to be not HTML. // http://msdn.microsoft.com/en-us/library/windows/apps/dn609716.aspx callback({ type: "loaderror", url: e.uri, code: e.webErrorStatus, message: "Navigation failed with error code " + e.webErrorStatus}, { keepCallback: true }); }); element.addEventListener("MSWebViewContentLoading", function (e) { if (navigationButtonsDiv && popup) { if (popup.canGoBack) { backButton.removeAttribute("disabled"); } else { backButton.setAttribute("disabled", "true"); } if (popup.canGoForward) { forwardButton.removeAttribute("disabled"); } else { forwardButton.setAttribute("disabled", "true"); } } }); } else { var onError = function () { callback({ type: "loaderror", url: this.contentWindow.location}, {keepCallback: true}); }; element.addEventListener("unload", function () { callback({ type: "loadstart", url: this.contentWindow.location}, {keepCallback: true}); }); element.addEventListener("load", function () { callback({ type: "loadstop", url: this.contentWindow.location}, {keepCallback: true}); }); element.addEventListener("error", onError); element.addEventListener("abort", onError); } } var IAB = { close: function (win, lose) { setImmediate(function () { if (browserWrap) { if (navigationEventsCallback) { navigationEventsCallback({ type: "exit" }); } browserWrap.parentNode.removeChild(browserWrap); // Reset body overflow style to initial value document.body.style.msOverflowStyle = bodyOverflowStyle; browserWrap = null; popup = null; } }); }, show: function (win, lose) { setImmediate(function () { if (browserWrap) { browserWrap.style.display = "block"; } }); }, open: function (win, lose, args) { // make function async so that we can add navigation events handlers before view is loaded and navigation occured setImmediate(function () { var strUrl = args[0], target = args[1], features = args[2], url; navigationEventsCallback = win; if (target === "_system") { url = new Windows.Foundation.Uri(strUrl); Windows.System.Launcher.launchUriAsync(url); } else if (target === "_self" || !target) { window.location = strUrl; } else { // "_blank" or anything else if (!browserWrap) { var browserWrapStyle = document.createElement('link'); browserWrapStyle.rel = "stylesheet"; browserWrapStyle.type = "text/css"; browserWrapStyle.href = urlutil.makeAbsolute("/www/css/inappbrowser.css"); document.head.appendChild(browserWrapStyle); browserWrap = document.createElement("div"); browserWrap.className = "inAppBrowserWrap"; if (features.indexOf("fullscreen=yes") > -1) { browserWrap.classList.add("inAppBrowserWrapFullscreen"); } // Save body overflow style to be able to reset it back later bodyOverflowStyle = document.body.style.msOverflowStyle; browserWrap.onclick = function () { setTimeout(function () { IAB.close(navigationEventsCallback); }, 0); }; document.body.appendChild(browserWrap); // Hide scrollbars for the whole body while inappbrowser's window is open document.body.style.msOverflowStyle = "none"; } if (features.indexOf("hidden=yes") !== -1) { browserWrap.style.display = "none"; } popup = document.createElement(isWebViewAvailable ? "x-ms-webview" : "iframe"); if (popup instanceof HTMLIFrameElement) { // For iframe we need to override bacground color of parent element here // otherwise pages without background color set will have transparent background popup.style.backgroundColor = "white"; } popup.style.borderWidth = "0px"; popup.style.width = "100%"; browserWrap.appendChild(popup); if (features.indexOf("location=yes") !== -1 || features.indexOf("location") === -1) { popup.style.height = "calc(100% - 70px)"; navigationButtonsDiv = document.createElement("div"); navigationButtonsDiv.className = "inappbrowser-app-bar"; navigationButtonsDiv.onclick = function (e) { e.cancelBubble = true; }; navigationButtonsDivInner = document.createElement("div"); navigationButtonsDivInner.className = "inappbrowser-app-bar-inner"; navigationButtonsDivInner.onclick = function (e) { e.cancelBubble = true; }; backButton = document.createElement("div"); backButton.innerText = "back"; backButton.className = "app-bar-action action-back"; backButton.addEventListener("click", function (e) { if (popup.canGoBack) popup.goBack(); }); forwardButton = document.createElement("div"); forwardButton.innerText = "forward"; forwardButton.className = "app-bar-action action-forward"; forwardButton.addEventListener("click", function (e) { if (popup.canGoForward) popup.goForward(); }); closeButton = document.createElement("div"); closeButton.innerText = "close"; closeButton.className = "app-bar-action action-close"; closeButton.addEventListener("click", function (e) { setTimeout(function () { IAB.close(navigationEventsCallback); }, 0); }); if (!isWebViewAvailable) { // iframe navigation is not yet supported backButton.setAttribute("disabled", "true"); forwardButton.setAttribute("disabled", "true"); } navigationButtonsDivInner.appendChild(backButton); navigationButtonsDivInner.appendChild(forwardButton); navigationButtonsDivInner.appendChild(closeButton); navigationButtonsDiv.appendChild(navigationButtonsDivInner); browserWrap.appendChild(navigationButtonsDiv); } else { popup.style.height = "100%"; } // start listening for navigation events attachNavigationEvents(popup, navigationEventsCallback); if (isWebViewAvailable) { strUrl = strUrl.replace("ms-appx://", "ms-appx-web://"); } popup.src = strUrl; } }); }, injectScriptCode: function (win, fail, args) { setImmediate(function () { var code = args[0], hasCallback = args[1]; if (isWebViewAvailable && browserWrap && popup) { var op = popup.invokeScriptAsync("eval", code); op.oncomplete = function (e) { if (hasCallback) { // return null if event target is unavailable by some reason var result = (e && e.target) ? [e.target.result] : [null]; win(result); } }; op.onerror = function () { }; op.start(); } }); }, injectScriptFile: function (win, fail, args) { setImmediate(function () { var filePath = args[0], hasCallback = args[1]; if (!!filePath) { filePath = urlutil.makeAbsolute(filePath); } if (isWebViewAvailable && browserWrap && popup) { var uri = new Windows.Foundation.Uri(filePath); Windows.Storage.StorageFile.getFileFromApplicationUriAsync(uri).done(function (file) { Windows.Storage.FileIO.readTextAsync(file).done(function (code) { var op = popup.invokeScriptAsync("eval", code); op.oncomplete = function(e) { if (hasCallback) { var result = [e.target.result]; win(result); } }; op.onerror = function () { }; op.start(); }); }); } }); }, injectStyleCode: function (win, fail, args) { setImmediate(function () { var code = args[0], hasCallback = args[1]; if (isWebViewAvailable && browserWrap && popup) { injectCSS(popup, code, hasCallback && win); } }); }, injectStyleFile: function (win, fail, args) { setImmediate(function () { var filePath = args[0], hasCallback = args[1]; filePath = filePath && urlutil.makeAbsolute(filePath); if (isWebViewAvailable && browserWrap && popup) { var uri = new Windows.Foundation.Uri(filePath); Windows.Storage.StorageFile.getFileFromApplicationUriAsync(uri).then(function (file) { return Windows.Storage.FileIO.readTextAsync(file); }).done(function (code) { injectCSS(popup, code, hasCallback && win); }, function () { // no-op, just catch an error }); } }); } }; function injectCSS (webView, cssCode, callback) { // This will automatically escape all thing that we need (quotes, slashes, etc.) var escapedCode = JSON.stringify(cssCode); var evalWrapper = "(function(d){var c=d.createElement('style');c.innerHTML=%s;d.head.appendChild(c);})(document)" .replace('%s', escapedCode); var op = webView.invokeScriptAsync("eval", evalWrapper); op.oncomplete = function() { if (callback) { callback([]); } }; op.onerror = function () { }; op.start(); } module.exports = IAB; require("cordova/exec/proxy").add("InAppBrowser", module.exports);
aroegies/trecrts-tools
trecrts-mobile-app/plugins/cordova-plugin-inappbrowser/src/windows/InAppBrowserProxy.js
JavaScript
apache-2.0
13,645
cask 'mplayer-osx-extended' do version 'rev15' sha256 '7979f2369730d389ceb4ec3082c65ffa3ec70f812f0699a2ef8acbae958a5c93' # github.com is the official download host per the vendor homepage url "https://github.com/sttz/MPlayer-OSX-Extended/releases/download/#{version}/MPlayer-OSX-Extended_#{version}.zip" appcast 'https://github.com/sttz/MPlayer-OSX-Extended/releases.atom', checkpoint: '97a7842a97b15d35ed296f0917e0c6ebdf9f5c54f978e15bf419134bac7bf232' name 'MPlayer OSX Extended' homepage 'http://www.mplayerosx.ch/' license :gpl app 'MPlayer OSX Extended.app' zap delete: '~/.mplayer' end
elnappo/homebrew-cask
Casks/mplayer-osx-extended.rb
Ruby
bsd-2-clause
624
"use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var AsyncAction_1 = require('./AsyncAction'); var AsyncScheduler_1 = require('./AsyncScheduler'); var VirtualTimeScheduler = (function (_super) { __extends(VirtualTimeScheduler, _super); function VirtualTimeScheduler(SchedulerAction, maxFrames) { var _this = this; if (SchedulerAction === void 0) { SchedulerAction = VirtualAction; } if (maxFrames === void 0) { maxFrames = Number.POSITIVE_INFINITY; } _super.call(this, SchedulerAction, function () { return _this.frame; }); this.maxFrames = maxFrames; this.frame = 0; this.index = -1; } /** * Prompt the Scheduler to execute all of its queued actions, therefore * clearing its queue. * @return {void} */ VirtualTimeScheduler.prototype.flush = function () { var _a = this, actions = _a.actions, maxFrames = _a.maxFrames; var error, action; while ((action = actions.shift()) && (this.frame = action.delay) <= maxFrames) { if (error = action.execute(action.state, action.delay)) { break; } } if (error) { while (action = actions.shift()) { action.unsubscribe(); } throw error; } }; VirtualTimeScheduler.frameTimeFactor = 10; return VirtualTimeScheduler; }(AsyncScheduler_1.AsyncScheduler)); exports.VirtualTimeScheduler = VirtualTimeScheduler; /** * We need this JSDoc comment for affecting ESDoc. * @ignore * @extends {Ignored} */ var VirtualAction = (function (_super) { __extends(VirtualAction, _super); function VirtualAction(scheduler, work, index) { if (index === void 0) { index = scheduler.index += 1; } _super.call(this, scheduler, work); this.scheduler = scheduler; this.work = work; this.index = index; this.index = scheduler.index = index; } VirtualAction.prototype.schedule = function (state, delay) { if (delay === void 0) { delay = 0; } if (!this.id) { return _super.prototype.schedule.call(this, state, delay); } // If an action is rescheduled, we save allocations by mutating its state, // pushing it to the end of the scheduler queue, and recycling the action. // But since the VirtualTimeScheduler is used for testing, VirtualActions // must be immutable so they can be inspected later. var action = new VirtualAction(this.scheduler, this.work); this.add(action); return action.schedule(state, delay); }; VirtualAction.prototype.requestAsyncId = function (scheduler, id, delay) { if (delay === void 0) { delay = 0; } this.delay = scheduler.frame + delay; var actions = scheduler.actions; actions.push(this); actions.sort(VirtualAction.sortActions); return true; }; VirtualAction.prototype.recycleAsyncId = function (scheduler, id, delay) { if (delay === void 0) { delay = 0; } return undefined; }; VirtualAction.sortActions = function (a, b) { if (a.delay === b.delay) { if (a.index === b.index) { return 0; } else if (a.index > b.index) { return 1; } else { return -1; } } else if (a.delay > b.delay) { return 1; } else { return -1; } }; return VirtualAction; }(AsyncAction_1.AsyncAction)); exports.VirtualAction = VirtualAction; //# sourceMappingURL=VirtualTimeScheduler.js.map
diegojromerolopez/djanban
src/djanban/static/angularapps/taskboard/node_modules/rxjs/scheduler/VirtualTimeScheduler.js
JavaScript
mit
3,914
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/menu_manager_factory.h" #include "chrome/browser/extensions/menu_manager.h" #include "chrome/browser/profiles/profile.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "extensions/browser/extension_system.h" #include "extensions/browser/extension_system_provider.h" #include "extensions/browser/extensions_browser_client.h" namespace extensions { // static MenuManager* MenuManagerFactory::GetForBrowserContext( content::BrowserContext* context) { return static_cast<MenuManager*>( GetInstance()->GetServiceForBrowserContext(context, true)); } // static MenuManagerFactory* MenuManagerFactory::GetInstance() { return Singleton<MenuManagerFactory>::get(); } // static KeyedService* MenuManagerFactory::BuildServiceInstanceForTesting( content::BrowserContext* context) { return GetInstance()->BuildServiceInstanceFor(context); } MenuManagerFactory::MenuManagerFactory() : BrowserContextKeyedServiceFactory( "MenuManager", BrowserContextDependencyManager::GetInstance()) { DependsOn(ExtensionsBrowserClient::Get()->GetExtensionSystemFactory()); } MenuManagerFactory::~MenuManagerFactory() {} KeyedService* MenuManagerFactory::BuildServiceInstanceFor( content::BrowserContext* context) const { Profile* profile = Profile::FromBrowserContext(context); return new MenuManager(profile, ExtensionSystem::Get(profile)->state_store()); } content::BrowserContext* MenuManagerFactory::GetBrowserContextToUse( content::BrowserContext* context) const { return ExtensionsBrowserClient::Get()->GetOriginalContext(context); } bool MenuManagerFactory::ServiceIsCreatedWithBrowserContext() const { return true; } bool MenuManagerFactory::ServiceIsNULLWhileTesting() const { return true; } } // namespace extensions
s20121035/rk3288_android5.1_repo
external/chromium_org/chrome/browser/extensions/menu_manager_factory.cc
C++
gpl-3.0
2,014
############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.osv import osv from openerp import netsvc from openerp.tools.translate import _ class procurement_order(osv.osv): _inherit = 'procurement.order' def check_buy(self, cr, uid, ids, context=None): for procurement in self.browse(cr, uid, ids, context=context): for line in procurement.product_id.flow_pull_ids: if line.location_id==procurement.location_id: return line.type_proc=='buy' return super(procurement_order, self).check_buy(cr, uid, ids) def check_produce(self, cr, uid, ids, context=None): for procurement in self.browse(cr, uid, ids, context=context): for line in procurement.product_id.flow_pull_ids: if line.location_id==procurement.location_id: return line.type_proc=='produce' return super(procurement_order, self).check_produce(cr, uid, ids) def check_move(self, cr, uid, ids, context=None): for procurement in self.browse(cr, uid, ids, context=context): for line in procurement.product_id.flow_pull_ids: if line.location_id==procurement.location_id: return (line.type_proc=='move') and (line.location_src_id) return False def action_move_create(self, cr, uid, ids, context=None): proc_obj = self.pool.get('procurement.order') move_obj = self.pool.get('stock.move') picking_obj=self.pool.get('stock.picking') wf_service = netsvc.LocalService("workflow") for proc in proc_obj.browse(cr, uid, ids, context=context): line = None for line in proc.product_id.flow_pull_ids: if line.location_id == proc.location_id: break assert line, 'Line cannot be False if we are on this state of the workflow' origin = (proc.origin or proc.name or '').split(':')[0] +':'+line.name picking_id = picking_obj.create(cr, uid, { 'origin': origin, 'company_id': line.company_id and line.company_id.id or False, 'type': line.picking_type, 'stock_journal_id': line.journal_id and line.journal_id.id or False, 'move_type': 'one', 'partner_id': line.partner_address_id.id, 'note': _('Picking for pulled procurement coming from original location %s, pull rule %s, via original Procurement %s (#%d)') % (proc.location_id.name, line.name, proc.name, proc.id), 'invoice_state': line.invoice_state, }) move_id = move_obj.create(cr, uid, { 'name': line.name, 'picking_id': picking_id, 'company_id': line.company_id and line.company_id.id or False, 'product_id': proc.product_id.id, 'date': proc.date_planned, 'product_qty': proc.product_qty, 'product_uom': proc.product_uom.id, 'product_uos_qty': (proc.product_uos and proc.product_uos_qty)\ or proc.product_qty, 'product_uos': (proc.product_uos and proc.product_uos.id)\ or proc.product_uom.id, 'partner_id': line.partner_address_id.id, 'location_id': line.location_src_id.id, 'location_dest_id': line.location_id.id, 'move_dest_id': proc.move_id and proc.move_id.id or False, # to verif, about history ? 'tracking_id': False, 'cancel_cascade': line.cancel_cascade, 'state': 'confirmed', 'note': _('Move for pulled procurement coming from original location %s, pull rule %s, via original Procurement %s (#%d)') % (proc.location_id.name, line.name, proc.name, proc.id), }) if proc.move_id and proc.move_id.state in ('confirmed'): move_obj.write(cr,uid, [proc.move_id.id], { 'state':'waiting' }, context=context) proc_id = proc_obj.create(cr, uid, { 'name': line.name, 'origin': origin, 'note': _('Pulled procurement coming from original location %s, pull rule %s, via original Procurement %s (#%d)') % (proc.location_id.name, line.name, proc.name, proc.id), 'company_id': line.company_id and line.company_id.id or False, 'date_planned': proc.date_planned, 'product_id': proc.product_id.id, 'product_qty': proc.product_qty, 'product_uom': proc.product_uom.id, 'product_uos_qty': (proc.product_uos and proc.product_uos_qty)\ or proc.product_qty, 'product_uos': (proc.product_uos and proc.product_uos.id)\ or proc.product_uom.id, 'location_id': line.location_src_id.id, 'procure_method': line.procure_method, 'move_id': move_id, }) wf_service = netsvc.LocalService("workflow") wf_service.trg_validate(uid, 'stock.picking', picking_id, 'button_confirm', cr) wf_service.trg_validate(uid, 'procurement.order', proc_id, 'button_confirm', cr) if proc.move_id: move_obj.write(cr, uid, [proc.move_id.id], {'location_id':proc.location_id.id}) msg = _('Pulled from another location.') self.write(cr, uid, [proc.id], {'state':'running', 'message': msg}) self.message_post(cr, uid, [proc.id], body=msg, context=context) # trigger direct processing (the new procurement shares the same planned date as the original one, which is already being processed) wf_service.trg_validate(uid, 'procurement.order', proc_id, 'button_check', cr) return False procurement_order() # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
jeffery9/mixprint_addons
stock_location/procurement_pull.py
Python
agpl-3.0
6,951
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ var Core = _dereq_('../lib/Core'), ShimIE8 = _dereq_('../lib/Shim.IE8'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/Core":4,"../lib/Shim.IE8":27}],2:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); var BinaryTree = function (data, compareFunc, hashFunc) { this.init.apply(this, arguments); }; BinaryTree.prototype.init = function (data, index, compareFunc, hashFunc) { this._store = []; this._keys = []; if (index !== undefined) { this.index(index); } if (compareFunc !== undefined) { this.compareFunc(compareFunc); } if (hashFunc !== undefined) { this.hashFunc(hashFunc); } if (data !== undefined) { this.data(data); } }; Shared.addModule('BinaryTree', BinaryTree); Shared.mixin(BinaryTree.prototype, 'Mixin.ChainReactor'); Shared.mixin(BinaryTree.prototype, 'Mixin.Sorting'); Shared.mixin(BinaryTree.prototype, 'Mixin.Common'); Shared.synthesize(BinaryTree.prototype, 'compareFunc'); Shared.synthesize(BinaryTree.prototype, 'hashFunc'); Shared.synthesize(BinaryTree.prototype, 'indexDir'); Shared.synthesize(BinaryTree.prototype, 'keys'); Shared.synthesize(BinaryTree.prototype, 'index', function (index) { if (index !== undefined) { // Convert the index object to an array of key val objects this.keys(this.extractKeys(index)); } return this.$super.call(this, index); }); BinaryTree.prototype.extractKeys = function (obj) { var i, keys = []; for (i in obj) { if (obj.hasOwnProperty(i)) { keys.push({ key: i, val: obj[i] }); } } return keys; }; BinaryTree.prototype.data = function (val) { if (val !== undefined) { this._data = val; if (this._hashFunc) { this._hash = this._hashFunc(val); } return this; } return this._data; }; /** * Pushes an item to the binary tree node's store array. * @param {*} val The item to add to the store. * @returns {*} */ BinaryTree.prototype.push = function (val) { if (val !== undefined) { this._store.push(val); return this; } return false; }; /** * Pulls an item from the binary tree node's store array. * @param {*} val The item to remove from the store. * @returns {*} */ BinaryTree.prototype.pull = function (val) { if (val !== undefined) { var index = this._store.indexOf(val); if (index > -1) { this._store.splice(index, 1); return this; } } return false; }; /** * Default compare method. Can be overridden. * @param a * @param b * @returns {number} * @private */ BinaryTree.prototype._compareFunc = function (a, b) { // Loop the index array var i, indexData, result = 0; for (i = 0; i < this._keys.length; i++) { indexData = this._keys[i]; if (indexData.val === 1) { result = this.sortAsc(a[indexData.key], b[indexData.key]); } else if (indexData.val === -1) { result = this.sortDesc(a[indexData.key], b[indexData.key]); } if (result !== 0) { return result; } } return result; }; /** * Default hash function. Can be overridden. * @param obj * @private */ BinaryTree.prototype._hashFunc = function (obj) { /*var i, indexData, hash = ''; for (i = 0; i < this._keys.length; i++) { indexData = this._keys[i]; if (hash) { hash += '_'; } hash += obj[indexData.key]; } return hash;*/ return obj[this._keys[0].key]; }; BinaryTree.prototype.insert = function (data) { var result, inserted, failed, i; if (data instanceof Array) { // Insert array of data inserted = []; failed = []; for (i = 0; i < data.length; i++) { if (this.insert(data[i])) { inserted.push(data[i]); } else { failed.push(data[i]); } } return { inserted: inserted, failed: failed }; } if (!this._data) { // Insert into this node (overwrite) as there is no data this.data(data); //this.push(data); return true; } result = this._compareFunc(this._data, data); if (result === 0) { this.push(data); // Less than this node if (this._left) { // Propagate down the left branch this._left.insert(data); } else { // Assign to left branch this._left = new BinaryTree(data, this._index, this._compareFunc, this._hashFunc); } return true; } if (result === -1) { // Greater than this node if (this._right) { // Propagate down the right branch this._right.insert(data); } else { // Assign to right branch this._right = new BinaryTree(data, this._index, this._compareFunc, this._hashFunc); } return true; } if (result === 1) { // Less than this node if (this._left) { // Propagate down the left branch this._left.insert(data); } else { // Assign to left branch this._left = new BinaryTree(data, this._index, this._compareFunc, this._hashFunc); } return true; } return false; }; BinaryTree.prototype.lookup = function (data, resultArr) { var result = this._compareFunc(this._data, data); resultArr = resultArr || []; if (result === 0) { if (this._left) { this._left.lookup(data, resultArr); } resultArr.push(this._data); if (this._right) { this._right.lookup(data, resultArr); } } if (result === -1) { if (this._right) { this._right.lookup(data, resultArr); } } if (result === 1) { if (this._left) { this._left.lookup(data, resultArr); } } return resultArr; }; BinaryTree.prototype.inOrder = function (type, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.inOrder(type, resultArr); } switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } if (this._right) { this._right.inOrder(type, resultArr); } return resultArr; }; /*BinaryTree.prototype.find = function (type, search, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.find(type, search, resultArr); } // Check if this node's data is greater or less than the from value var fromResult = this.sortAsc(this._data[key], from), toResult = this.sortAsc(this._data[key], to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.find(type, search, resultArr); } return resultArr; };*/ /** * * @param {String} type * @param {String} key The data key / path to range search against. * @param {Number} from Range search from this value (inclusive) * @param {Number} to Range search to this value (inclusive) * @param {Array=} resultArr Leave undefined when calling (internal use), * passes the result array between recursive calls to be returned when * the recursion chain completes. * @param {Path=} pathResolver Leave undefined when calling (internal use), * caches the path resolver instance for performance. * @returns {Array} Array of matching document objects */ BinaryTree.prototype.findRange = function (type, key, from, to, resultArr, pathResolver) { resultArr = resultArr || []; pathResolver = pathResolver || new Path(key); if (this._left) { this._left.findRange(type, key, from, to, resultArr, pathResolver); } // Check if this node's data is greater or less than the from value var pathVal = pathResolver.value(this._data), fromResult = this.sortAsc(pathVal, from), toResult = this.sortAsc(pathVal, to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.findRange(type, key, from, to, resultArr, pathResolver); } return resultArr; }; /*BinaryTree.prototype.findRegExp = function (type, key, pattern, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.findRegExp(type, key, pattern, resultArr); } // Check if this node's data is greater or less than the from value var fromResult = this.sortAsc(this._data[key], from), toResult = this.sortAsc(this._data[key], to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.findRegExp(type, key, pattern, resultArr); } return resultArr; };*/ BinaryTree.prototype.match = function (query, options) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var pathSolver = new Path(), indexKeyArr, queryArr, matchedKeys = [], matchedKeyCount = 0, i; indexKeyArr = pathSolver.parseArr(this._index, { verbose: true }); queryArr = pathSolver.parseArr(query, { ignore:/\$/, verbose: true }); // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return pathSolver.countObjectPaths(this._keys, query); }; Shared.finishModule('BinaryTree'); module.exports = BinaryTree; },{"./Path":23,"./Shared":26}],3:[function(_dereq_,module,exports){ "use strict"; var Shared, Db, Metrics, KeyValueStore, Path, IndexHashMap, IndexBinaryTree, Crc, Overload, ReactorIO; Shared = _dereq_('./Shared'); /** * Creates a new collection. Collections store multiple documents and * handle CRUD against those documents. * @constructor */ var Collection = function (name) { this.init.apply(this, arguments); }; Collection.prototype.init = function (name, options) { this._primaryKey = '_id'; this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._name = name; this._data = []; this._metrics = new Metrics(); this._options = options || { changeTimestamp: false }; // Create an object to store internal protected data this._metaData = {}; this._deferQueue = { insert: [], update: [], remove: [], upsert: [], async: [] }; this._deferThreshold = { insert: 100, update: 100, remove: 100, upsert: 100 }; this._deferTime = { insert: 1, update: 1, remove: 1, upsert: 1 }; this._deferredCalls = true; // Set the subset to itself since it is the root collection this.subsetOf(this); }; Shared.addModule('Collection', Collection); Shared.mixin(Collection.prototype, 'Mixin.Common'); Shared.mixin(Collection.prototype, 'Mixin.Events'); Shared.mixin(Collection.prototype, 'Mixin.ChainReactor'); Shared.mixin(Collection.prototype, 'Mixin.CRUD'); Shared.mixin(Collection.prototype, 'Mixin.Constants'); Shared.mixin(Collection.prototype, 'Mixin.Triggers'); Shared.mixin(Collection.prototype, 'Mixin.Sorting'); Shared.mixin(Collection.prototype, 'Mixin.Matching'); Shared.mixin(Collection.prototype, 'Mixin.Updating'); Shared.mixin(Collection.prototype, 'Mixin.Tags'); Metrics = _dereq_('./Metrics'); KeyValueStore = _dereq_('./KeyValueStore'); Path = _dereq_('./Path'); IndexHashMap = _dereq_('./IndexHashMap'); IndexBinaryTree = _dereq_('./IndexBinaryTree'); Crc = _dereq_('./Crc'); Db = Shared.modules.Db; Overload = _dereq_('./Overload'); ReactorIO = _dereq_('./ReactorIO'); /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Collection.prototype.crc = Crc; /** * Gets / sets the deferred calls flag. If set to true (default) * then operations on large data sets can be broken up and done * over multiple CPU cycles (creating an async state). For purely * synchronous behaviour set this to false. * @param {Boolean=} val The value to set. * @returns {Boolean} */ Shared.synthesize(Collection.prototype, 'deferredCalls'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'state'); /** * Gets / sets the name of the collection. * @param {String=} val The name of the collection to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'name'); /** * Gets / sets the metadata stored in the collection. */ Shared.synthesize(Collection.prototype, 'metaData'); /** * Gets / sets boolean to determine if the collection should be * capped or not. */ Shared.synthesize(Collection.prototype, 'capped'); /** * Gets / sets capped collection size. This is the maximum number * of records that the capped collection will store. */ Shared.synthesize(Collection.prototype, 'cappedSize'); Collection.prototype._asyncPending = function (key) { this._deferQueue.async.push(key); }; Collection.prototype._asyncComplete = function (key) { // Remove async flag for this type var index = this._deferQueue.async.indexOf(key); while (index > -1) { this._deferQueue.async.splice(index, 1); index = this._deferQueue.async.indexOf(key); } if (this._deferQueue.async.length === 0) { this.deferEmit('ready'); } }; /** * Get the data array that represents the collection's data. * This data is returned by reference and should not be altered outside * of the provided CRUD functionality of the collection as doing so * may cause unstable index behaviour within the collection. * @returns {Array} */ Collection.prototype.data = function () { return this._data; }; /** * Drops a collection and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ Collection.prototype.drop = function (callback) { var key; if (!this.isDropped()) { if (this._db && this._db._collection && this._name) { if (this.debug()) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; this.emit('drop', this); delete this._db._collection[this._name]; // Remove any reactor IO chain links if (this._collate) { for (key in this._collate) { if (this._collate.hasOwnProperty(key)) { this.collateRemove(key); } } } delete this._primaryKey; delete this._primaryIndex; delete this._primaryCrc; delete this._crcLookup; delete this._name; delete this._data; delete this._metrics; delete this._listeners; if (callback) { callback(false, true); } return true; } } else { if (callback) { callback(false, true); } return true; } if (callback) { callback(false, true); } return false; }; /** * Gets / sets the primary key for this collection. * @param {String=} keyName The name of the primary key. * @returns {*} */ Collection.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { if (this._primaryKey !== keyName) { var oldKey = this._primaryKey; this._primaryKey = keyName; // Set the primary key index primary key this._primaryIndex.primaryKey(keyName); // Rebuild the primary key index this.rebuildPrimaryKeyIndex(); // Propagate change down the chain this.chainSend('primaryKey', keyName, {oldData: oldKey}); } return this; } return this._primaryKey; }; /** * Handles insert events and routes changes to binds and views as required. * @param {Array} inserted An array of inserted documents. * @param {Array} failed An array of documents that failed to insert. * @private */ Collection.prototype._onInsert = function (inserted, failed) { this.emit('insert', inserted, failed); }; /** * Handles update events and routes changes to binds and views as required. * @param {Array} items An array of updated documents. * @private */ Collection.prototype._onUpdate = function (items) { this.emit('update', items); }; /** * Handles remove events and routes changes to binds and views as required. * @param {Array} items An array of removed documents. * @private */ Collection.prototype._onRemove = function (items) { this.emit('remove', items); }; /** * Handles any change to the collection. * @private */ Collection.prototype._onChange = function () { if (this._options.changeTimestamp) { // Record the last change timestamp this._metaData.lastChange = new Date(); } }; /** * Gets / sets the db instance this class instance belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(Collection.prototype, 'db', function (db) { if (db) { if (this.primaryKey() === '_id') { // Set primary key to the db's key by default this.primaryKey(db.primaryKey()); // Apply the same debug settings this.debug(db.debug()); } } return this.$super.apply(this, arguments); }); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Collection.prototype, 'mongoEmulation'); /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set. * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param options Optional options object. * @param callback Optional callback function. */ Collection.prototype.setData = function (data, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (data) { var op = this._metrics.create('setData'); op.start(); options = this.options(options); this.preSetData(data, options, callback); if (options.$decouple) { data = this.decouple(data); } if (!(data instanceof Array)) { data = [data]; } op.time('transformIn'); data = this.transformIn(data); op.time('transformIn'); var oldData = [].concat(this._data); this._dataReplace(data); // Update the primary key index op.time('Rebuild Primary Key Index'); this.rebuildPrimaryKeyIndex(options); op.time('Rebuild Primary Key Index'); // Rebuild all other indexes op.time('Rebuild All Other Indexes'); this._rebuildIndexes(); op.time('Rebuild All Other Indexes'); op.time('Resolve chains'); this.chainSend('setData', data, {oldData: oldData}); op.time('Resolve chains'); op.stop(); this._onChange(); this.emit('setData', this._data, oldData); } if (callback) { callback(false); } return this; }; /** * Drops and rebuilds the primary key index for all documents in the collection. * @param {Object=} options An optional options object. * @private */ Collection.prototype.rebuildPrimaryKeyIndex = function (options) { options = options || { $ensureKeys: undefined, $violationCheck: undefined }; var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true, violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true, arr, arrCount, arrItem, pIndex = this._primaryIndex, crcIndex = this._primaryCrc, crcLookup = this._crcLookup, pKey = this._primaryKey, jString; // Drop the existing primary index pIndex.truncate(); crcIndex.truncate(); crcLookup.truncate(); // Loop the data and check for a primary key in each object arr = this._data; arrCount = arr.length; while (arrCount--) { arrItem = arr[arrCount]; if (ensureKeys) { // Make sure the item has a primary key this.ensurePrimaryKey(arrItem); } if (violationCheck) { // Check for primary key violation if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) { // Primary key violation throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]); } } else { pIndex.set(arrItem[pKey], arrItem); } // Generate a CRC string jString = this.jStringify(arrItem); crcIndex.set(arrItem[pKey], jString); crcLookup.set(jString, arrItem); } }; /** * Checks for a primary key on the document and assigns one if none * currently exists. * @param {Object} obj The object to check a primary key against. * @private */ Collection.prototype.ensurePrimaryKey = function (obj) { if (obj[this._primaryKey] === undefined) { // Assign a primary key automatically obj[this._primaryKey] = this.objectId(); } }; /** * Clears all data from the collection. * @returns {Collection} */ Collection.prototype.truncate = function () { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } this.emit('truncate', this._data); // Clear all the data from the collection this._data.length = 0; // Re-create the primary index data this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._onChange(); this.deferEmit('change', {type: 'truncate'}); return this; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} obj The document object to upsert or an array containing * documents to upsert. * * If the document contains a primary key field (based on the collections's primary * key) then the database will search for an existing document with a matching id. * If a matching document is found, the document will be updated. Any keys that * match keys on the existing document will be overwritten with new data. Any keys * that do not currently exist on the document will be added to the document. * * If the document does not contain an id or the id passed does not match an existing * document, an insert is performed instead. If no id is present a new primary key * id is provided for the item. * * @param {Function=} callback Optional callback method. * @returns {Object} An object containing two keys, "op" contains either "insert" or * "update" depending on the type of operation that was performed and "result" * contains the return data from the operation used. */ Collection.prototype.upsert = function (obj, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (obj) { var queue = this._deferQueue.upsert, deferThreshold = this._deferThreshold.upsert, returnData = {}, query, i; // Determine if the object passed is an array or not if (obj instanceof Array) { if (this._deferredCalls && obj.length > deferThreshold) { // Break up upsert into blocks this._deferQueue.upsert = queue.concat(obj); this._asyncPending('upsert'); // Fire off the insert queue handler this.processQueue('upsert', callback); return {}; } else { // Loop the array and upsert each item returnData = []; for (i = 0; i < obj.length; i++) { returnData.push(this.upsert(obj[i])); } if (callback) { callback(); } return returnData; } } // Determine if the operation is an insert or an update if (obj[this._primaryKey]) { // Check if an object with this primary key already exists query = {}; query[this._primaryKey] = obj[this._primaryKey]; if (this._primaryIndex.lookup(query)[0]) { // The document already exists with this id, this operation is an update returnData.op = 'update'; } else { // No document with this id exists, this operation is an insert returnData.op = 'insert'; } } else { // The document passed does not contain an id, this operation is an insert returnData.op = 'insert'; } switch (returnData.op) { case 'insert': returnData.result = this.insert(obj); break; case 'update': returnData.result = this.update(query, obj); break; default: break; } return returnData; } else { if (callback) { callback(); } } return {}; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ Collection.prototype.filter = function (query, func, options) { return (this.find(query, options)).filter(func); }; /** * Executes a method against each document that matches query and then executes * an update based on the return data of the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the update. * @param {Object=} options Optional options object passed to the initial find call. * @returns {Array} */ Collection.prototype.filterUpdate = function (query, func, options) { var items = this.find(query, options), results = [], singleItem, singleQuery, singleUpdate, pk = this.primaryKey(), i; for (i = 0; i < items.length; i++) { singleItem = items[i]; singleUpdate = func(singleItem); if (singleUpdate) { singleQuery = {}; singleQuery[pk] = singleItem[pk]; results.push(this.update(singleQuery, singleUpdate)); } } return results; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} query The query that must be matched for a document to be * operated on. * @param {Object} update The object containing updated key/values. Any keys that * match keys on the existing document will be overwritten with this data. Any * keys that do not currently exist on the document will be added to the document. * @param {Object=} options An options object. * @returns {Array} The items that were updated. */ Collection.prototype.update = function (query, update, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // Decouple the update data update = this.decouple(update); // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); this.convertToFdb(update); } // Handle transform update = this.transformIn(update); if (this.debug()) { console.log(this.logIdentifier() + ' Updating some data'); } var self = this, op = this._metrics.create('update'), dataSet, updated, updateCall = function (referencedDoc) { var oldDoc = self.decouple(referencedDoc), newDoc, triggerOperation, result; if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) { newDoc = self.decouple(referencedDoc); triggerOperation = { type: 'update', query: self.decouple(query), update: self.decouple(update), options: self.decouple(options), op: op }; // Update newDoc with the update criteria so we know what the data will look // like AFTER the update is processed result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, ''); if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, ''); // NOTE: If for some reason we would only like to fire this event if changes are actually going // to occur on the object from the proposed update then we can add "result &&" to the if self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc); } else { // Trigger cancelled operation so tell result that it was not updated result = false; } } else { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, update, query, options, ''); } // Inform indexes of the change self._updateIndexes(oldDoc, referencedDoc); return result; }; op.start(); op.time('Retrieve documents to update'); dataSet = this.find(query, {$decouple: false}); op.time('Retrieve documents to update'); if (dataSet.length) { op.time('Update documents'); updated = dataSet.filter(updateCall); op.time('Update documents'); if (updated.length) { op.time('Resolve chains'); this.chainSend('update', { query: query, update: update, dataSet: updated }, options); op.time('Resolve chains'); this._onUpdate(updated); this._onChange(); this.deferEmit('change', {type: 'update', data: updated}); } } op.stop(); // TODO: Should we decouple the updated array before return by default? return updated || []; }; /** * Replaces an existing object with data from the new object without * breaking data references. * @param {Object} currentObj The object to alter. * @param {Object} newObj The new object to overwrite the existing one with. * @returns {*} Chain. * @private */ Collection.prototype._replaceObj = function (currentObj, newObj) { var i; // Check if the new document has a different primary key value from the existing one // Remove item from indexes this._removeFromIndexes(currentObj); // Remove existing keys from current object for (i in currentObj) { if (currentObj.hasOwnProperty(i)) { delete currentObj[i]; } } // Add new keys to current object for (i in newObj) { if (newObj.hasOwnProperty(i)) { currentObj[i] = newObj[i]; } } // Update the item in the primary index if (!this._insertIntoIndexes(currentObj)) { throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]); } // Update the object in the collection data //this._data.splice(this._data.indexOf(currentObj), 1, newObj); return this; }; /** * Helper method to update a document from it's id. * @param {String} id The id of the document. * @param {Object} update The object containing the key/values to update to. * @returns {Object} The document that was updated or undefined * if no document was updated. */ Collection.prototype.updateById = function (id, update) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.update(searchObj, update)[0]; }; /** * Internal method for document updating. * @param {Object} doc The document to update. * @param {Object} update The object with key/value pairs to update the document with. * @param {Object} query The query object that we need to match to perform an update. * @param {Object} options An options object. * @param {String} path The current recursive path. * @param {String} opType The type of update operation to perform, if none is specified * default is to set new data against matching fields. * @returns {Boolean} True if the document was updated with new / changed data or * false if it was not updated because the data was the same. * @private */ Collection.prototype.updateObject = function (doc, update, query, options, path, opType) { // TODO: This method is long, try to break it into smaller pieces update = this.decouple(update); // Clear leading dots from path path = path || ''; if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); } //var oldDoc = this.decouple(doc), var updated = false, recurseUpdated = false, operation, tmpArray, tmpIndex, tmpCount, tempIndex, tempKey, replaceObj, pk, pathInstance, sourceIsArray, updateIsArray, i; // Loop each key in the update object for (i in update) { if (update.hasOwnProperty(i)) { // Reset operation flag operation = false; // Check if the property starts with a dollar (function) if (i.substr(0, 1) === '$') { // Check for commands switch (i) { case '$key': case '$index': case '$data': case '$min': case '$max': // Ignore some operators operation = true; break; case '$each': operation = true; // Loop over the array of updates and run each one tmpCount = update.$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path); if (recurseUpdated) { updated = true; } } updated = updated || recurseUpdated; break; case '$replace': operation = true; replaceObj = update.$replace; pk = this.primaryKey(); // Loop the existing item properties and compare with // the replacement (never remove primary key) for (tempKey in doc) { if (doc.hasOwnProperty(tempKey) && tempKey !== pk) { if (replaceObj[tempKey] === undefined) { // The new document doesn't have this field, remove it from the doc this._updateUnset(doc, tempKey); updated = true; } } } // Loop the new item props and update the doc for (tempKey in replaceObj) { if (replaceObj.hasOwnProperty(tempKey) && tempKey !== pk) { this._updateOverwrite(doc, tempKey, replaceObj[tempKey]); updated = true; } } break; default: operation = true; // Now run the operation recurseUpdated = this.updateObject(doc, update[i], query, options, path, i); updated = updated || recurseUpdated; break; } } // Check if the key has a .$ at the end, denoting an array lookup if (this._isPositionalKey(i)) { operation = true; // Modify i to be the name of the field i = i.substr(0, i.length - 2); pathInstance = new Path(path + '.' + i); // Check if the key is an array and has items if (doc[i] && doc[i] instanceof Array && doc[i].length) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) { tmpArray.push(tmpIndex); } } // Loop the items that matched and update them for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } } if (!operation) { if (!opType && typeof(update[i]) === 'object') { if (doc[i] !== null && typeof(doc[i]) === 'object') { // Check if we are dealing with arrays sourceIsArray = doc[i] instanceof Array; updateIsArray = update[i] instanceof Array; if (sourceIsArray || updateIsArray) { // Check if the update is an object and the doc is an array if (!updateIsArray && sourceIsArray) { // Update is an object, source is an array so match the array items // with our query object to find the one to update inside this array // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { // Either both source and update are arrays or the update is // an array and the source is not, so set source to update if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { // The doc key is an object so traverse the // update further recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { switch (opType) { case '$inc': var doUpdate = true; // Check for a $min / $max operator if (update[i] > 0) { if (update.$max) { // Check current value if (doc[i] >= update.$max) { // Don't update doUpdate = false; } } } else if (update[i] < 0) { if (update.$min) { // Check current value if (doc[i] <= update.$min) { // Don't update doUpdate = false; } } } if (doUpdate) { this._updateIncrement(doc, i, update[i]); updated = true; } break; case '$cast': // Casts a property to the type specified if it is not already // that type. If the cast is an array or an object and the property // is not already that type a new array or object is created and // set to the property, overwriting the previous value switch (update[i]) { case 'array': if (!(doc[i] instanceof Array)) { // Cast to an array this._updateProperty(doc, i, update.$data || []); updated = true; } break; case 'object': if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) { // Cast to an object this._updateProperty(doc, i, update.$data || {}); updated = true; } break; case 'number': if (typeof doc[i] !== 'number') { // Cast to a number this._updateProperty(doc, i, Number(doc[i])); updated = true; } break; case 'string': if (typeof doc[i] !== 'string') { // Cast to a string this._updateProperty(doc, i, String(doc[i])); updated = true; } break; default: throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]); } break; case '$push': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Check for a $position modifier with an $each if (update[i].$position !== undefined && update[i].$each instanceof Array) { // Grab the position to insert at tempIndex = update[i].$position; // Loop the each array and push each item tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]); } } else if (update[i].$each instanceof Array) { // Do a loop over the each to push multiple items tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updatePush(doc[i], update[i].$each[tmpIndex]); } } else { // Do a standard push this._updatePush(doc[i], update[i]); } updated = true; } else { throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')'); } break; case '$pull': if (doc[i] instanceof Array) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { tmpArray.push(tmpIndex); } } tmpCount = tmpArray.length; // Now loop the pull array and remove items to be pulled while (tmpCount--) { this._updatePull(doc[i], tmpArray[tmpCount]); updated = true; } } break; case '$pullAll': if (doc[i] instanceof Array) { if (update[i] instanceof Array) { tmpArray = doc[i]; tmpCount = tmpArray.length; if (tmpCount > 0) { // Now loop the pull array and remove items to be pulled while (tmpCount--) { for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) { if (tmpArray[tmpCount] === update[i][tempIndex]) { this._updatePull(doc[i], tmpCount); tmpCount--; updated = true; } } if (tmpCount < 0) { break; } } } } else { throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')'); } } break; case '$addToSet': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Loop the target array and check for existence of item var targetArr = doc[i], targetArrIndex, targetArrCount = targetArr.length, objHash, addObj = true, optionObj = (options && options.$addToSet), hashMode, pathSolver; // Check if we have an options object for our operation if (update[i].$key) { hashMode = false; pathSolver = new Path(update[i].$key); objHash = pathSolver.value(update[i])[0]; // Remove the key from the object before we add it delete update[i].$key; } else if (optionObj && optionObj.key) { hashMode = false; pathSolver = new Path(optionObj.key); objHash = pathSolver.value(update[i])[0]; } else { objHash = this.jStringify(update[i]); hashMode = true; } for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) { if (hashMode) { // Check if objects match via a string hash (JSON) if (this.jStringify(targetArr[targetArrIndex]) === objHash) { // The object already exists, don't add it addObj = false; break; } } else { // Check if objects match based on the path if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) { // The object already exists, don't add it addObj = false; break; } } } if (addObj) { this._updatePush(doc[i], update[i]); updated = true; } } else { throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')'); } break; case '$splicePush': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { tempIndex = update.$index; if (tempIndex !== undefined) { delete update.$index; // Check for out of bounds index if (tempIndex > doc[i].length) { tempIndex = doc[i].length; } this._updateSplicePush(doc[i], tempIndex, update[i]); updated = true; } else { throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!'); } } else { throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')'); } break; case '$move': if (doc[i] instanceof Array) { // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { var moveToIndex = update.$index; if (moveToIndex !== undefined) { delete update.$index; this._updateSpliceMove(doc[i], tmpIndex, moveToIndex); updated = true; } else { throw(this.logIdentifier() + ' Cannot move without a $index integer value!'); } break; } } } else { throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')'); } break; case '$mul': this._updateMultiply(doc, i, update[i]); updated = true; break; case '$rename': this._updateRename(doc, i, update[i]); updated = true; break; case '$overwrite': this._updateOverwrite(doc, i, update[i]); updated = true; break; case '$unset': this._updateUnset(doc, i); updated = true; break; case '$clear': this._updateClear(doc, i); updated = true; break; case '$pop': if (doc[i] instanceof Array) { if (this._updatePop(doc[i], update[i])) { updated = true; } } else { throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')'); } break; case '$toggle': // Toggle the boolean property between true and false this._updateProperty(doc, i, !doc[i]); updated = true; break; default: if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } break; } } } } } return updated; }; /** * Determines if the passed key has an array positional mark (a dollar at the end * of its name). * @param {String} key The key to check. * @returns {Boolean} True if it is a positional or false if not. * @private */ Collection.prototype._isPositionalKey = function (key) { return key.substr(key.length - 2, 2) === '.$'; }; /** * Removes any documents from the collection that match the search query * key/values. * @param {Object} query The query object. * @param {Object=} options An options object. * @param {Function=} callback A callback method. * @returns {Array} An array of the documents that were removed. */ Collection.prototype.remove = function (query, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var self = this, dataSet, index, arrIndex, returnArr, removeMethod, triggerOperation, doc, newDoc; if (typeof(options) === 'function') { callback = options; options = {}; } // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (query instanceof Array) { returnArr = []; for (arrIndex = 0; arrIndex < query.length; arrIndex++) { returnArr.push(this.remove(query[arrIndex], {noEmit: true})); } if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } if (callback) { callback(false, returnArr); } return returnArr; } else { returnArr = []; dataSet = this.find(query, {$decouple: false}); if (dataSet.length) { removeMethod = function (dataItem) { // Remove the item from the collection's indexes self._removeFromIndexes(dataItem); // Remove data from internal stores index = self._data.indexOf(dataItem); self._dataRemoveAtIndex(index); returnArr.push(dataItem); }; // Remove the data from the collection for (var i = 0; i < dataSet.length; i++) { doc = dataSet[i]; if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) { triggerOperation = { type: 'remove' }; newDoc = self.decouple(doc); if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) { // The trigger didn't ask to cancel so execute the removal method removeMethod(doc); self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc); } } else { // No triggers to execute removeMethod(doc); } } if (returnArr.length) { //op.time('Resolve chains'); self.chainSend('remove', { query: query, dataSet: returnArr }, options); //op.time('Resolve chains'); if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } this._onChange(); this.deferEmit('change', {type: 'remove', data: returnArr}); } } if (callback) { callback(false, returnArr); } return returnArr; } }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. * @returns {Object} The document that was removed or undefined if * nothing was removed. */ Collection.prototype.removeById = function (id) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.remove(searchObj)[0]; }; /** * Processes a deferred action queue. * @param {String} type The queue name to process. * @param {Function} callback A method to call when the queue has processed. * @param {Object=} resultObj A temp object to hold results in. */ Collection.prototype.processQueue = function (type, callback, resultObj) { var self = this, queue = this._deferQueue[type], deferThreshold = this._deferThreshold[type], deferTime = this._deferTime[type], dataArr, result; resultObj = resultObj || { deferred: true }; if (queue.length) { // Process items up to the threshold if (queue.length > deferThreshold) { // Grab items up to the threshold value dataArr = queue.splice(0, deferThreshold); } else { // Grab all the remaining items dataArr = queue.splice(0, queue.length); } result = self[type](dataArr); switch (type) { case 'insert': resultObj.inserted = resultObj.inserted || []; resultObj.failed = resultObj.failed || []; resultObj.inserted = resultObj.inserted.concat(result.inserted); resultObj.failed = resultObj.failed.concat(result.failed); break; } // Queue another process setTimeout(function () { self.processQueue.call(self, type, callback, resultObj); }, deferTime); } else { if (callback) { callback(resultObj); } this._asyncComplete(type); } // Check if all queues are complete if (!this.isProcessingQueue()) { this.deferEmit('queuesComplete'); } }; /** * Checks if any CRUD operations have been deferred and are still waiting to * be processed. * @returns {Boolean} True if there are still deferred CRUD operations to process * or false if all queues are clear. */ Collection.prototype.isProcessingQueue = function () { var i; for (i in this._deferQueue) { if (this._deferQueue.hasOwnProperty(i)) { if (this._deferQueue[i].length) { return true; } } } return false; }; /** * Inserts a document or array of documents into the collection. * @param {Object|Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Function=} callback Optional callback called once action is complete. * objects to insert into the collection. */ Collection.prototype.insert = function (data, index, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (typeof(index) === 'function') { callback = index; index = this._data.length; } else if (index === undefined) { index = this._data.length; } data = this.transformIn(data); return this._insertHandle(data, index, callback); }; /** * Inserts a document or array of documents into the collection. * @param {Object|Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Function=} callback Optional callback called once action is complete. * objects to insert into the collection. */ Collection.prototype._insertHandle = function (data, index, callback) { var //self = this, queue = this._deferQueue.insert, deferThreshold = this._deferThreshold.insert, //deferTime = this._deferTime.insert, inserted = [], failed = [], insertResult, resultObj, i; if (data instanceof Array) { // Check if there are more insert items than the insert defer // threshold, if so, break up inserts so we don't tie up the // ui or thread if (this._deferredCalls && data.length > deferThreshold) { // Break up insert into blocks this._deferQueue.insert = queue.concat(data); this._asyncPending('insert'); // Fire off the insert queue handler this.processQueue('insert', callback); return; } else { // Loop the array and add items for (i = 0; i < data.length; i++) { insertResult = this._insert(data[i], index + i); if (insertResult === true) { inserted.push(data[i]); } else { failed.push({ doc: data[i], reason: insertResult }); } } } } else { // Store the data item insertResult = this._insert(data, index); if (insertResult === true) { inserted.push(data); } else { failed.push({ doc: data, reason: insertResult }); } } resultObj = { deferred: false, inserted: inserted, failed: failed }; this._onInsert(inserted, failed); if (callback) { callback(resultObj); } this._onChange(); this.deferEmit('change', {type: 'insert', data: inserted}); return resultObj; }; /** * Internal method to insert a document into the collection. Will * check for index violations before allowing the document to be inserted. * @param {Object} doc The document to insert after passing index violation * tests. * @param {Number=} index Optional index to insert the document at. * @returns {Boolean|Object} True on success, false if no document passed, * or an object containing details about an index violation if one occurred. * @private */ Collection.prototype._insert = function (doc, index) { if (doc) { var self = this, indexViolation, triggerOperation, insertMethod, newDoc, capped = this.capped(), cappedSize = this.cappedSize(); this.ensurePrimaryKey(doc); // Check indexes are not going to be broken by the document indexViolation = this.insertIndexViolation(doc); insertMethod = function (doc) { // Add the item to the collection's indexes self._insertIntoIndexes(doc); // Check index overflow if (index > self._data.length) { index = self._data.length; } // Insert the document self._dataInsertAtIndex(index, doc); // Check capped collection status and remove first record // if we are over the threshold if (capped && self._data.length > cappedSize) { // Remove the first item in the data array self.removeById(self._data[0][self._primaryKey]); } //op.time('Resolve chains'); self.chainSend('insert', doc, {index: index}); //op.time('Resolve chains'); }; if (!indexViolation) { if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { triggerOperation = { type: 'insert' }; if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) { insertMethod(doc); if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { // Clone the doc so that the programmer cannot update the internal document // on the "after" phase trigger newDoc = self.decouple(doc); self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc); } } else { // The trigger just wants to cancel the operation return 'Trigger cancelled operation'; } } else { // No triggers to execute insertMethod(doc); } return true; } else { return 'Index violation in index: ' + indexViolation; } } return 'No document passed to insert'; }; /** * Inserts a document into the internal collection data array at * Inserts a document into the internal collection data array at * the specified index. * @param {number} index The index to insert at. * @param {object} doc The document to insert. * @private */ Collection.prototype._dataInsertAtIndex = function (index, doc) { this._data.splice(index, 0, doc); }; /** * Removes a document from the internal collection data array at * the specified index. * @param {number} index The index to remove from. * @private */ Collection.prototype._dataRemoveAtIndex = function (index) { this._data.splice(index, 1); }; /** * Replaces all data in the collection's internal data array with * the passed array of data. * @param {array} data The array of data to replace existing data with. * @private */ Collection.prototype._dataReplace = function (data) { // Clear the array - using a while loop with pop is by far the // fastest way to clear an array currently while (this._data.length) { this._data.pop(); } // Append new items to the array this._data = this._data.concat(data); }; /** * Inserts a document into the collection indexes. * @param {Object} doc The document to insert. * @private */ Collection.prototype._insertIntoIndexes = function (doc) { var arr = this._indexByName, arrIndex, violated, jString = this.jStringify(doc); // Insert to primary key index violated = this._primaryIndex.uniqueSet(doc[this._primaryKey], doc); this._primaryCrc.uniqueSet(doc[this._primaryKey], jString); this._crcLookup.uniqueSet(jString, doc); // Insert into other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].insert(doc); } } return violated; }; /** * Removes a document from the collection indexes. * @param {Object} doc The document to remove. * @private */ Collection.prototype._removeFromIndexes = function (doc) { var arr = this._indexByName, arrIndex, jString = this.jStringify(doc); // Remove from primary key index this._primaryIndex.unSet(doc[this._primaryKey]); this._primaryCrc.unSet(doc[this._primaryKey]); this._crcLookup.unSet(jString); // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].remove(doc); } } }; /** * Updates collection index data for the passed document. * @param {Object} oldDoc The old document as it was before the update. * @param {Object} newDoc The document as it now is after the update. * @private */ Collection.prototype._updateIndexes = function (oldDoc, newDoc) { this._removeFromIndexes(oldDoc); this._insertIntoIndexes(newDoc); }; /** * Rebuild collection indexes. * @private */ Collection.prototype._rebuildIndexes = function () { var arr = this._indexByName, arrIndex; // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].rebuild(); } } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param {Object} query The query object to generate the subset with. * @param {Object=} options An options object. * @returns {*} */ Collection.prototype.subset = function (query, options) { var result = this.find(query, options); return new Collection() .subsetOf(this) .primaryKey(this._primaryKey) .setData(result); }; /** * Gets / sets the collection that this collection is a subset of. * @param {Collection=} collection The collection to set as the parent of this subset. * @returns {Collection} */ Shared.synthesize(Collection.prototype, 'subsetOf'); /** * Checks if the collection is a subset of the passed collection. * @param {Collection} collection The collection to test against. * @returns {Boolean} True if the passed collection is the parent of * the current collection. */ Collection.prototype.isSubsetOf = function (collection) { return this._subsetOf === collection; }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ Collection.prototype.distinct = function (key, query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var data = this.find(query, options), pathSolver = new Path(key), valueUsed = {}, distinctValues = [], value, i; // Loop the data and build array of distinct values for (i = 0; i < data.length; i++) { value = pathSolver.value(data[i])[0]; if (value && !valueUsed[value]) { valueUsed[value] = true; distinctValues.push(value); } } return distinctValues; }; /** * Helper method to find a document by it's id. * @param {String} id The id of the document. * @param {Object=} options The options object, allowed keys are sort and limit. * @returns {Array} The items that were updated. */ Collection.prototype.findById = function (id, options) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.find(searchObj, options)[0]; }; /** * Finds all documents that contain the passed string or search object * regardless of where the string might occur within the document. This * will match strings from the start, middle or end of the document's * string (partial match). * @param search The string to search for. Case sensitive. * @param options A standard find() options object. * @returns {Array} An array of documents that matched the search string. */ Collection.prototype.peek = function (search, options) { // Loop all items var arr = this._data, arrCount = arr.length, arrIndex, arrItem, tempColl = new Collection(), typeOfSearch = typeof search; if (typeOfSearch === 'string') { for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Get json representation of object arrItem = this.jStringify(arr[arrIndex]); // Check if string exists in object json if (arrItem.indexOf(search) > -1) { // Add this item to the temp collection tempColl.insert(arr[arrIndex]); } } return tempColl.find({}, options); } else { return this.find(search, options); } }; /** * Provides a query plan / operations log for a query. * @param {Object} query The query to execute. * @param {Object=} options Optional options object. * @returns {Object} The query plan. */ Collection.prototype.explain = function (query, options) { var result = this.find(query, options); return result.__fdbOp._data; }; /** * Generates an options object with default values or adds default * values to a passed object if those values are not currently set * to anything. * @param {object=} obj Optional options object to modify. * @returns {object} The options object. */ Collection.prototype.options = function (obj) { obj = obj || {}; obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true; obj.$explain = obj.$explain !== undefined ? obj.$explain : false; return obj; }; /** * Queries the collection based on the query object passed. * @param {Object} query The query key/values that a document must match in * order for it to be returned in the result array. * @param {Object=} options An optional options object. * @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !! * Optional callback. If specified the find process * will not return a value and will assume that you wish to operate under an * async mode. This will break up large find requests into smaller chunks and * process them in a non-blocking fashion allowing large datasets to be queried * without causing the browser UI to pause. Results from this type of operation * will be passed back to the callback once completed. * * @returns {Array} The results array from the find operation, containing all * documents that matched the query. */ Collection.prototype.find = function (query, options, callback) { // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (callback) { // Check the size of the collection's data array // Split operation into smaller tasks and callback when complete callback('Callbacks for the find() operation are not yet implemented!', []); return []; } return this._find.apply(this, arguments); }; Collection.prototype._find = function (query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // TODO: This method is quite long, break into smaller pieces query = query || {}; options = this.options(options); var op = this._metrics.create('find'), pk = this.primaryKey(), self = this, analysis, scanLength, requiresTableScan = true, resultArr, joinCollectionIndex, joinIndex, joinCollection = {}, joinQuery, joinPath, joinCollectionName, joinCollectionInstance, joinMatch, joinMatchIndex, joinSearchQuery, joinSearchOptions, joinMulti, joinRequire, joinFindResults, joinFindResult, joinItem, joinPrefix, resultCollectionName, resultIndex, resultRemove = [], index, i, j, k, l, fieldListOn = [], fieldListOff = [], elemMatchPathSolver, elemMatchSubArr, elemMatchSpliceArr, matcherTmpOptions = {}, result, cursor = {}, pathSolver, //renameFieldMethod, //renameFieldPath, matcher = function (doc) { return self._match(doc, query, options, 'and', matcherTmpOptions); }; op.start(); if (query) { // Get query analysis to execute best optimised code path op.time('analyseQuery'); analysis = this._analyseQuery(self.decouple(query), options, op); op.time('analyseQuery'); op.data('analysis', analysis); if (analysis.hasJoin && analysis.queriesJoin) { // The query has a join and tries to limit by it's joined data // Get an instance reference to the join collections op.time('joinReferences'); for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) { joinCollectionName = analysis.joinsOn[joinIndex]; joinPath = new Path(analysis.joinQueries[joinCollectionName]); joinQuery = joinPath.value(query)[0]; joinCollection[analysis.joinsOn[joinIndex]] = this._db.collection(analysis.joinsOn[joinIndex]).subset(joinQuery); // Remove join clause from main query delete query[analysis.joinQueries[joinCollectionName]]; } op.time('joinReferences'); } // Check if an index lookup can be used to return this result if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) { op.data('index.potential', analysis.indexMatch); op.data('index.used', analysis.indexMatch[0].index); // Get the data from the index op.time('indexLookup'); resultArr = analysis.indexMatch[0].lookup || []; op.time('indexLookup'); // Check if the index coverage is all keys, if not we still need to table scan it if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) { // Don't require a table scan to find relevant documents requiresTableScan = false; } } else { op.flag('usedIndex', false); } if (requiresTableScan) { if (resultArr && resultArr.length) { scanLength = resultArr.length; op.time('tableScan: ' + scanLength); // Filter the source data and return the result resultArr = resultArr.filter(matcher); } else { // Filter the source data and return the result scanLength = this._data.length; op.time('tableScan: ' + scanLength); resultArr = this._data.filter(matcher); } op.time('tableScan: ' + scanLength); } // Order the array if we were passed a sort clause if (options.$orderBy) { op.time('sort'); resultArr = this.sort(options.$orderBy, resultArr); op.time('sort'); } if (options.$page !== undefined && options.$limit !== undefined) { // Record paging data cursor.page = options.$page; cursor.pages = Math.ceil(resultArr.length / options.$limit); cursor.records = resultArr.length; // Check if we actually need to apply the paging logic if (options.$page && options.$limit > 0) { op.data('cursor', cursor); // Skip to the page specified based on limit resultArr.splice(0, options.$page * options.$limit); } } if (options.$skip) { cursor.skip = options.$skip; // Skip past the number of records specified resultArr.splice(0, options.$skip); op.data('skip', options.$skip); } if (options.$limit && resultArr && resultArr.length > options.$limit) { cursor.limit = options.$limit; resultArr.length = options.$limit; op.data('limit', options.$limit); } if (options.$decouple) { // Now decouple the data from the original objects op.time('decouple'); resultArr = this.decouple(resultArr); op.time('decouple'); op.data('flag.decouple', true); } // Now process any joins on the final data if (options.$join) { for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) { for (joinCollectionName in options.$join[joinCollectionIndex]) { if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) { // Set the key to store the join result in to the collection name by default resultCollectionName = joinCollectionName; // Get the join collection instance from the DB if (joinCollection[joinCollectionName]) { joinCollectionInstance = joinCollection[joinCollectionName]; } else { joinCollectionInstance = this._db.collection(joinCollectionName); } // Get the match data for the join joinMatch = options.$join[joinCollectionIndex][joinCollectionName]; // Loop our result data array for (resultIndex = 0; resultIndex < resultArr.length; resultIndex++) { // Loop the join conditions and build a search object from them joinSearchQuery = {}; joinMulti = false; joinRequire = false; joinPrefix = ''; for (joinMatchIndex in joinMatch) { if (joinMatch.hasOwnProperty(joinMatchIndex)) { // Check the join condition name for a special command operator if (joinMatchIndex.substr(0, 1) === '$') { // Special command switch (joinMatchIndex) { case '$where': if (joinMatch[joinMatchIndex].query) { // Commented old code here, new one does dynamic reverse lookups //joinSearchQuery = joinMatch[joinMatchIndex].query; joinSearchQuery = self._resolveDynamicQuery(joinMatch[joinMatchIndex].query, resultArr[resultIndex]); } if (joinMatch[joinMatchIndex].options) { joinSearchOptions = joinMatch[joinMatchIndex].options; } break; case '$as': // Rename the collection when stored in the result document resultCollectionName = joinMatch[joinMatchIndex]; break; case '$multi': // Return an array of documents instead of a single matching document joinMulti = joinMatch[joinMatchIndex]; break; case '$require': // Remove the result item if no matching join data is found joinRequire = joinMatch[joinMatchIndex]; break; case '$prefix': // Add a prefix to properties mixed in joinPrefix = joinMatch[joinMatchIndex]; break; default: break; } } else { // Get the data to match against and store in the search object // Resolve complex referenced query joinSearchQuery[joinMatchIndex] = self._resolveDynamicQuery(joinMatch[joinMatchIndex], resultArr[resultIndex]); } } } // Do a find on the target collection against the match data joinFindResults = joinCollectionInstance.find(joinSearchQuery, joinSearchOptions); // Check if we require a joined row to allow the result item if (!joinRequire || (joinRequire && joinFindResults[0])) { // Join is not required or condition is met if (resultCollectionName === '$root') { // The property name to store the join results in is $root // which means we need to mixin the results but this only // works if joinMulti is disabled if (joinMulti !== false) { // Throw an exception here as this join is not physically possible! throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!'); } // Mixin the result joinFindResult = joinFindResults[0]; joinItem = resultArr[resultIndex]; for (l in joinFindResult) { if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) { // Properties are only mixed in if they do not already exist // in the target item (are undefined). Using a prefix denoted via // $prefix is a good way to prevent property name conflicts joinItem[joinPrefix + l] = joinFindResult[l]; } } } else { resultArr[resultIndex][resultCollectionName] = joinMulti === false ? joinFindResults[0] : joinFindResults; } } else { // Join required but condition not met, add item to removal queue resultRemove.push(resultArr[resultIndex]); } } } } } op.data('flag.join', true); } // Process removal queue if (resultRemove.length) { op.time('removalQueue'); for (i = 0; i < resultRemove.length; i++) { index = resultArr.indexOf(resultRemove[i]); if (index > -1) { resultArr.splice(index, 1); } } op.time('removalQueue'); } if (options.$transform) { op.time('transform'); for (i = 0; i < resultArr.length; i++) { resultArr.splice(i, 1, options.$transform(resultArr[i])); } op.time('transform'); op.data('flag.transform', true); } // Process transforms if (this._transformEnabled && this._transformOut) { op.time('transformOut'); resultArr = this.transformOut(resultArr); op.time('transformOut'); } op.data('results', resultArr.length); } else { resultArr = []; } // Check for an $as operator in the options object and if it exists // iterate over the fields and generate a rename function that will // operate over the entire returned data array and rename each object's // fields to their new names // TODO: Enable $as in collection find to allow renaming fields /*if (options.$as) { renameFieldPath = new Path(); renameFieldMethod = function (obj, oldFieldPath, newFieldName) { renameFieldPath.path(oldFieldPath); renameFieldPath.rename(newFieldName); }; for (i in options.$as) { if (options.$as.hasOwnProperty(i)) { } } }*/ if (!options.$aggregate) { // Generate a list of fields to limit data by // Each property starts off being enabled by default (= 1) then // if any property is explicitly specified as 1 then all switch to // zero except _id. // // Any that are explicitly set to zero are switched off. op.time('scanFields'); for (i in options) { if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) { if (options[i] === 1) { fieldListOn.push(i); } else if (options[i] === 0) { fieldListOff.push(i); } } } op.time('scanFields'); // Limit returned fields by the options data if (fieldListOn.length || fieldListOff.length) { op.data('flag.limitFields', true); op.data('limitFields.on', fieldListOn); op.data('limitFields.off', fieldListOff); op.time('limitFields'); // We have explicit fields switched on or off for (i = 0; i < resultArr.length; i++) { result = resultArr[i]; for (j in result) { if (result.hasOwnProperty(j)) { if (fieldListOn.length) { // We have explicit fields switched on so remove all fields // that are not explicitly switched on // Check if the field name is not the primary key if (j !== pk) { if (fieldListOn.indexOf(j) === -1) { // This field is not in the on list, remove it delete result[j]; } } } if (fieldListOff.length) { // We have explicit fields switched off so remove fields // that are explicitly switched off if (fieldListOff.indexOf(j) > -1) { // This field is in the off list, remove it delete result[j]; } } } } } op.time('limitFields'); } // Now run any projections on the data required if (options.$elemMatch) { op.data('flag.elemMatch', true); op.time('projection-elemMatch'); for (i in options.$elemMatch) { if (options.$elemMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) { // The item matches the projection query so set the sub-array // to an array that ONLY contains the matching item and then // exit the loop since we only want to match the first item elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]); break; } } } } } } op.time('projection-elemMatch'); } if (options.$elemsMatch) { op.data('flag.elemsMatch', true); op.time('projection-elemsMatch'); for (i in options.$elemsMatch) { if (options.$elemsMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { elemMatchSpliceArr = []; // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) { // The item matches the projection query so add it to the final array elemMatchSpliceArr.push(elemMatchSubArr[k]); } } // Now set the final sub-array to the matched items elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr); } } } } op.time('projection-elemsMatch'); } } // Process aggregation if (options.$aggregate) { op.data('flag.aggregate', true); op.time('aggregate'); pathSolver = new Path(options.$aggregate); resultArr = pathSolver.value(resultArr); op.time('aggregate'); } op.stop(); resultArr.__fdbOp = op; resultArr.$cursor = cursor; return resultArr; }; Collection.prototype._resolveDynamicQuery = function (query, item) { var self = this, newQuery, propType, propVal, pathResult, i; if (typeof query === 'string') { // Check if the property name starts with a back-reference if (query.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value pathResult = new Path(query.substr(3, query.length - 3)).value(item); } else { pathResult = new Path(query).value(item); } if (pathResult.length > 1) { return {$in: pathResult}; } else { return pathResult[0]; } } newQuery = {}; for (i in query) { if (query.hasOwnProperty(i)) { propType = typeof query[i]; propVal = query[i]; switch (propType) { case 'string': // Check if the property name starts with a back-reference if (propVal.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value newQuery[i] = new Path(propVal.substr(3, propVal.length - 3)).value(item)[0]; } else { newQuery[i] = propVal; } break; case 'object': newQuery[i] = self._resolveDynamicQuery(propVal, item); break; default: newQuery[i] = propVal; break; } } } return newQuery; }; /** * Returns one document that satisfies the specified query criteria. If multiple * documents satisfy the query, this method returns the first document to match * the query. * @returns {*} */ Collection.prototype.findOne = function () { return (this.find.apply(this, arguments))[0]; }; /** * Gets the index in the collection data array of the first item matched by * the passed query object. * @param {Object} query The query to run to find the item to return the index of. * @param {Object=} options An options object. * @returns {Number} */ Collection.prototype.indexOf = function (query, options) { var item = this.find(query, {$decouple: false})[0], sortedData; if (item) { if (!options || options && !options.$orderBy) { // Basic lookup from order of insert return this._data.indexOf(item); } else { // Trying to locate index based on query with sort order options.$decouple = false; sortedData = this.find(query, options); return sortedData.indexOf(item); } } return -1; }; /** * Returns the index of the document identified by the passed item's primary key. * @param {*} itemLookup The document whose primary key should be used to lookup * or the id to lookup. * @param {Object=} options An options object. * @returns {Number} The index the item with the matching primary key is occupying. */ Collection.prototype.indexOfDocById = function (itemLookup, options) { var item, sortedData; if (typeof itemLookup !== 'object') { item = this._primaryIndex.get(itemLookup); } else { item = this._primaryIndex.get(itemLookup[this._primaryKey]); } if (item) { if (!options || options && !options.$orderBy) { // Basic lookup return this._data.indexOf(item); } else { // Sorted lookup options.$decouple = false; sortedData = this.find({}, options); return sortedData.indexOf(item); } } return -1; }; /** * Removes a document from the collection by it's index in the collection's * data array. * @param {Number} index The index of the document to remove. * @returns {Object} The document that has been removed or false if none was * removed. */ Collection.prototype.removeByIndex = function (index) { var doc, docId; doc = this._data[index]; if (doc !== undefined) { doc = this.decouple(doc); docId = doc[this.primaryKey()]; return this.removeById(docId); } return false; }; /** * Gets / sets the collection transform options. * @param {Object} obj A collection transform options object. * @returns {*} */ Collection.prototype.transform = function (obj) { if (obj !== undefined) { if (typeof obj === "object") { if (obj.enabled !== undefined) { this._transformEnabled = obj.enabled; } if (obj.dataIn !== undefined) { this._transformIn = obj.dataIn; } if (obj.dataOut !== undefined) { this._transformOut = obj.dataOut; } } else { this._transformEnabled = obj !== false; } return this; } return { enabled: this._transformEnabled, dataIn: this._transformIn, dataOut: this._transformOut }; }; /** * Transforms data using the set transformIn method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformIn = function (data) { if (this._transformEnabled && this._transformIn) { if (data instanceof Array) { var finalArr = [], i; for (i = 0; i < data.length; i++) { finalArr[i] = this._transformIn(data[i]); } return finalArr; } else { return this._transformIn(data); } } return data; }; /** * Transforms data using the set transformOut method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformOut = function (data) { if (this._transformEnabled && this._transformOut) { if (data instanceof Array) { var finalArr = [], i; for (i = 0; i < data.length; i++) { finalArr[i] = this._transformOut(data[i]); } return finalArr; } else { return this._transformOut(data); } } return data; }; /** * Sorts an array of documents by the given sort path. * @param {*} sortObj The keys and orders the array objects should be sorted by. * @param {Array} arr The array of documents to sort. * @returns {Array} */ Collection.prototype.sort = function (sortObj, arr) { // Make sure we have an array object arr = arr || []; var sortArr = [], sortKey, sortSingleObj; for (sortKey in sortObj) { if (sortObj.hasOwnProperty(sortKey)) { sortSingleObj = {}; sortSingleObj[sortKey] = sortObj[sortKey]; sortSingleObj.___fdbKey = String(sortKey); sortArr.push(sortSingleObj); } } if (sortArr.length < 2) { // There is only one sort criteria, do a simple sort and return it return this._sort(sortObj, arr); } else { return this._bucketSort(sortArr, arr); } }; /** * Takes array of sort paths and sorts them into buckets before returning final * array fully sorted by multi-keys. * @param keyArr * @param arr * @returns {*} * @private */ Collection.prototype._bucketSort = function (keyArr, arr) { var keyObj = keyArr.shift(), arrCopy, bucketData, bucketOrder, bucketKey, buckets, i, finalArr = []; if (keyArr.length > 0) { // Sort array by bucket key arr = this._sort(keyObj, arr); // Split items into buckets bucketData = this.bucket(keyObj.___fdbKey, arr); bucketOrder = bucketData.order; buckets = bucketData.buckets; // Loop buckets and sort contents for (i = 0; i < bucketOrder.length; i++) { bucketKey = bucketOrder[i]; arrCopy = [].concat(keyArr); finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey])); } return finalArr; } else { return this._sort(keyObj, arr); } }; /** * Sorts array by individual sort path. * @param key * @param arr * @returns {Array|*} * @private */ Collection.prototype._sort = function (key, arr) { var self = this, sorterMethod, pathSolver = new Path(), dataPath = pathSolver.parse(key, true)[0]; pathSolver.path(dataPath.path); if (dataPath.value === 1) { // Sort ascending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortAsc(valA, valB); }; } else if (dataPath.value === -1) { // Sort descending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortDesc(valA, valB); }; } else { throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!'); } return arr.sort(sorterMethod); }; /** * Takes an array of objects and returns a new object with the array items * split into buckets by the passed key. * @param {String} key The key to split the array into buckets by. * @param {Array} arr An array of objects. * @returns {Object} */ Collection.prototype.bucket = function (key, arr) { var i, oldField, field, fieldArr = [], buckets = {}; for (i = 0; i < arr.length; i++) { field = String(arr[i][key]); if (oldField !== field) { fieldArr.push(field); oldField = field; } buckets[field] = buckets[field] || []; buckets[field].push(arr[i]); } return { buckets: buckets, order: fieldArr }; }; /** * Internal method that takes a search query and options and returns an object * containing details about the query which can be used to optimise the search. * * @param query * @param options * @param op * @returns {Object} * @private */ Collection.prototype._analyseQuery = function (query, options, op) { var analysis = { queriesOn: [this._name], indexMatch: [], hasJoin: false, queriesJoin: false, joinQueries: {}, query: query, options: options }, joinCollectionIndex, joinCollectionName, joinCollections = [], joinCollectionReferences = [], queryPath, index, indexMatchData, indexRef, indexRefName, indexLookup, pathSolver, queryKeyCount, i; // Check if the query is a primary key lookup op.time('checkIndexes'); pathSolver = new Path(); queryKeyCount = pathSolver.countKeys(query); if (queryKeyCount) { if (query[this._primaryKey] !== undefined) { // Return item via primary key possible op.time('checkIndexMatch: Primary Key'); analysis.indexMatch.push({ lookup: this._primaryIndex.lookup(query, options), keyData: { matchedKeys: [this._primaryKey], totalKeyCount: queryKeyCount, score: 1 }, index: this._primaryIndex }); op.time('checkIndexMatch: Primary Key'); } // Check if an index can speed up the query for (i in this._indexById) { if (this._indexById.hasOwnProperty(i)) { indexRef = this._indexById[i]; indexRefName = indexRef.name(); op.time('checkIndexMatch: ' + indexRefName); indexMatchData = indexRef.match(query, options); if (indexMatchData.score > 0) { // This index can be used, store it indexLookup = indexRef.lookup(query, options); analysis.indexMatch.push({ lookup: indexLookup, keyData: indexMatchData, index: indexRef }); } op.time('checkIndexMatch: ' + indexRefName); if (indexMatchData.score === queryKeyCount) { // Found an optimal index, do not check for any more break; } } } op.time('checkIndexes'); // Sort array descending on index key count (effectively a measure of relevance to the query) if (analysis.indexMatch.length > 1) { op.time('findOptimalIndex'); analysis.indexMatch.sort(function (a, b) { if (a.keyData.score > b.keyData.score) { // This index has a higher score than the other return -1; } if (a.keyData.score < b.keyData.score) { // This index has a lower score than the other return 1; } // The indexes have the same score but can still be compared by the number of records // they return from the query. The fewer records they return the better so order by // record count if (a.keyData.score === b.keyData.score) { return a.lookup.length - b.lookup.length; } }); op.time('findOptimalIndex'); } } // Check for join data if (options.$join) { analysis.hasJoin = true; // Loop all join operations for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) { // Loop the join collections and keep a reference to them for (joinCollectionName in options.$join[joinCollectionIndex]) { if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) { joinCollections.push(joinCollectionName); // Check if the join uses an $as operator if ('$as' in options.$join[joinCollectionIndex][joinCollectionName]) { joinCollectionReferences.push(options.$join[joinCollectionIndex][joinCollectionName].$as); } else { joinCollectionReferences.push(joinCollectionName); } } } } // Loop the join collection references and determine if the query references // any of the collections that are used in the join. If there no queries against // joined collections the find method can use a code path optimised for this. // Queries against joined collections requires the joined collections to be filtered // first and then joined so requires a little more work. for (index = 0; index < joinCollectionReferences.length; index++) { // Check if the query references any collection data that the join will create queryPath = this._queryReferencesCollection(query, joinCollectionReferences[index], ''); if (queryPath) { analysis.joinQueries[joinCollections[index]] = queryPath; analysis.queriesJoin = true; } } analysis.joinsOn = joinCollections; analysis.queriesOn = analysis.queriesOn.concat(joinCollections); } return analysis; }; /** * Checks if the passed query references this collection. * @param query * @param collection * @param path * @returns {*} * @private */ Collection.prototype._queryReferencesCollection = function (query, collection, path) { var i; for (i in query) { if (query.hasOwnProperty(i)) { // Check if this key is a reference match if (i === collection) { if (path) { path += '.'; } return path + i; } else { if (typeof(query[i]) === 'object') { // Recurse if (path) { path += '.'; } path += i; return this._queryReferencesCollection(query[i], collection, path); } } } } return false; }; /** * Returns the number of documents currently in the collection. * @returns {Number} */ Collection.prototype.count = function (query, options) { if (!query) { return this._data.length; } else { // Run query and return count return this.find(query, options).length; } }; /** * Finds sub-documents from the collection's documents. * @param {Object} match The query object to use when matching parent documents * from which the sub-documents are queried. * @param {String} path The path string used to identify the key in which * sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching which sub-documents * to return. * @param {Object=} subDocOptions The options object to use when querying for * sub-documents. * @returns {*} */ Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) { var pathHandler = new Path(path), docArr = this.find(match), docCount = docArr.length, docIndex, subDocArr, subDocCollection = this._db.collection('__FDB_temp_' + this.objectId()), subDocResults, resultObj = { parents: docCount, subDocTotal: 0, subDocs: [], pathFound: false, err: '' }; subDocOptions = subDocOptions || {}; for (docIndex = 0; docIndex < docCount; docIndex++) { subDocArr = pathHandler.value(docArr[docIndex])[0]; if (subDocArr) { subDocCollection.setData(subDocArr); subDocResults = subDocCollection.find(subDocQuery, subDocOptions); if (subDocOptions.returnFirst && subDocResults.length) { return subDocResults[0]; } if (subDocOptions.$split) { resultObj.subDocs.push(subDocResults); } else { resultObj.subDocs = resultObj.subDocs.concat(subDocResults); } resultObj.subDocTotal += subDocResults.length; resultObj.pathFound = true; } } // Drop the sub-document collection subDocCollection.drop(); // Check if the call should not return stats, if so return only subDocs array if (subDocOptions.$stats) { return resultObj; } else { return resultObj.subDocs; } if (!resultObj.pathFound) { resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path; } return resultObj; }; /** * Finds the first sub-document from the collection's documents that matches * the subDocQuery parameter. * @param {Object} match The query object to use when matching parent documents * from which the sub-documents are queried. * @param {String} path The path string used to identify the key in which * sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching which sub-documents * to return. * @param {Object=} subDocOptions The options object to use when querying for * sub-documents. * @returns {Object} */ Collection.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) { return this.findSub(match, path, subDocQuery, subDocOptions)[0]; }; /** * Checks that the passed document will not violate any index rules if * inserted into the collection. * @param {Object} doc The document to check indexes against. * @returns {Boolean} Either false (no violation occurred) or true if * a violation was detected. */ Collection.prototype.insertIndexViolation = function (doc) { var indexViolated, arr = this._indexByName, arrIndex, arrItem; // Check the item's primary key is not already in use if (this._primaryIndex.get(doc[this._primaryKey])) { indexViolated = this._primaryIndex; } else { // Check violations of other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arrItem = arr[arrIndex]; if (arrItem.unique()) { if (arrItem.violation(doc)) { indexViolated = arrItem; break; } } } } } return indexViolated ? indexViolated.name() : false; }; /** * Creates an index on the specified keys. * @param {Object} keys The object containing keys to index. * @param {Object} options An options object. * @returns {*} */ Collection.prototype.ensureIndex = function (keys, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } this._indexByName = this._indexByName || {}; this._indexById = this._indexById || {}; var index, time = { start: new Date().getTime() }; if (options) { switch (options.type) { case 'hashed': index = new IndexHashMap(keys, options, this); break; case 'btree': index = new IndexBinaryTree(keys, options, this); break; default: // Default index = new IndexHashMap(keys, options, this); break; } } else { // Default index = new IndexHashMap(keys, options, this); } // Check the index does not already exist if (this._indexByName[index.name()]) { // Index already exists return { err: 'Index with that name already exists' }; } if (this._indexById[index.id()]) { // Index already exists return { err: 'Index with those keys already exists' }; } // Create the index index.rebuild(); // Add the index this._indexByName[index.name()] = index; this._indexById[index.id()] = index; time.end = new Date().getTime(); time.total = time.end - time.start; this._lastOp = { type: 'ensureIndex', stats: { time: time } }; return { index: index, id: index.id(), name: index.name(), state: index.state() }; }; /** * Gets an index by it's name. * @param {String} name The name of the index to retreive. * @returns {*} */ Collection.prototype.index = function (name) { if (this._indexByName) { return this._indexByName[name]; } }; /** * Gets the last reporting operation's details such as run time. * @returns {Object} */ Collection.prototype.lastOp = function () { return this._metrics.list(); }; /** * Generates a difference object that contains insert, update and remove arrays * representing the operations to execute to make this collection have the same * data as the one passed. * @param {Collection} collection The collection to diff against. * @returns {{}} */ Collection.prototype.diff = function (collection) { var diff = { insert: [], update: [], remove: [] }; var pm = this.primaryKey(), arr, arrIndex, arrItem, arrCount; // Check if the primary key index of each collection can be utilised if (pm !== collection.primaryKey()) { throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!'); } // Use the collection primary key index to do the diff (super-fast) arr = collection._data; // Check if we have an array or another collection while (arr && !(arr instanceof Array)) { // We don't have an array, assign collection and get data collection = arr; arr = collection._data; } arrCount = arr.length; // Loop the collection's data array and check for matching items for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; // Check for a matching item in this collection if (this._primaryIndex.get(arrItem[pm])) { // Matching item exists, check if the data is the same if (this._primaryCrc.get(arrItem[pm]) !== collection._primaryCrc.get(arrItem[pm])) { // The documents exist in both collections but data differs, update required diff.update.push(arrItem); } } else { // The document is missing from this collection, insert required diff.insert.push(arrItem); } } // Now loop this collection's data and check for matching items arr = this._data; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; if (!collection._primaryIndex.get(arrItem[pm])) { // The document does not exist in the other collection, remove required diff.remove.push(arrItem); } } return diff; }; Collection.prototype.collateAdd = new Overload({ /** * Adds a data source to collate data from and specifies the * key name to collate data to. * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {String=} keyName Optional name of the key to collate data to. * If none is provided the record CRUD is operated on the root collection * data. */ 'object, string': function (collection, keyName) { var self = this; self.collateAdd(collection, function (packet) { var obj1, obj2; switch (packet.type) { case 'insert': if (keyName) { obj1 = { $push: {} }; obj1.$push[keyName] = self.decouple(packet.data); self.update({}, obj1); } else { self.insert(packet.data); } break; case 'update': if (keyName) { obj1 = {}; obj2 = {}; obj1[keyName] = packet.data.query; obj2[keyName + '.$'] = packet.data.update; self.update(obj1, obj2); } else { self.update(packet.data.query, packet.data.update); } break; case 'remove': if (keyName) { obj1 = { $pull: {} }; obj1.$pull[keyName] = {}; obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()]; self.update({}, obj1); } else { self.remove(packet.data); } break; default: } }); }, /** * Adds a data source to collate data from and specifies a process * method that will handle the collation functionality (for custom * collation). * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {Function} process The process method. */ 'object, function': function (collection, process) { if (typeof collection === 'string') { // The collection passed is a name, not a reference so get // the reference from the name collection = this._db.collection(collection, { autoCreate: false, throwError: false }); } if (collection) { this._collate = this._collate || {}; this._collate[collection.name()] = new ReactorIO(collection, this, process); return this; } else { throw('Cannot collate from a non-existent collection!'); } } }); Collection.prototype.collateRemove = function (collection) { if (typeof collection === 'object') { // We need to have the name of the collection to remove it collection = collection.name(); } if (collection) { // Drop the reactor IO chain node this._collate[collection].drop(); // Remove the collection data from the collate object delete this._collate[collection]; return this; } else { throw('No collection name passed to collateRemove() or collection not found!'); } }; Db.prototype.collection = new Overload({ /** * Get a collection with no name (generates a random name). If the * collection does not already exist then one is created for that * name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @returns {Collection} */ '': function () { return this.$main.call(this, { name: this.objectId() }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {Object} data An options object or a collection instance. * @returns {Collection} */ 'object': function (data) { // Handle being passed an instance if (data instanceof Collection) { if (data.state() !== 'droppped') { return data; } else { return this.$main.call(this, { name: data.name() }); } } return this.$main.call(this, data); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @returns {Collection} */ 'string': function (collectionName) { return this.$main.call(this, { name: collectionName }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the primary key field on the collection * objects. Defaults to "_id". * @returns {Collection} */ 'string, string': function (collectionName, primaryKey) { return this.$main.call(this, { name: collectionName, primaryKey: primaryKey }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {Object} options An options object. * @returns {Collection} */ 'string, object': function (collectionName, options) { options.name = collectionName; return this.$main.call(this, options); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the primary key field on the collection * objects. Defaults to "_id". * @param {Object} options An options object. * @returns {Collection} */ 'string, string, object': function (collectionName, primaryKey, options) { options.name = collectionName; options.primaryKey = primaryKey; return this.$main.call(this, options); }, /** * The main handler method. This gets called by all the other variants and * handles the actual logic of the overloaded method. * @func collection * @memberof Db * @param {Object} options An options object. * @returns {*} */ '$main': function (options) { var self = this, name = options.name; if (name) { if (this._collection[name]) { return this._collection[name]; } else { if (options && options.autoCreate === false) { if (options && options.throwError !== false) { throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!'); } return undefined; } if (this.debug()) { console.log(this.logIdentifier() + ' Creating collection ' + name); } } this._collection[name] = this._collection[name] || new Collection(name, options).db(this); this._collection[name].mongoEmulation(this.mongoEmulation()); if (options.primaryKey !== undefined) { this._collection[name].primaryKey(options.primaryKey); } if (options.capped !== undefined) { // Check we have a size if (options.size !== undefined) { this._collection[name].capped(options.capped); this._collection[name].cappedSize(options.size); } else { throw(this.logIdentifier() + ' Cannot create a capped collection without specifying a size!'); } } // Listen for events on this collection so we can fire global events // on the database in response to it self._collection[name].on('change', function () { self.emit('change', self._collection[name], 'collection', name); }); self.emit('create', self._collection[name], 'collection', name); return this._collection[name]; } else { if (!options || (options && options.throwError !== false)) { throw(this.logIdentifier() + ' Cannot get collection with undefined name!'); } } } }); /** * Determine if a collection with the passed name already exists. * @memberof Db * @param {String} viewName The name of the collection to check for. * @returns {boolean} */ Db.prototype.collectionExists = function (viewName) { return Boolean(this._collection[viewName]); }; /** * Returns an array of collections the DB currently has. * @memberof Db * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each collection * the database is currently managing. */ Db.prototype.collections = function (search) { var arr = [], collections = this._collection, collection, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in collections) { if (collections.hasOwnProperty(i)) { collection = collections[i]; if (search) { if (search.exec(i)) { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } else { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Collection'); module.exports = Collection; },{"./Crc":5,"./IndexBinaryTree":7,"./IndexHashMap":8,"./KeyValueStore":9,"./Metrics":10,"./Overload":22,"./Path":23,"./ReactorIO":24,"./Shared":26}],4:[function(_dereq_,module,exports){ /* License Copyright (c) 2015 Irrelon Software Limited http://www.irrelon.com http://www.forerunnerdb.com Please visit the license page to see latest license information: http://www.forerunnerdb.com/licensing.html */ "use strict"; var Shared, Db, Metrics, Overload, _instances = []; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB instance. Core instances handle the lifecycle of * multiple database instances. * @constructor */ var Core = function (name) { this.init.apply(this, arguments); }; Core.prototype.init = function (name) { this._db = {}; this._debug = {}; this._name = name || 'ForerunnerDB'; _instances.push(this); }; /** * Returns the number of instantiated ForerunnerDB objects. * @returns {Number} The number of instantiated instances. */ Core.prototype.instantiatedCount = function () { return _instances.length; }; /** * Get all instances as an array or a single ForerunnerDB instance * by it's array index. * @param {Number=} index Optional index of instance to get. * @returns {Array|Object} Array of instances or a single instance. */ Core.prototype.instances = function (index) { if (index !== undefined) { return _instances[index]; } return _instances; }; /** * Get all instances as an array of instance names or a single ForerunnerDB * instance by it's name. * @param {String=} name Optional name of instance to get. * @returns {Array|Object} Array of instance names or a single instance. */ Core.prototype.namedInstances = function (name) { var i, instArr; if (name !== undefined) { for (i = 0; i < _instances.length; i++) { if (_instances[i].name === name) { return _instances[i]; } } return undefined; } instArr = []; for (i = 0; i < _instances.length; i++) { instArr.push(_instances[i].name); } return instArr; }; Core.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } if (callback) { callback(); } } }, /** * Checks if an array of named modules are loaded and if so * calls the passed callback method. * @func moduleLoaded * @memberof Core * @param {Array} moduleName The array of module names to check for. * @param {Function} callback The callback method to call if modules are loaded. */ 'array, function': function (moduleNameArr, callback) { var moduleName, i; for (i = 0; i < moduleNameArr.length; i++) { moduleName = moduleNameArr[i]; if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } } } if (callback) { callback(); } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Core.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded() method to non-instantiated object ForerunnerDB Core.moduleLoaded = Core.prototype.moduleLoaded; // Expose version() method to non-instantiated object ForerunnerDB Core.version = Core.prototype.version; // Expose instances() method to non-instantiated object ForerunnerDB Core.instances = Core.prototype.instances; // Expose instantiatedCount() method to non-instantiated object ForerunnerDB Core.instantiatedCount = Core.prototype.instantiatedCount; // Provide public access to the Shared object Core.shared = Shared; Core.prototype.shared = Shared; Shared.addModule('Core', Core); Shared.mixin(Core.prototype, 'Mixin.Common'); Shared.mixin(Core.prototype, 'Mixin.Constants'); Db = _dereq_('./Db.js'); Metrics = _dereq_('./Metrics.js'); /** * Gets / sets the name of the instance. This is primarily used for * name-spacing persistent storage. * @param {String=} val The name of the instance to set. * @returns {*} */ Shared.synthesize(Core.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Core.prototype, 'mongoEmulation'); // Set a flag to determine environment Core.prototype._isServer = false; /** * Returns true if ForerunnerDB is running on a client browser. * @returns {boolean} */ Core.prototype.isClient = function () { return !this._isServer; }; /** * Returns true if ForerunnerDB is running on a server. * @returns {boolean} */ Core.prototype.isServer = function () { return this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Core.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Core.prototype.isServer = function () { return this._isServer; }; /** * Added to provide an error message for users who have not seen * the new instantiation breaking change warning and try to get * a collection directly from the core instance. */ Core.prototype.collection = function () { throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"); }; module.exports = Core; },{"./Db.js":6,"./Metrics.js":10,"./Overload":22,"./Shared":26}],5:[function(_dereq_,module,exports){ "use strict"; /** * @mixin */ var crcTable = (function () { var crcTable = [], c, n, k; for (n = 0; n < 256; n++) { c = n; for (k = 0; k < 8; k++) { c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line } crcTable[n] = c; } return crcTable; }()); module.exports = function(str) { var crc = 0 ^ (-1), // jshint ignore:line i; for (i = 0; i < str.length; i++) { crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line } return (crc ^ (-1)) >>> 0; // jshint ignore:line }; },{}],6:[function(_dereq_,module,exports){ "use strict"; var Shared, Core, Collection, Metrics, Crc, Overload; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB database instance. * @constructor */ var Db = function (name, core) { this.init.apply(this, arguments); }; Db.prototype.init = function (name, core) { this.core(core); this._primaryKey = '_id'; this._name = name; this._collection = {}; this._debug = {}; }; Shared.addModule('Db', Db); Db.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } if (callback) { callback(); } } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Db.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded method to non-instantiated object ForerunnerDB Db.moduleLoaded = Db.prototype.moduleLoaded; // Expose version method to non-instantiated object ForerunnerDB Db.version = Db.prototype.version; // Provide public access to the Shared object Db.shared = Shared; Db.prototype.shared = Shared; Shared.addModule('Db', Db); Shared.mixin(Db.prototype, 'Mixin.Common'); Shared.mixin(Db.prototype, 'Mixin.ChainReactor'); Shared.mixin(Db.prototype, 'Mixin.Constants'); Shared.mixin(Db.prototype, 'Mixin.Tags'); Core = Shared.modules.Core; Collection = _dereq_('./Collection.js'); Metrics = _dereq_('./Metrics.js'); Crc = _dereq_('./Crc.js'); Db.prototype._isServer = false; /** * Gets / sets the core object this database belongs to. */ Shared.synthesize(Db.prototype, 'core'); /** * Gets / sets the default primary key for new collections. * @param {String=} val The name of the primary key to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'primaryKey'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'state'); /** * Gets / sets the name of the database. * @param {String=} val The name of the database to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Db.prototype, 'mongoEmulation'); /** * Returns true if ForerunnerDB is running on a client browser. * @returns {boolean} */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Returns true if ForerunnerDB is running on a server. * @returns {boolean} */ Db.prototype.isServer = function () { return this._isServer; }; /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Db.prototype.crc = Crc; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Db.prototype.isServer = function () { return this._isServer; }; /** * Converts a normal javascript array of objects into a DB collection. * @param {Array} arr An array of objects. * @returns {Collection} A new collection instance with the data set to the * array passed. */ Db.prototype.arrayToCollection = function (arr) { return new Collection().setData(arr); }; /** * Registers an event listener against an event name. * @param {String} event The name of the event to listen for. * @param {Function} listener The listener method to call when * the event is fired. * @returns {*} */ Db.prototype.on = function(event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || []; this._listeners[event].push(listener); return this; }; /** * De-registers an event listener from an event name. * @param {String} event The name of the event to stop listening for. * @param {Function} listener The listener method passed to on() when * registering the event listener. * @returns {*} */ Db.prototype.off = function(event, listener) { if (event in this._listeners) { var arr = this._listeners[event], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } return this; }; /** * Emits an event by name with the given data. * @param {String} event The name of the event to emit. * @param {*=} data The data to emit with the event. * @returns {*} */ Db.prototype.emit = function(event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arr = this._listeners[event], arrCount = arr.length, arrIndex; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } return this; }; Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object. * @param search String or search object. * @returns {Array} */ Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object and return them in an object where each key is the name * of the collection that the document was matched in. * @param search String or search object. * @returns {object} */ Db.prototype.peekCat = function (search) { var i, coll, cat = {}, arr, typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = coll.peek(search); if (arr && arr.length) { cat[coll.name()] = arr; } } else { arr = coll.find(search); if (arr && arr.length) { cat[coll.name()] = arr; } } } } return cat; }; Db.prototype.drop = new Overload({ /** * Drops the database. * @func drop * @memberof Db */ '': function () { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional callback method. * @func drop * @memberof Db * @param {Function} callback Optional callback method. */ 'function': function (callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional persistent storage drop. Persistent * storage is dropped by default if no preference is provided. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. */ 'boolean': function (removePersist) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database and optionally controls dropping persistent storage * and callback method. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. * @param {Function} callback Optional callback method. */ 'boolean, function': function (removePersist, callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist, afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; } }); /** * Gets a database instance by name. * @memberof Core * @param {String=} name Optional name of the database. If none is provided * a random name is assigned. * @returns {Db} */ Core.prototype.db = function (name) { // Handle being passed an instance if (name instanceof Db) { return name; } if (!name) { name = this.objectId(); } this._db[name] = this._db[name] || new Db(name, this); this._db[name].mongoEmulation(this.mongoEmulation()); return this._db[name]; }; /** * Returns an array of databases that ForerunnerDB currently has. * @memberof Core * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each database * that ForerunnerDB is currently managing and it's child entities. */ Core.prototype.databases = function (search) { var arr = [], tmpObj, addDb, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in this._db) { if (this._db.hasOwnProperty(i)) { addDb = true; if (search) { if (!search.exec(i)) { addDb = false; } } if (addDb) { tmpObj = { name: i, children: [] }; if (this.shared.moduleExists('Collection')) { tmpObj.children.push({ module: 'collection', moduleName: 'Collections', count: this._db[i].collections().length }); } if (this.shared.moduleExists('CollectionGroup')) { tmpObj.children.push({ module: 'collectionGroup', moduleName: 'Collection Groups', count: this._db[i].collectionGroups().length }); } if (this.shared.moduleExists('Document')) { tmpObj.children.push({ module: 'document', moduleName: 'Documents', count: this._db[i].documents().length }); } if (this.shared.moduleExists('Grid')) { tmpObj.children.push({ module: 'grid', moduleName: 'Grids', count: this._db[i].grids().length }); } if (this.shared.moduleExists('Overview')) { tmpObj.children.push({ module: 'overview', moduleName: 'Overviews', count: this._db[i].overviews().length }); } if (this.shared.moduleExists('View')) { tmpObj.children.push({ module: 'view', moduleName: 'Views', count: this._db[i].views().length }); } arr.push(tmpObj); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Db'); module.exports = Db; },{"./Collection.js":3,"./Crc.js":5,"./Metrics.js":10,"./Overload":22,"./Shared":26}],7:[function(_dereq_,module,exports){ "use strict"; /* name id rebuild state match lookup */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), BinaryTree = _dereq_('./BinaryTree'), treeInstance = new BinaryTree(), btree = function () {}; treeInstance.inOrder('hash'); /** * The index class used to instantiate hash map indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexBinaryTree = function () { this.init.apply(this, arguments); }; IndexBinaryTree.prototype.init = function (keys, options, collection) { this._btree = new (btree.create(2, this.sortAsc))(); this._size = 0; this._id = this._itemKeyHash(keys, keys); this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); } this.name(options && options.name ? options.name : this._id); }; Shared.addModule('IndexBinaryTree', IndexBinaryTree); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor'); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting'); IndexBinaryTree.prototype.id = function () { return this._id; }; IndexBinaryTree.prototype.state = function () { return this._state; }; IndexBinaryTree.prototype.size = function () { return this._size; }; Shared.synthesize(IndexBinaryTree.prototype, 'data'); Shared.synthesize(IndexBinaryTree.prototype, 'name'); Shared.synthesize(IndexBinaryTree.prototype, 'collection'); Shared.synthesize(IndexBinaryTree.prototype, 'type'); Shared.synthesize(IndexBinaryTree.prototype, 'unique'); IndexBinaryTree.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexBinaryTree.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._btree = new (btree.create(2, this.sortAsc))(); if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexBinaryTree.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, dataItemHash = this._itemKeyHash(dataItem, this._keys), keyArr; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // We store multiple items that match a key inside an array // that is then stored against that key in the tree... // Check if item exists for this key already keyArr = this._btree.get(dataItemHash); // Check if the array exists if (keyArr === undefined) { // Generate an array for this key first keyArr = []; // Put the new array into the tree under the key this._btree.put(dataItemHash, keyArr); } // Push the item into the array keyArr.push(dataItem); this._size++; }; IndexBinaryTree.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, dataItemHash = this._itemKeyHash(dataItem, this._keys), keyArr, itemIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } // Try and get the array for the item hash key keyArr = this._btree.get(dataItemHash); if (keyArr !== undefined) { // The key array exits, remove the item from the key array itemIndex = keyArr.indexOf(dataItem); if (itemIndex > -1) { // Check the length of the array if (keyArr.length === 1) { // This item is the last in the array, just kill the tree entry this._btree.del(dataItemHash); } else { // Remove the item keyArr.splice(itemIndex, 1); } this._size--; } } }; IndexBinaryTree.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.lookup = function (query) { return this._data[this._itemHash(query, this._keys)] || []; }; IndexBinaryTree.prototype.match = function (query, options) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var pathSolver = new Path(); var indexKeyArr = pathSolver.parseArr(this._keys), queryArr = pathSolver.parseArr(query), matchedKeys = [], matchedKeyCount = 0, i; // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } else { // Query match failed - this is a hash map index so partial key match won't work return { matchedKeys: [], totalKeyCount: queryArr.length, score: 0 }; } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return pathSolver.countObjectPaths(this._keys, query); }; IndexBinaryTree.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexBinaryTree.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexBinaryTree.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('IndexBinaryTree'); module.exports = IndexBinaryTree; },{"./BinaryTree":2,"./Path":23,"./Shared":26}],8:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The index class used to instantiate hash map indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexHashMap = function () { this.init.apply(this, arguments); }; IndexHashMap.prototype.init = function (keys, options, collection) { this._crossRef = {}; this._size = 0; this._id = this._itemKeyHash(keys, keys); this.data({}); this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); } this.name(options && options.name ? options.name : this._id); }; Shared.addModule('IndexHashMap', IndexHashMap); Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor'); IndexHashMap.prototype.id = function () { return this._id; }; IndexHashMap.prototype.state = function () { return this._state; }; IndexHashMap.prototype.size = function () { return this._size; }; Shared.synthesize(IndexHashMap.prototype, 'data'); Shared.synthesize(IndexHashMap.prototype, 'name'); Shared.synthesize(IndexHashMap.prototype, 'collection'); Shared.synthesize(IndexHashMap.prototype, 'type'); Shared.synthesize(IndexHashMap.prototype, 'unique'); IndexHashMap.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexHashMap.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._data = {}; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexHashMap.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pushToPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.update = function (dataItem, options) { // TODO: Write updates to work // 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this) // 2: Remove the uniqueHash as it currently stands // 3: Generate a new uniqueHash for dataItem // 4: Insert the new uniqueHash }; IndexHashMap.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pullFromPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.pushToPathValue = function (hash, obj) { var pathValArr = this._data[hash] = this._data[hash] || []; // Make sure we have not already indexed this object at this path/value if (pathValArr.indexOf(obj) === -1) { // Index the object pathValArr.push(obj); // Record the reference to this object in our index size this._size++; // Cross-reference this association for later lookup this.pushToCrossRef(obj, pathValArr); } }; IndexHashMap.prototype.pullFromPathValue = function (hash, obj) { var pathValArr = this._data[hash], indexOfObject; // Make sure we have already indexed this object at this path/value indexOfObject = pathValArr.indexOf(obj); if (indexOfObject > -1) { // Un-index the object pathValArr.splice(indexOfObject, 1); // Record the reference to this object in our index size this._size--; // Remove object cross-reference this.pullFromCrossRef(obj, pathValArr); } // Check if we should remove the path value array if (!pathValArr.length) { // Remove the array delete this._data[hash]; } }; IndexHashMap.prototype.pull = function (obj) { // Get all places the object has been used and remove them var id = obj[this._collection.primaryKey()], crossRefArr = this._crossRef[id], arrIndex, arrCount = crossRefArr.length, arrItem; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = crossRefArr[arrIndex]; // Remove item from this index lookup array this._pullFromArray(arrItem, obj); } // Record the reference to this object in our index size this._size--; // Now remove the cross-reference entry for this object delete this._crossRef[id]; }; IndexHashMap.prototype._pullFromArray = function (arr, obj) { var arrCount = arr.length; while (arrCount--) { if (arr[arrCount] === obj) { arr.splice(arrCount, 1); } } }; IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()], crObj; this._crossRef[id] = this._crossRef[id] || []; // Check if the cross-reference to the pathVal array already exists crObj = this._crossRef[id]; if (crObj.indexOf(pathValArr) === -1) { // Add the cross-reference crObj.push(pathValArr); } }; IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()]; delete this._crossRef[id]; }; IndexHashMap.prototype.lookup = function (query) { return this._data[this._itemHash(query, this._keys)] || []; }; IndexHashMap.prototype.match = function (query, options) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var pathSolver = new Path(); var indexKeyArr = pathSolver.parseArr(this._keys), queryArr = pathSolver.parseArr(query), matchedKeys = [], matchedKeyCount = 0, i; // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } else { // Query match failed - this is a hash map index so partial key match won't work return { matchedKeys: [], totalKeyCount: queryArr.length, score: 0 }; } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return pathSolver.countObjectPaths(this._keys, query); }; IndexHashMap.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexHashMap.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexHashMap.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('IndexHashMap'); module.exports = IndexHashMap; },{"./Path":23,"./Shared":26}],9:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * The key value store class used when storing basic in-memory KV data, * and can be queried for quick retrieval. Mostly used for collection * primary key indexes and lookups. * @param {String=} name Optional KV store name. * @constructor */ var KeyValueStore = function (name) { this.init.apply(this, arguments); }; KeyValueStore.prototype.init = function (name) { this._name = name; this._data = {}; this._primaryKey = '_id'; }; Shared.addModule('KeyValueStore', KeyValueStore); Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor'); /** * Get / set the name of the key/value store. * @param {String} val The name to set. * @returns {*} */ Shared.synthesize(KeyValueStore.prototype, 'name'); /** * Get / set the primary key. * @param {String} key The key to set. * @returns {*} */ KeyValueStore.prototype.primaryKey = function (key) { if (key !== undefined) { this._primaryKey = key; return this; } return this._primaryKey; }; /** * Removes all data from the store. * @returns {*} */ KeyValueStore.prototype.truncate = function () { this._data = {}; return this; }; /** * Sets data against a key in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {*} */ KeyValueStore.prototype.set = function (key, value) { this._data[key] = value ? value : true; return this; }; /** * Gets data stored for the passed key. * @param {String} key The key to get data for. * @returns {*} */ KeyValueStore.prototype.get = function (key) { return this._data[key]; }; /** * Get / set the primary key. * @param {*} obj A lookup query, can be a string key, an array of string keys, * an object with further query clauses or a regular expression that should be * run against all keys. * @returns {*} */ KeyValueStore.prototype.lookup = function (obj) { var pKeyVal = obj[this._primaryKey], arrIndex, arrCount, lookupItem, result; if (pKeyVal instanceof Array) { // An array of primary keys, find all matches arrCount = pKeyVal.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { lookupItem = this._data[pKeyVal[arrIndex]]; if (lookupItem) { result.push(lookupItem); } } return result; } else if (pKeyVal instanceof RegExp) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (pKeyVal.test(arrIndex)) { result.push(this._data[arrIndex]); } } } return result; } else if (typeof pKeyVal === 'object') { // The primary key clause is an object, now we have to do some // more extensive searching if (pKeyVal.$ne) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (arrIndex !== pKeyVal.$ne) { result.push(this._data[arrIndex]); } } } return result; } if (pKeyVal.$in && (pKeyVal.$in instanceof Array)) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (pKeyVal.$in.indexOf(arrIndex) > -1) { result.push(this._data[arrIndex]); } } } return result; } if (pKeyVal.$nin && (pKeyVal.$nin instanceof Array)) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (pKeyVal.$nin.indexOf(arrIndex) === -1) { result.push(this._data[arrIndex]); } } } return result; } if (pKeyVal.$or && (pKeyVal.$or instanceof Array)) { // Create new data result = []; for (arrIndex = 0; arrIndex < pKeyVal.$or.length; arrIndex++) { result = result.concat(this.lookup(pKeyVal.$or[arrIndex])); } return result; } } else { // Key is a basic lookup from string lookupItem = this._data[pKeyVal]; if (lookupItem !== undefined) { return [lookupItem]; } else { return []; } } }; /** * Removes data for the given key from the store. * @param {String} key The key to un-set. * @returns {*} */ KeyValueStore.prototype.unSet = function (key) { delete this._data[key]; return this; }; /** * Sets data for the give key in the store only where the given key * does not already have a value in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {Boolean} True if data was set or false if data already * exists for the key. */ KeyValueStore.prototype.uniqueSet = function (key, value) { if (this._data[key] === undefined) { this._data[key] = value; return true; } return false; }; Shared.finishModule('KeyValueStore'); module.exports = KeyValueStore; },{"./Shared":26}],10:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Operation = _dereq_('./Operation'); /** * The metrics class used to store details about operations. * @constructor */ var Metrics = function () { this.init.apply(this, arguments); }; Metrics.prototype.init = function () { this._data = []; }; Shared.addModule('Metrics', Metrics); Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor'); /** * Creates an operation within the metrics instance and if metrics * are currently enabled (by calling the start() method) the operation * is also stored in the metrics log. * @param {String} name The name of the operation. * @returns {Operation} */ Metrics.prototype.create = function (name) { var op = new Operation(name); if (this._enabled) { this._data.push(op); } return op; }; /** * Starts logging operations. * @returns {Metrics} */ Metrics.prototype.start = function () { this._enabled = true; return this; }; /** * Stops logging operations. * @returns {Metrics} */ Metrics.prototype.stop = function () { this._enabled = false; return this; }; /** * Clears all logged operations. * @returns {Metrics} */ Metrics.prototype.clear = function () { this._data = []; return this; }; /** * Returns an array of all logged operations. * @returns {Array} */ Metrics.prototype.list = function () { return this._data; }; Shared.finishModule('Metrics'); module.exports = Metrics; },{"./Operation":21,"./Shared":26}],11:[function(_dereq_,module,exports){ "use strict"; var CRUD = { preSetData: function () { }, postSetData: function () { } }; module.exports = CRUD; },{}],12:[function(_dereq_,module,exports){ "use strict"; /** * The chain reactor mixin, provides methods to the target object that allow chain * reaction events to propagate to the target and be handled, processed and passed * on down the chain. * @mixin */ var ChainReactor = { /** * * @param obj */ chain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list'); } } this._chain = this._chain || []; var index = this._chain.indexOf(obj); if (index === -1) { this._chain.push(obj); } }, unChain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list'); } } if (this._chain) { var index = this._chain.indexOf(obj); if (index > -1) { this._chain.splice(index, 1); } } }, chainSend: function (type, data, options) { if (this._chain) { var arr = this._chain, arrItem, count = arr.length, index; for (index = 0; index < count; index++) { arrItem = arr[index]; if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) { if (this.debug && this.debug()) { if (arrItem._reactorIn && arrItem._reactorOut) { console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"'); } else { console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"'); } } arrItem.chainReceive(this, type, data, options); } else { console.log('Reactor Data:', type, data, options); console.log('Reactor Node:', arrItem); throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!'); } } } }, chainReceive: function (sender, type, data, options) { var chainPacket = { sender: sender, type: type, data: data, options: options }; if (this.debug && this.debug()) { console.log(this.logIdentifier() + 'Received data from parent reactor node'); } // Fire our internal handler if (!this._chainHandler || (this._chainHandler && !this._chainHandler(chainPacket))) { // Propagate the message down the chain this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options); } } }; module.exports = ChainReactor; },{}],13:[function(_dereq_,module,exports){ "use strict"; var idCounter = 0, Overload = _dereq_('./Overload'), Serialiser = _dereq_('./Serialiser'), Common, serialiser = new Serialiser(); /** * Provides commonly used methods to most classes in ForerunnerDB. * @mixin */ Common = { // Expose the serialiser object so it can be extended with new data handlers. serialiser: serialiser, /** * Gets / sets data in the item store. The store can be used to set and * retrieve data against a key. Useful for adding arbitrary key/value data * to a collection / view etc and retrieving it later. * @param {String|*} key The key under which to store the passed value or * retrieve the existing stored value. * @param {*=} val Optional value. If passed will overwrite the existing value * stored against the specified key if one currently exists. * @returns {*} */ store: function (key, val) { if (key !== undefined) { if (val !== undefined) { // Store the data this._store = this._store || {}; this._store[key] = val; return this; } if (this._store) { return this._store[key]; } } return undefined; }, /** * Removes a previously stored key/value pair from the item store, set previously * by using the store() method. * @param {String|*} key The key of the key/value pair to remove; * @returns {Common} Returns this for chaining. */ unStore: function (key) { if (key !== undefined) { delete this._store[key]; } return this; }, /** * Returns a non-referenced version of the passed object / array. * @param {Object} data The object or array to return as a non-referenced version. * @param {Number=} copies Optional number of copies to produce. If specified, the return * value will be an array of decoupled objects, each distinct from the other. * @returns {*} */ decouple: function (data, copies) { if (data !== undefined) { if (!copies) { return this.jParse(this.jStringify(data)); } else { var i, json = this.jStringify(data), copyArr = []; for (i = 0; i < copies; i++) { copyArr.push(this.jParse(json)); } return copyArr; } } return undefined; }, /** * Parses and returns data from stringified version. * @param {String} data The stringified version of data to parse. * @returns {Object} The parsed JSON object from the data. */ jParse: function (data) { return serialiser.parse(data); //return JSON.parse(data); }, /** * Converts a JSON object into a stringified version. * @param {Object} data The data to stringify. * @returns {String} The stringified data. */ jStringify: function (data) { return serialiser.stringify(data); //return JSON.stringify(data); }, /** * Generates a new 16-character hexadecimal unique ID or * generates a new 16-character hexadecimal ID based on * the passed string. Will always generate the same ID * for the same string. * @param {String=} str A string to generate the ID from. * @return {String} */ objectId: function (str) { var id, pow = Math.pow(10, 17); if (!str) { idCounter++; id = (idCounter + ( Math.random() * pow + Math.random() * pow + Math.random() * pow + Math.random() * pow )).toString(16); } else { var val = 0, count = str.length, i; for (i = 0; i < count; i++) { val += str.charCodeAt(i) * pow; } id = val.toString(16); } return id; }, /** * Gets / sets debug flag that can enable debug message output to the * console if required. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ /** * Sets debug flag for a particular type that can enable debug message * output to the console if required. * @param {String} type The name of the debug type to set flag for. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ debug: new Overload([ function () { return this._debug && this._debug.all; }, function (val) { if (val !== undefined) { if (typeof val === 'boolean') { this._debug = this._debug || {}; this._debug.all = val; this.chainSend('debug', this._debug); return this; } else { return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all); } } return this._debug && this._debug.all; }, function (type, val) { if (type !== undefined) { if (val !== undefined) { this._debug = this._debug || {}; this._debug[type] = val; this.chainSend('debug', this._debug); return this; } return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]); } return this._debug && this._debug.all; } ]), /** * Returns a string describing the class this instance is derived from. * @returns {string} */ classIdentifier: function () { return 'ForerunnerDB.' + this.className; }, /** * Returns a string describing the instance by it's class name and instance * object name. * @returns {String} The instance identifier. */ instanceIdentifier: function () { return '[' + this.className + ']' + this.name(); }, /** * Returns a string used to denote a console log against this instance, * consisting of the class identifier and instance identifier. * @returns {string} The log identifier. */ logIdentifier: function () { return this.classIdentifier() + ': ' + this.instanceIdentifier(); }, /** * Converts a query object with MongoDB dot notation syntax * to Forerunner's object notation syntax. * @param {Object} obj The object to convert. */ convertToFdb: function (obj) { var varName, splitArr, objCopy, i; for (i in obj) { if (obj.hasOwnProperty(i)) { objCopy = obj; if (i.indexOf('.') > -1) { // Replace .$ with a placeholder before splitting by . char i = i.replace('.$', '[|$|]'); splitArr = i.split('.'); while ((varName = splitArr.shift())) { // Replace placeholder back to original .$ varName = varName.replace('[|$|]', '.$'); if (splitArr.length) { objCopy[varName] = {}; } else { objCopy[varName] = obj[i]; } objCopy = objCopy[varName]; } delete obj[i]; } } } }, /** * Checks if the state is dropped. * @returns {boolean} True when dropped, false otherwise. */ isDropped: function () { return this._state === 'dropped'; } }; module.exports = Common; },{"./Overload":22,"./Serialiser":25}],14:[function(_dereq_,module,exports){ "use strict"; /** * Provides some database constants. * @mixin */ var Constants = { TYPE_INSERT: 0, TYPE_UPDATE: 1, TYPE_REMOVE: 2, PHASE_BEFORE: 0, PHASE_AFTER: 1 }; module.exports = Constants; },{}],15:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * Provides event emitter functionality including the methods: on, off, once, emit, deferEmit. * @mixin */ var Events = { on: new Overload({ /** * Attach an event listener to the passed event. * @param {String} event The name of the event to listen for. * @param {Function} listener The method to call when the event is fired. */ 'string, function': function (event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event]['*'] = this._listeners[event]['*'] || []; this._listeners[event]['*'].push(listener); return this; }, /** * Attach an event listener to the passed event only if the passed * id matches the document id for the event being fired. * @param {String} event The name of the event to listen for. * @param {*} id The document id to match against. * @param {Function} listener The method to call when the event is fired. */ 'string, *, function': function (event, id, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event][id] = this._listeners[event][id] || []; this._listeners[event][id].push(listener); return this; } }), once: new Overload({ 'string, function': function (eventName, callback) { var self = this, internalCallback = function () { self.off(eventName, internalCallback); callback.apply(self, arguments); }; return this.on(eventName, internalCallback); }, 'string, *, function': function (eventName, id, callback) { var self = this, internalCallback = function () { self.off(eventName, id, internalCallback); callback.apply(self, arguments); }; return this.on(eventName, id, internalCallback); } }), off: new Overload({ 'string': function (event) { if (this._listeners && this._listeners[event] && event in this._listeners) { delete this._listeners[event]; } return this; }, 'string, function': function (event, listener) { var arr, index; if (typeof(listener) === 'string') { if (this._listeners && this._listeners[event] && this._listeners[event][listener]) { delete this._listeners[event][listener]; } } else { if (this._listeners && event in this._listeners) { arr = this._listeners[event]['*']; index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } } return this; }, 'string, *, function': function (event, id, listener) { if (this._listeners && event in this._listeners && id in this.listeners[event]) { var arr = this._listeners[event][id], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } }, 'string, *': function (event, id) { if (this._listeners && event in this._listeners && id in this._listeners[event]) { // Kill all listeners for this event id delete this._listeners[event][id]; } } }), emit: function (event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arrIndex, arrCount, tmpFunc, arr, listenerIdArr, listenerIdCount, listenerIdIndex; // Handle global emit if (this._listeners[event]['*']) { arr = this._listeners[event]['*']; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Check we have a function to execute tmpFunc = arr[arrIndex]; if (typeof tmpFunc === 'function') { tmpFunc.apply(this, Array.prototype.slice.call(arguments, 1)); } } } // Handle individual emit if (data instanceof Array) { // Check if the array is an array of objects in the collection if (data[0] && data[0][this._primaryKey]) { // Loop the array and check for listeners against the primary key listenerIdArr = this._listeners[event]; arrCount = data.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { if (listenerIdArr[data[arrIndex][this._primaryKey]]) { // Emit for this id listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length; for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) { tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex]; if (typeof tmpFunc === 'function') { listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } } } } } } return this; }, /** * Queues an event to be fired. This has automatic de-bouncing so that any * events of the same type that occur within 100 milliseconds of a previous * one will all be wrapped into a single emit rather than emitting tons of * events for lots of chained inserts etc. Only the data from the last * de-bounced event will be emitted. * @param {String} eventName The name of the event to emit. * @param {*=} data Optional data to emit with the event. */ deferEmit: function (eventName, data) { var self = this, args; if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) { args = arguments; // Check for an existing timeout this._deferTimeout = this._deferTimeout || {}; if (this._deferTimeout[eventName]) { clearTimeout(this._deferTimeout[eventName]); } // Set a timeout this._deferTimeout[eventName] = setTimeout(function () { if (self.debug()) { console.log(self.logIdentifier() + ' Emitting ' + args[0]); } self.emit.apply(self, args); }, 1); } else { this.emit.apply(this, arguments); } return this; } }; module.exports = Events; },{"./Overload":22}],16:[function(_dereq_,module,exports){ "use strict"; /** * Provides object matching algorithm methods. * @mixin */ var Matching = { /** * Internal method that checks a document against a test object. * @param {*} source The source object or value to test against. * @param {*} test The test object or value to test with. * @param {Object} queryOptions The options the query was passed with. * @param {String=} opToApply The special operation to apply to the test such * as 'and' or an 'or' operator. * @param {Object=} options An object containing options to apply to the * operation such as limiting the fields returned etc. * @returns {Boolean} True if the test was positive, false on negative. * @private */ _match: function (source, test, queryOptions, opToApply, options) { // TODO: This method is quite long, break into smaller pieces var operation, applyOp = opToApply, recurseVal, tmpIndex, sourceType = typeof source, testType = typeof test, matchedAll = true, opResult, substringCache, i; options = options || {}; queryOptions = queryOptions || {}; // Check if options currently holds a root query object if (!options.$rootQuery) { // Root query not assigned, hold the root query options.$rootQuery = test; } // Check if options currently holds a root source object if (!options.$rootSource) { // Root query not assigned, hold the root query options.$rootSource = source; } // Assign current query data options.$currentQuery = test; options.$rootData = options.$rootData || {}; // Check if the comparison data are both strings or numbers if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) { // The source and test data are flat types that do not require recursive searches, // so just compare them and return the result if (sourceType === 'number') { // Number comparison if (source !== test) { matchedAll = false; } } else { // String comparison // TODO: We can probably use a queryOptions.$locale as a second parameter here // TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35 if (source.localeCompare(test)) { matchedAll = false; } } } else if ((sourceType === 'string' || sourceType === 'number') && (testType === 'object' && test instanceof RegExp)) { if (!test.test(source)) { matchedAll = false; } } else { for (i in test) { if (test.hasOwnProperty(i)) { // Assign previous query data options.$previousQuery = options.$parent; // Assign parent query data options.$parent = { query: test[i], key: i, parent: options.$previousQuery }; // Reset operation flag operation = false; // Grab first two chars of the key name to check for $ substringCache = i.substr(0, 2); // Check if the property is a comment (ignorable) if (substringCache === '//') { // Skip this property continue; } // Check if the property starts with a dollar (function) if (substringCache.indexOf('$') === 0) { // Ask the _matchOp method to handle the operation opResult = this._matchOp(i, source, test[i], queryOptions, options); // Check the result of the matchOp operation // If the result is -1 then no operation took place, otherwise the result // will be a boolean denoting a match (true) or no match (false) if (opResult > -1) { if (opResult) { if (opToApply === 'or') { return true; } } else { // Set the matchedAll flag to the result of the operation // because the operation did not return true matchedAll = opResult; } // Record that an operation was handled operation = true; } } // Check for regex if (!operation && test[i] instanceof RegExp) { operation = true; if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } if (!operation) { // Check if our query is an object if (typeof(test[i]) === 'object') { // Because test[i] is an object, source must also be an object // Check if our source data we are checking the test query against // is an object or an array if (source[i] !== undefined) { if (source[i] instanceof Array && !(test[i] instanceof Array)) { // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (!(source[i] instanceof Array) && test[i] instanceof Array) { // The test key data is an array and the source key data is not so check // each item in the test key data to see if the source item matches one // of them. This is effectively an $in search. recurseVal = false; for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) { recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (typeof(source) === 'object') { // Recurse down the object tree recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } } else { // First check if the test match is an $exists if (test[i] && test[i].$exists !== undefined) { // Push the item through another match recurse recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } else { // Check if the prop matches our test value if (source && source[i] === test[i]) { if (opToApply === 'or') { return true; } } else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") { // We are looking for a value inside an array // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } if (opToApply === 'and' && !matchedAll) { return false; } } } } return matchedAll; }, /** * Internal method, performs a matching process against a query operator such as $gt or $nin. * @param {String} key The property name in the test that matches the operator to perform * matching against. * @param {*} source The source data to match the query against. * @param {*} test The query to match the source against. * @param {Object} queryOptions The options the query was passed with. * @param {Object=} options An options object. * @returns {*} * @private */ _matchOp: function (key, source, test, queryOptions, options) { // Check for commands switch (key) { case '$gt': // Greater than return source > test; case '$gte': // Greater than or equal return source >= test; case '$lt': // Less than return source < test; case '$lte': // Less than or equal return source <= test; case '$exists': // Property exists return (source === undefined) !== test; case '$eq': // Equals return source == test; // jshint ignore:line case '$eeq': // Equals equals return source === test; case '$ne': // Not equals return source != test; // jshint ignore:line case '$nee': // Not equals equals return source !== test; case '$or': // Match true on ANY check to pass for (var orIndex = 0; orIndex < test.length; orIndex++) { if (this._match(source, test[orIndex], queryOptions, 'and', options)) { return true; } } return false; case '$and': // Match true on ALL checks to pass for (var andIndex = 0; andIndex < test.length; andIndex++) { if (!this._match(source, test[andIndex], queryOptions, 'and', options)) { return false; } } return true; case '$in': // In // Check that the in test is an array if (test instanceof Array) { var inArr = test, inArrCount = inArr.length, inArrIndex; for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) { if (this._match(source, inArr[inArrIndex], queryOptions, 'and', options)) { return true; } } return false; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { throw(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key); } break; case '$nin': // Not in // Check that the not-in test is an array if (test instanceof Array) { var notInArr = test, notInArrCount = notInArr.length, notInArrIndex; for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) { if (this._match(source, notInArr[notInArrIndex], queryOptions, 'and', options)) { return false; } } return true; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { throw(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key); } break; case '$distinct': // Ensure options holds a distinct lookup options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {}; for (var distinctProp in test) { if (test.hasOwnProperty(distinctProp)) { options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {}; // Check if the options distinct lookup has this field's value if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) { // Value is already in use return false; } else { // Set the value in the lookup options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true; // Allow the item in the results return true; } } } break; case '$count': var countKey, countArr, countVal; // Iterate the count object's keys for (countKey in test) { if (test.hasOwnProperty(countKey)) { // Check the property exists and is an array. If the property being counted is not // an array (or doesn't exist) then use a value of zero in any further count logic countArr = source[countKey]; if (typeof countArr === 'object' && countArr instanceof Array) { countVal = countArr.length; } else { countVal = 0; } // Now recurse down the query chain further to satisfy the query for this key (countKey) if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) { return false; } } } // Allow the item in the results return true; case '$find': case '$findOne': case '$findSub': var fromType = 'collection', findQuery, findOptions, subQuery, subOptions, subPath, result, operation = {}; // Check we have a database object to work from if (!this.db()) { throw('Cannot operate a ' + key + ' sub-query on an anonymous collection (one with no db set)!'); } // Check all parts of the $find operation exist if (!test.$from) { throw(key + ' missing $from property!'); } if (test.$fromType) { fromType = test.$fromType; // Check the fromType exists as a method if (!this.db()[fromType] || typeof this.db()[fromType] !== 'function') { throw(key + ' cannot operate against $fromType "' + fromType + '" because the database does not recognise this type of object!'); } } // Perform the find operation findQuery = test.$query || {}; findOptions = test.$options || {}; if (key === '$findSub') { if (!test.$path) { throw(key + ' missing $path property!'); } subPath = test.$path; subQuery = test.$subQuery || {}; subOptions = test.$subOptions || {}; result = this.db()[fromType](test.$from).findSub(findQuery, subPath, subQuery, subOptions); } else { result = this.db()[fromType](test.$from)[key.substr(1)](findQuery, findOptions); } operation[options.$parent.parent.key] = result; return this._match(source, operation, queryOptions, 'and', options); } return -1; } }; module.exports = Matching; },{}],17:[function(_dereq_,module,exports){ "use strict"; /** * Provides sorting methods. * @mixin */ var Sorting = { /** * Sorts the passed value a against the passed value b ascending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortAsc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return a.localeCompare(b); } else { if (a > b) { return 1; } else if (a < b) { return -1; } } return 0; }, /** * Sorts the passed value a against the passed value b descending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortDesc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return b.localeCompare(a); } else { if (a > b) { return -1; } else if (a < b) { return 1; } } return 0; } }; module.exports = Sorting; },{}],18:[function(_dereq_,module,exports){ "use strict"; var Tags, tagMap = {}; /** * Provides class instance tagging and tag operation methods. * @mixin */ Tags = { /** * Tags a class instance for later lookup. * @param {String} name The tag to add. * @returns {boolean} */ tagAdd: function (name) { var i, self = this, mapArr = tagMap[name] = tagMap[name] || []; for (i = 0; i < mapArr.length; i++) { if (mapArr[i] === self) { return true; } } mapArr.push(self); // Hook the drop event for this so we can react if (self.on) { self.on('drop', function () { // We've been dropped so remove ourselves from the tag map self.tagRemove(name); }); } return true; }, /** * Removes a tag from a class instance. * @param {String} name The tag to remove. * @returns {boolean} */ tagRemove: function (name) { var i, mapArr = tagMap[name]; if (mapArr) { for (i = 0; i < mapArr.length; i++) { if (mapArr[i] === this) { mapArr.splice(i, 1); return true; } } } return false; }, /** * Gets an array of all instances tagged with the passed tag name. * @param {String} name The tag to lookup. * @returns {Array} The array of instances that have the passed tag. */ tagLookup: function (name) { return tagMap[name] || []; }, /** * Drops all instances that are tagged with the passed tag name. * @param {String} name The tag to lookup. * @param {Function} callback Callback once dropping has completed * for all instances that match the passed tag name. * @returns {boolean} */ tagDrop: function (name, callback) { var arr = this.tagLookup(name), dropCb, dropCount, i; dropCb = function () { dropCount--; if (callback && dropCount === 0) { callback(false); } }; if (arr.length) { dropCount = arr.length; // Loop the array and drop all items for (i = arr.length - 1; i >= 0; i--) { arr[i].drop(dropCb); } } return true; } }; module.exports = Tags; },{}],19:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * Provides trigger functionality methods. * @mixin */ var Triggers = { /** * Add a trigger by id. * @param {String} id The id of the trigger. This must be unique to the type and * phase of the trigger. Only one trigger may be added with this id per type and * phase. * @param {Number} type The type of operation to apply the trigger to. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of an operation to fire the trigger on. See * Mixin.Constants for constants to use. * @param {Function} method The method to call when the trigger is fired. * @returns {boolean} True if the trigger was added successfully, false if not. */ addTrigger: function (id, type, phase, method) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex === -1) { // The trigger does not exist, create it self._trigger = self._trigger || {}; self._trigger[type] = self._trigger[type] || {}; self._trigger[type][phase] = self._trigger[type][phase] || []; self._trigger[type][phase].push({ id: id, method: method, enabled: true }); return true; } return false; }, /** * * @param {String} id The id of the trigger to remove. * @param {Number} type The type of operation to remove the trigger from. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of the operation to remove the trigger from. * See Mixin.Constants for constants to use. * @returns {boolean} True if removed successfully, false if not. */ removeTrigger: function (id, type, phase) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // The trigger exists, remove it self._trigger[type][phase].splice(triggerIndex, 1); } return false; }, enableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = true; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = true; return true; } return false; } }), disableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = false; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = false; return true; } return false; } }), /** * Checks if a trigger will fire based on the type and phase provided. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {Boolean} True if the trigger will fire, false otherwise. */ willTrigger: function (type, phase) { if (this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) { // Check if a trigger in this array is enabled var arr = this._trigger[type][phase], i; for (i = 0; i < arr.length; i++) { if (arr[i].enabled) { return true; } } } return false; }, /** * Processes trigger actions based on the operation, type and phase. * @param {Object} operation Operation data to pass to the trigger. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @param {Object} oldDoc The document snapshot before operations are * carried out against the data. * @param {Object} newDoc The document snapshot after operations are * carried out against the data. * @returns {boolean} */ processTrigger: function (operation, type, phase, oldDoc, newDoc) { var self = this, triggerArr, triggerIndex, triggerCount, triggerItem, response; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { triggerItem = triggerArr[triggerIndex]; // Check if the trigger is enabled if (triggerItem.enabled) { if (this.debug()) { var typeName, phaseName; switch (type) { case this.TYPE_INSERT: typeName = 'insert'; break; case this.TYPE_UPDATE: typeName = 'update'; break; case this.TYPE_REMOVE: typeName = 'remove'; break; default: typeName = ''; break; } switch (phase) { case this.PHASE_BEFORE: phaseName = 'before'; break; case this.PHASE_AFTER: phaseName = 'after'; break; default: phaseName = ''; break; } //console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"'); } // Run the trigger's method and store the response response = triggerItem.method.call(self, operation, oldDoc, newDoc); // Check the response for a non-expected result (anything other than // undefined, true or false is considered a throwable error) if (response === false) { // The trigger wants us to cancel operations return false; } if (response !== undefined && response !== true && response !== false) { // Trigger responded with error, throw the error throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response); } } } // Triggers all ran without issue, return a success (true) return true; } }, /** * Returns the index of a trigger by id based on type and phase. * @param {String} id The id of the trigger to find the index of. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {number} * @private */ _triggerIndexOf: function (id, type, phase) { var self = this, triggerArr, triggerCount, triggerIndex; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { if (triggerArr[triggerIndex].id === id) { return triggerIndex; } } } return -1; } }; module.exports = Triggers; },{"./Overload":22}],20:[function(_dereq_,module,exports){ "use strict"; /** * Provides methods to handle object update operations. * @mixin */ var Updating = { /** * Updates a property on an object. * @param {Object} doc The object whose property is to be updated. * @param {String} prop The property to update. * @param {*} val The new value of the property. * @private */ _updateProperty: function (doc, prop, val) { doc[prop] = val; if (this.debug()) { console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '"'); } }, /** * Increments a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to increment by. * @private */ _updateIncrement: function (doc, prop, val) { doc[prop] += val; }, /** * Changes the index of an item in the passed array. * @param {Array} arr The array to modify. * @param {Number} indexFrom The index to move the item from. * @param {Number} indexTo The index to move the item to. * @private */ _updateSpliceMove: function (arr, indexFrom, indexTo) { arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]); if (this.debug()) { console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"'); } }, /** * Inserts an item into the passed array at the specified index. * @param {Array} arr The array to insert into. * @param {Number} index The index to insert at. * @param {Object} doc The document to insert. * @private */ _updateSplicePush: function (arr, index, doc) { if (arr.length > index) { arr.splice(index, 0, doc); } else { arr.push(doc); } }, /** * Inserts an item at the end of an array. * @param {Array} arr The array to insert the item into. * @param {Object} doc The document to insert. * @private */ _updatePush: function (arr, doc) { arr.push(doc); }, /** * Removes an item from the passed array. * @param {Array} arr The array to modify. * @param {Number} index The index of the item in the array to remove. * @private */ _updatePull: function (arr, index) { arr.splice(index, 1); }, /** * Multiplies a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to multiply by. * @private */ _updateMultiply: function (doc, prop, val) { doc[prop] *= val; }, /** * Renames a property on a document to the passed property. * @param {Object} doc The document to modify. * @param {String} prop The property to rename. * @param {Number} val The new property name. * @private */ _updateRename: function (doc, prop, val) { doc[val] = doc[prop]; delete doc[prop]; }, /** * Sets a property on a document to the passed value. * @param {Object} doc The document to modify. * @param {String} prop The property to set. * @param {*} val The new property value. * @private */ _updateOverwrite: function (doc, prop, val) { doc[prop] = val; }, /** * Deletes a property on a document. * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @private */ _updateUnset: function (doc, prop) { delete doc[prop]; }, /** * Removes all properties from an object without destroying * the object instance, thereby maintaining data-bound linking. * @param {Object} doc The parent object to modify. * @param {String} prop The name of the child object to clear. * @private */ _updateClear: function (doc, prop) { var obj = doc[prop], i; if (obj && typeof obj === 'object') { for (i in obj) { if (obj.hasOwnProperty(i)) { this._updateUnset(obj, i); } } } }, /** * Pops an item or items from the array stack. * @param {Object} doc The document to modify. * @param {Number} val If set to a positive integer, will pop the number specified * from the stack, if set to a negative integer will shift the number specified * from the stack. * @return {Boolean} * @private */ _updatePop: function (doc, val) { var updated = false, i; if (doc.length > 0) { if (val > 0) { for (i = 0; i < val; i++) { doc.pop(); } updated = true; } else if (val < 0) { for (i = 0; i > val; i--) { doc.shift(); } updated = true; } } return updated; } }; module.exports = Updating; },{}],21:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The operation class, used to store details about an operation being * performed by the database. * @param {String} name The name of the operation. * @constructor */ var Operation = function (name) { this.pathSolver = new Path(); this.counter = 0; this.init.apply(this, arguments); }; Operation.prototype.init = function (name) { this._data = { operation: name, // The name of the operation executed such as "find", "update" etc index: { potential: [], // Indexes that could have potentially been used used: false // The index that was picked to use }, steps: [], // The steps taken to generate the query results, time: { startMs: 0, stopMs: 0, totalMs: 0, process: {} }, flag: {}, // An object with flags that denote certain execution paths log: [] // Any extra data that might be useful such as warnings or helpful hints }; }; Shared.addModule('Operation', Operation); Shared.mixin(Operation.prototype, 'Mixin.ChainReactor'); /** * Starts the operation timer. */ Operation.prototype.start = function () { this._data.time.startMs = new Date().getTime(); }; /** * Adds an item to the operation log. * @param {String} event The item to log. * @returns {*} */ Operation.prototype.log = function (event) { if (event) { var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0, logObj = { event: event, time: new Date().getTime(), delta: 0 }; this._data.log.push(logObj); if (lastLogTime) { logObj.delta = logObj.time - lastLogTime; } return this; } return this._data.log; }; /** * Called when starting and ending a timed operation, used to time * internal calls within an operation's execution. * @param {String} section An operation name. * @returns {*} */ Operation.prototype.time = function (section) { if (section !== undefined) { var process = this._data.time.process, processObj = process[section] = process[section] || {}; if (!processObj.startMs) { // Timer started processObj.startMs = new Date().getTime(); processObj.stepObj = { name: section }; this._data.steps.push(processObj.stepObj); } else { processObj.stopMs = new Date().getTime(); processObj.totalMs = processObj.stopMs - processObj.startMs; processObj.stepObj.totalMs = processObj.totalMs; delete processObj.stepObj; } return this; } return this._data.time; }; /** * Used to set key/value flags during operation execution. * @param {String} key * @param {String} val * @returns {*} */ Operation.prototype.flag = function (key, val) { if (key !== undefined && val !== undefined) { this._data.flag[key] = val; } else if (key !== undefined) { return this._data.flag[key]; } else { return this._data.flag; } }; Operation.prototype.data = function (path, val, noTime) { if (val !== undefined) { // Assign value to object path this.pathSolver.set(this._data, path, val); return this; } return this.pathSolver.get(this._data, path); }; Operation.prototype.pushData = function (path, val, noTime) { // Assign value to object path this.pathSolver.push(this._data, path, val); }; /** * Stops the operation timer. */ Operation.prototype.stop = function () { this._data.time.stopMs = new Date().getTime(); this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs; }; Shared.finishModule('Operation'); module.exports = Operation; },{"./Path":23,"./Shared":26}],22:[function(_dereq_,module,exports){ "use strict"; /** * Allows a method to accept overloaded calls with different parameters controlling * which passed overload function is called. * @param {Object} def * @returns {Function} * @constructor */ var Overload = function (def) { if (def) { var self = this, index, count, tmpDef, defNewKey, sigIndex, signatures; if (!(def instanceof Array)) { tmpDef = {}; // Def is an object, make sure all prop names are devoid of spaces for (index in def) { if (def.hasOwnProperty(index)) { defNewKey = index.replace(/ /g, ''); // Check if the definition array has a * string in it if (defNewKey.indexOf('*') === -1) { // No * found tmpDef[defNewKey] = def[index]; } else { // A * was found, generate the different signatures that this // definition could represent signatures = this.generateSignaturePermutations(defNewKey); for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) { if (!tmpDef[signatures[sigIndex]]) { tmpDef[signatures[sigIndex]] = def[index]; } } } } } def = tmpDef; } return function () { var arr = [], lookup, type, name; // Check if we are being passed a key/function object or an array of functions if (def instanceof Array) { // We were passed an array of functions count = def.length; for (index = 0; index < count; index++) { if (def[index].length === arguments.length) { return self.callExtend(this, '$main', def, def[index], arguments); } } } else { // Generate lookup key from arguments // Copy arguments to an array for (index = 0; index < arguments.length; index++) { type = typeof arguments[index]; // Handle detecting arrays if (type === 'object' && arguments[index] instanceof Array) { type = 'array'; } // Handle been presented with a single undefined argument if (arguments.length === 1 && type === 'undefined') { break; } // Add the type to the argument types array arr.push(type); } lookup = arr.join(','); // Check for an exact lookup match if (def[lookup]) { return self.callExtend(this, '$main', def, def[lookup], arguments); } else { for (index = arr.length; index >= 0; index--) { // Get the closest match lookup = arr.slice(0, index).join(','); if (def[lookup + ',...']) { // Matched against arguments + "any other" return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments); } } } } name = typeof this.name === 'function' ? this.name() : 'Unknown'; console.log('Overload: ', def); throw('ForerunnerDB.Overload "' + name + '": Overloaded method does not have a matching signature for the passed arguments: ' + this.jStringify(arr)); }; } return function () {}; }; /** * Generates an array of all the different definition signatures that can be * created from the passed string with a catch-all wildcard *. E.g. it will * convert the signature: string,*,string to all potentials: * string,string,string * string,number,string * string,object,string, * string,function,string, * string,undefined,string * * @param {String} str Signature string with a wildcard in it. * @returns {Array} An array of signature strings that are generated. */ Overload.prototype.generateSignaturePermutations = function (str) { var signatures = [], newSignature, types = ['string', 'object', 'number', 'function', 'undefined'], index; if (str.indexOf('*') > -1) { // There is at least one "any" type, break out into multiple keys // We could do this at query time with regular expressions but // would be significantly slower for (index = 0; index < types.length; index++) { newSignature = str.replace('*', types[index]); signatures = signatures.concat(this.generateSignaturePermutations(newSignature)); } } else { signatures.push(str); } return signatures; }; Overload.prototype.callExtend = function (context, prop, propContext, func, args) { var tmp, ret; if (context && propContext[prop]) { tmp = context[prop]; context[prop] = propContext[prop]; ret = func.apply(context, args); context[prop] = tmp; return ret; } else { return func.apply(context, args); } }; module.exports = Overload; },{}],23:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Path object used to resolve object paths and retrieve data from * objects by using paths. * @param {String=} path The path to assign. * @constructor */ var Path = function (path) { this.init.apply(this, arguments); }; Path.prototype.init = function (path) { if (path) { this.path(path); } }; Shared.addModule('Path', Path); Shared.mixin(Path.prototype, 'Mixin.Common'); Shared.mixin(Path.prototype, 'Mixin.ChainReactor'); /** * Gets / sets the given path for the Path instance. * @param {String=} path The path to assign. */ Path.prototype.path = function (path) { if (path !== undefined) { this._path = this.clean(path); this._pathParts = this._path.split('.'); return this; } return this._path; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Boolean} True if the object paths exist. */ Path.prototype.hasObjectPaths = function (testKeys, testObj) { var result = true, i; for (i in testKeys) { if (testKeys.hasOwnProperty(i)) { if (testObj[i] === undefined) { return false; } if (typeof testKeys[i] === 'object') { // Recurse object result = this.hasObjectPaths(testKeys[i], testObj[i]); // Should we exit early? if (!result) { return false; } } } } return result; }; /** * Counts the total number of key endpoints in the passed object. * @param {Object} testObj The object to count key endpoints for. * @returns {Number} The number of endpoints. */ Path.prototype.countKeys = function (testObj) { var totalKeys = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (testObj[i] !== undefined) { if (typeof testObj[i] !== 'object') { totalKeys++; } else { totalKeys += this.countKeys(testObj[i]); } } } } return totalKeys; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths and if so returns the number matched. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Object} Stats on the matched keys */ Path.prototype.countObjectPaths = function (testKeys, testObj) { var matchData, matchedKeys = {}, matchedKeyCount = 0, totalKeyCount = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (typeof testObj[i] === 'object') { // The test / query object key is an object, recurse matchData = this.countObjectPaths(testKeys[i], testObj[i]); matchedKeys[i] = matchData.matchedKeys; totalKeyCount += matchData.totalKeyCount; matchedKeyCount += matchData.matchedKeyCount; } else { // The test / query object has a property that is not an object so add it as a key totalKeyCount++; // Check if the test keys also have this key and it is also not an object if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') { matchedKeys[i] = true; matchedKeyCount++; } else { matchedKeys[i] = false; } } } } return { matchedKeys: matchedKeys, matchedKeyCount: matchedKeyCount, totalKeyCount: totalKeyCount }; }; /** * Takes a non-recursive object and converts the object hierarchy into * a path string. * @param {Object} obj The object to parse. * @param {Boolean=} withValue If true will include a 'value' key in the returned * object that represents the value the object path points to. * @returns {Object} */ Path.prototype.parse = function (obj, withValue) { var paths = [], path = '', resultData, i, k; for (i in obj) { if (obj.hasOwnProperty(i)) { // Set the path to the key path = i; if (typeof(obj[i]) === 'object') { if (withValue) { resultData = this.parse(obj[i], withValue); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path, value: resultData[k].value }); } } else { resultData = this.parse(obj[i]); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path }); } } } else { if (withValue) { paths.push({ path: path, value: obj[i] }); } else { paths.push({ path: path }); } } } } return paths; }; /** * Takes a non-recursive object and converts the object hierarchy into * an array of path strings that allow you to target all possible paths * in an object. * * The options object accepts an "ignore" field with a regular expression * as the value. If any key matches the expression it is not included in * the results. * * The options object accepts a boolean "verbose" field. If set to true * the results will include all paths leading up to endpoints as well as * they endpoints themselves. * * @returns {Array} */ Path.prototype.parseArr = function (obj, options) { options = options || {}; return this._parseArr(obj, '', [], options); }; Path.prototype._parseArr = function (obj, path, paths, options) { var i, newPath = ''; path = path || ''; paths = paths || []; for (i in obj) { if (obj.hasOwnProperty(i)) { if (!options.ignore || (options.ignore && !options.ignore.test(i))) { if (path) { newPath = path + '.' + i; } else { newPath = i; } if (typeof(obj[i]) === 'object') { if (options.verbose) { paths.push(newPath); } this._parseArr(obj[i], newPath, paths, options); } else { paths.push(newPath); } } } } return paths; }; Path.prototype.valueOne = function (obj, path) { return this.value(obj, path)[0]; }; /** * Gets the value(s) that the object contains for the currently assigned path string. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @param {Object=} options An optional options object. * @returns {Array} An array of values for the given path. */ Path.prototype.value = function (obj, path, options) { var pathParts, arr, arrCount, objPart, objPartParent, valuesArr, returnArr, i, k; if (obj !== undefined && typeof obj === 'object') { if (!options || options && !options.skipArrCheck) { // Check if we were passed an array of objects and if so, // iterate over the array and return the value from each // array item if (obj instanceof Array) { returnArr = []; for (i = 0; i < obj.length; i++) { returnArr.push(this.valueOne(obj[i], path)); } return returnArr; } } valuesArr = []; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (objPartParent instanceof Array) { // Search inside the array for the next key for (k = 0; k < objPartParent.length; k++) { valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i], {skipArrCheck: true})); } return valuesArr; } else { if (!objPart || typeof(objPart) !== 'object') { break; } } objPartParent = objPart; } return [objPart]; } else { return []; } }; /** * Sets a value on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to update. * @param {*} val The value to set the object path to. * @returns {*} */ Path.prototype.set = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = val; } } return obj; }; Path.prototype.get = function (obj, path) { return this.value(obj, path)[0]; }; /** * Push a value to an array on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to the array to push to. * @param {*} val The value to push to the array at the object path. * @returns {*} */ Path.prototype.push = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = obj[part] || []; if (obj[part] instanceof Array) { obj[part].push(val); } else { throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!'); } } } return obj; }; /** * Gets the value(s) that the object contains for the currently assigned path string * with their associated keys. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @returns {Array} An array of values for the given path with the associated key. */ Path.prototype.keyValue = function (obj, path) { var pathParts, arr, arrCount, objPart, objPartParent, objPartHash, i; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (!objPart || typeof(objPart) !== 'object') { objPartHash = arr[i] + ':' + objPart; break; } objPartParent = objPart; } return objPartHash; }; /** * Sets a value on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to update. * @param {*} val The value to set the object path to. * @returns {*} */ Path.prototype.set = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = val; } } return obj; }; /** * Removes leading period (.) from string and returns it. * @param {String} str The string to clean. * @returns {*} */ Path.prototype.clean = function (str) { if (str.substr(0, 1) === '.') { str = str.substr(1, str.length -1); } return str; }; Shared.finishModule('Path'); module.exports = Path; },{"./Shared":26}],24:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Provides chain reactor node linking so that a chain reaction can propagate * down a node tree. Effectively creates a chain link between the reactorIn and * reactorOut objects where a chain reaction from the reactorIn is passed through * the reactorProcess before being passed to the reactorOut object. Reactor * packets are only passed through to the reactorOut if the reactor IO method * chainSend is used. * @param {*} reactorIn An object that has the Mixin.ChainReactor methods mixed * in to it. Chain reactions that occur inside this object will be passed through * to the reactorOut object. * @param {*} reactorOut An object that has the Mixin.ChainReactor methods mixed * in to it. Chain reactions that occur in the reactorIn object will be passed * through to this object. * @param {Function} reactorProcess The processing method to use when chain * reactions occur. * @constructor */ var ReactorIO = function (reactorIn, reactorOut, reactorProcess) { if (reactorIn && reactorOut && reactorProcess) { this._reactorIn = reactorIn; this._reactorOut = reactorOut; this._chainHandler = reactorProcess; if (!reactorIn.chain || !reactorOut.chainReceive) { throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!'); } // Register the reactorIO with the input reactorIn.chain(this); // Register the output with the reactorIO this.chain(reactorOut); } else { throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!'); } }; Shared.addModule('ReactorIO', ReactorIO); /** * Drop a reactor IO object, breaking the reactor link between the in and out * reactor nodes. * @returns {boolean} */ ReactorIO.prototype.drop = function () { if (!this.isDropped()) { this._state = 'dropped'; // Remove links if (this._reactorIn) { this._reactorIn.unChain(this); } if (this._reactorOut) { this.unChain(this._reactorOut); } delete this._reactorIn; delete this._reactorOut; delete this._chainHandler; this.emit('drop', this); delete this._listeners; } return true; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(ReactorIO.prototype, 'state'); Shared.mixin(ReactorIO.prototype, 'Mixin.Common'); Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor'); Shared.mixin(ReactorIO.prototype, 'Mixin.Events'); Shared.finishModule('ReactorIO'); module.exports = ReactorIO; },{"./Shared":26}],25:[function(_dereq_,module,exports){ "use strict"; /** * Provides functionality to encode and decode JavaScript objects to strings * and back again. This differs from JSON.stringify and JSON.parse in that * special objects such as dates can be encoded to strings and back again * so that the reconstituted version of the string still contains a JavaScript * date object. * @constructor */ var Serialiser = function () { this.init.apply(this, arguments); }; Serialiser.prototype.init = function () { this._encoder = []; this._decoder = {}; // Register our handlers this.registerEncoder('$date', function (data) { if (data instanceof Date) { return data.toISOString(); } }); this.registerDecoder('$date', function (data) { return new Date(data); }); }; /** * Register an encoder that can handle encoding for a particular * object type. * @param {String} handles The name of the handler e.g. $date. * @param {Function} method The encoder method. */ Serialiser.prototype.registerEncoder = function (handles, method) { this._encoder.push(function (data) { var methodVal = method(data), returnObj; if (methodVal !== undefined) { returnObj = {}; returnObj[handles] = methodVal; } return returnObj; }); }; /** * Register a decoder that can handle decoding for a particular * object type. * @param {String} handles The name of the handler e.g. $date. When an object * has a field matching this handler name then this decode will be invoked * to provide a decoded version of the data that was previously encoded by * it's counterpart encoder method. * @param {Function} method The decoder method. */ Serialiser.prototype.registerDecoder = function (handles, method) { this._decoder[handles] = method; }; /** * Loops the encoders and asks each one if it wants to handle encoding for * the passed data object. If no value is returned (undefined) then the data * will be passed to the next encoder and so on. If a value is returned the * loop will break and the encoded data will be used. * @param {Object} data The data object to handle. * @returns {*} The encoded data. * @private */ Serialiser.prototype._encode = function (data) { // Loop the encoders and if a return value is given by an encoder // the loop will exit and return that value. var count = this._encoder.length, retVal; while (count-- && !retVal) { retVal = this._encoder[count](data); } return retVal; }; /** * Converts a previously encoded string back into an object. * @param {String} data The string to convert to an object. * @returns {Object} The reconstituted object. */ Serialiser.prototype.parse = function (data) { return this._parse(JSON.parse(data)); }; /** * Handles restoring an object with special data markers back into * it's original format. * @param {Object} data The object to recurse. * @param {Object=} target The target object to restore data to. * @returns {Object} The final restored object. * @private */ Serialiser.prototype._parse = function (data, target) { var i; if (typeof data === 'object' && data !== null) { if (data instanceof Array) { target = target || []; } else { target = target || {}; } // Iterate through the object's keys and handle // special object types and restore them for (i in data) { if (data.hasOwnProperty(i)) { if (i.substr(0, 1) === '$' && this._decoder[i]) { // This is a special object type and a handler // exists, restore it return this._decoder[i](data[i]); } // Not a special object or no handler, recurse as normal target[i] = this._parse(data[i], target[i]); } } } else { target = data; } // The data is a basic type return target; }; /** * Converts an object to a encoded string representation. * @param {Object} data The object to encode. */ Serialiser.prototype.stringify = function (data) { return JSON.stringify(this._stringify(data)); }; /** * Recurse down an object and encode special objects so they can be * stringified and later restored. * @param {Object} data The object to parse. * @param {Object=} target The target object to store converted data to. * @returns {Object} The converted object. * @private */ Serialiser.prototype._stringify = function (data, target) { var handledData, i; if (typeof data === 'object' && data !== null) { // Handle special object types so they can be encoded with // a special marker and later restored by a decoder counterpart handledData = this._encode(data); if (handledData) { // An encoder handled this object type so return it now return handledData; } if (data instanceof Array) { target = target || []; } else { target = target || {}; } // Iterate through the object's keys and serialise for (i in data) { if (data.hasOwnProperty(i)) { target[i] = this._stringify(data[i], target[i]); } } } else { target = data; } // The data is a basic type return target; }; module.exports = Serialiser; },{}],26:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * A shared object that can be used to store arbitrary data between class * instances, and access helper methods. * @mixin */ var Shared = { version: '1.3.505', modules: {}, plugins: {}, _synth: {}, /** * Adds a module to ForerunnerDB. * @memberof Shared * @param {String} name The name of the module. * @param {Function} module The module class. */ addModule: function (name, module) { // Store the module in the module registry this.modules[name] = module; // Tell the universe we are loading this module this.emit('moduleLoad', [name, module]); }, /** * Called by the module once all processing has been completed. Used to determine * if the module is ready for use by other modules. * @memberof Shared * @param {String} name The name of the module. */ finishModule: function (name) { if (this.modules[name]) { // Set the finished loading flag to true this.modules[name]._fdbFinished = true; // Assign the module name to itself so it knows what it // is called if (this.modules[name].prototype) { this.modules[name].prototype.className = name; } else { this.modules[name].className = name; } this.emit('moduleFinished', [name, this.modules[name]]); } else { throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name); } }, /** * Will call your callback method when the specified module has loaded. If the module * is already loaded the callback is called immediately. * @memberof Shared * @param {String} name The name of the module. * @param {Function} callback The callback method to call when the module is loaded. */ moduleFinished: function (name, callback) { if (this.modules[name] && this.modules[name]._fdbFinished) { if (callback) { callback(name, this.modules[name]); } } else { this.on('moduleFinished', callback); } }, /** * Determines if a module has been added to ForerunnerDB or not. * @memberof Shared * @param {String} name The name of the module. * @returns {Boolean} True if the module exists or false if not. */ moduleExists: function (name) { return Boolean(this.modules[name]); }, /** * Adds the properties and methods defined in the mixin to the passed object. * @memberof Shared * @param {Object} obj The target object to add mixin key/values to. * @param {String} mixinName The name of the mixin to add to the object. */ mixin: new Overload({ 'object, string': function (obj, mixinName) { var mixinObj; if (typeof mixinName === 'string') { mixinObj = this.mixins[mixinName]; if (!mixinObj) { throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName); } } return this.$main.call(this, obj, mixinObj); }, 'object, *': function (obj, mixinObj) { return this.$main.call(this, obj, mixinObj); }, '$main': function (obj, mixinObj) { if (mixinObj && typeof mixinObj === 'object') { for (var i in mixinObj) { if (mixinObj.hasOwnProperty(i)) { obj[i] = mixinObj[i]; } } } return obj; } }), /** * Generates a generic getter/setter method for the passed method name. * @memberof Shared * @param {Object} obj The object to add the getter/setter to. * @param {String} name The name of the getter/setter to generate. * @param {Function=} extend A method to call before executing the getter/setter. * The existing getter/setter can be accessed from the extend method via the * $super e.g. this.$super(); */ synthesize: function (obj, name, extend) { this._synth[name] = this._synth[name] || function (val) { if (val !== undefined) { this['_' + name] = val; return this; } return this['_' + name]; }; if (extend) { var self = this; obj[name] = function () { var tmp = this.$super, ret; this.$super = self._synth[name]; ret = extend.apply(this, arguments); this.$super = tmp; return ret; }; } else { obj[name] = this._synth[name]; } }, /** * Allows a method to be overloaded. * @memberof Shared * @param arr * @returns {Function} * @constructor */ overload: Overload, /** * Define the mixins that other modules can use as required. * @memberof Shared */ mixins: { 'Mixin.Common': _dereq_('./Mixin.Common'), 'Mixin.Events': _dereq_('./Mixin.Events'), 'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'), 'Mixin.CRUD': _dereq_('./Mixin.CRUD'), 'Mixin.Constants': _dereq_('./Mixin.Constants'), 'Mixin.Triggers': _dereq_('./Mixin.Triggers'), 'Mixin.Sorting': _dereq_('./Mixin.Sorting'), 'Mixin.Matching': _dereq_('./Mixin.Matching'), 'Mixin.Updating': _dereq_('./Mixin.Updating'), 'Mixin.Tags': _dereq_('./Mixin.Tags') } }; // Add event handling to shared Shared.mixin(Shared, 'Mixin.Events'); module.exports = Shared; },{"./Mixin.CRUD":11,"./Mixin.ChainReactor":12,"./Mixin.Common":13,"./Mixin.Constants":14,"./Mixin.Events":15,"./Mixin.Matching":16,"./Mixin.Sorting":17,"./Mixin.Tags":18,"./Mixin.Triggers":19,"./Mixin.Updating":20,"./Overload":22}],27:[function(_dereq_,module,exports){ /* jshint strict:false */ if (!Array.prototype.filter) { Array.prototype.filter = function(fun/*, thisArg*/) { if (this === void 0 || this === null) { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; // jshint ignore:line if (typeof fun !== 'function') { throw new TypeError(); } var res = []; var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++) { if (i in t) { var val = t[i]; // NOTE: Technically this should Object.defineProperty at // the next index, as push can be affected by // properties on Object.prototype and Array.prototype. // But that method's new, and collisions should be // rare, so use the more-compatible alternative. if (fun.call(thisArg, val, i, t)) { res.push(val); } } } return res; }; } if (typeof Object.create !== 'function') { Object.create = (function() { var Temp = function() {}; return function (prototype) { if (arguments.length > 1) { throw Error('Second argument not supported'); } if (typeof prototype !== 'object') { throw TypeError('Argument must be an object'); } Temp.prototype = prototype; var result = new Temp(); Temp.prototype = null; return result; }; })(); } // Production steps of ECMA-262, Edition 5, 15.4.4.14 // Reference: http://es5.github.io/#x15.4.4.14e if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(searchElement, fromIndex) { var k; // 1. Let O be the result of calling ToObject passing // the this value as the argument. if (this === null) { throw new TypeError('"this" is null or not defined'); } var O = Object(this); // 2. Let lenValue be the result of calling the Get // internal method of O with the argument "length". // 3. Let len be ToUint32(lenValue). var len = O.length >>> 0; // jshint ignore:line // 4. If len is 0, return -1. if (len === 0) { return -1; } // 5. If argument fromIndex was passed let n be // ToInteger(fromIndex); else let n be 0. var n = +fromIndex || 0; if (Math.abs(n) === Infinity) { n = 0; } // 6. If n >= len, return -1. if (n >= len) { return -1; } // 7. If n >= 0, then Let k be n. // 8. Else, n<0, Let k be len - abs(n). // If k is less than 0, then let k be 0. k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); // 9. Repeat, while k < len while (k < len) { // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the // HasProperty internal method of O with argument Pk. // This step can be combined with c // c. If kPresent is true, then // i. Let elementK be the result of calling the Get // internal method of O with the argument ToString(k). // ii. Let same be the result of applying the // Strict Equality Comparison Algorithm to // searchElement and elementK. // iii. If same is true, return k. if (k in O && O[k] === searchElement) { return k; } k++; } return -1; }; } module.exports = {}; },{}]},{},[1]);
AMoo-Miki/cdnjs
ajax/libs/forerunnerdb/1.3.505/fdb-core.js
JavaScript
mit
240,356
<?php /** * Minileven functions and definitions * * Sets up the theme and provides some helper functions. Some helper functions * are used in the theme as custom template tags. Others are attached to action and * filter hooks in WordPress to change core functionality. * * The first function, minileven_setup(), sets up the theme by registering support * for various features in WordPress, such as post thumbnails, navigation menus, and the like. * * @package Minileven */ /** * Set the content width based on the theme's design and stylesheet. */ if ( ! isset( $content_width ) ) $content_width = 584; /** * Tell WordPress to run minileven_setup() when the 'after_setup_theme' hook is run. */ add_action( 'after_setup_theme', 'minileven_setup' ); if ( ! function_exists( 'minileven_setup' ) ): /** * Sets up theme defaults and registers support for various WordPress features. */ function minileven_setup() { global $wp_version; /** * Custom template tags for this theme. */ require( get_template_directory() . '/inc/template-tags.php' ); /** * Custom functions that act independently of the theme templates */ require( get_template_directory() . '/inc/tweaks.php' ); /** * Implement the Custom Header functions */ require( get_template_directory() . '/inc/custom-header.php' ); /* Make Minileven available for translation. * Translations can be added to the /languages/ directory. * If you're building a theme based on Minileven, use a find and replace * to change 'minileven' to the name of your theme in all the template files. */ /* Don't load a minileven textdomain, as it uses the Jetpack textdomain. load_theme_textdomain( 'minileven', get_template_directory() . '/languages' ); */ // Add default posts and comments RSS feed links to <head>. add_theme_support( 'automatic-feed-links' ); // This theme uses wp_nav_menu() in one location. register_nav_menu( 'primary', __( 'Primary Menu', 'jetpack' ) ); // Add support for a variety of post formats add_theme_support( 'post-formats', array( 'gallery' ) ); // Add support for custom backgrounds add_theme_support( 'custom-background' ); // Add support for post thumbnails add_theme_support( 'post-thumbnails' ); } endif; // minileven_setup /** * Enqueue scripts and styles */ function minileven_scripts() { global $post; wp_enqueue_style( 'style', get_stylesheet_uri() ); wp_enqueue_script( 'small-menu', get_template_directory_uri() . '/js/small-menu.js', array( 'jquery' ), '20120206', true ); if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) { wp_enqueue_script( 'comment-reply' ); } } add_action( 'wp_enqueue_scripts', 'minileven_scripts' ); function minileven_fonts() { /* translators: If there are characters in your language that are not supported by Open Sans, translate this to 'off'. Do not translate into your own language. */ if ( 'off' !== _x( 'on', 'Open Sans font: on or off', 'jetpack' ) ) { $opensans_subsets = 'latin,latin-ext'; /* translators: To add an additional Open Sans character subset specific to your language, translate this to 'greek', 'cyrillic' or 'vietnamese'. Do not translate into your own language. */ $opensans_subset = _x( 'no-subset', 'Open Sans font: add new subset (greek, cyrillic, vietnamese)', 'jetpack' ); if ( 'cyrillic' == $opensans_subset ) $opensans_subsets .= ',cyrillic,cyrillic-ext'; elseif ( 'greek' == $opensans_subset ) $opensans_subsets .= ',greek,greek-ext'; elseif ( 'vietnamese' == $opensans_subset ) $opensans_subsets .= ',vietnamese'; $opensans_query_args = array( 'family' => 'Open+Sans:200,200italic,300,300italic,400,400italic,600,600italic,700,700italic', 'subset' => $opensans_subsets, ); wp_register_style( 'minileven-open-sans', add_query_arg( $opensans_query_args, "//fonts.googleapis.com/css" ), array(), null ); } } add_action( 'init', 'minileven_fonts' ); /** * Register our sidebars and widgetized areas. * @since Minileven 1.0 */ function minileven_widgets_init() { register_sidebar( array( 'name' => __( 'Main Sidebar', 'jetpack' ), 'id' => 'sidebar-1', 'before_widget' => '<aside id="%1$s" class="widget %2$s">', 'after_widget' => "</aside>", 'before_title' => '<h3 class="widget-title">', 'after_title' => '</h3>', ) ); } add_action( 'widgets_init', 'minileven_widgets_init' ); function minileven_posts_per_page() { return 5; } add_filter('pre_option_posts_per_page', 'minileven_posts_per_page'); /** * Determine the currently active theme. */ function minileven_actual_current_theme() { $removed = remove_action( 'option_stylesheet', 'jetpack_mobile_stylesheet' ); $stylesheet = get_option( 'stylesheet' ); if ( $removed ) add_action( 'option_stylesheet', 'jetpack_mobile_stylesheet' ); return $stylesheet; } /* This function grabs the location of the custom menus from the current theme. If no menu is set in a location * it will return a boolean "false". This function helps Minileven know which custom menu to display. */ function minileven_get_menu_location() { $theme_slug = minileven_actual_current_theme(); $mods = get_option( "theme_mods_{$theme_slug}" ); if ( has_filter( 'jetpack_mobile_theme_menu' ) ) { /** * Filter the menu displayed in the Mobile Theme. * * @since 3.4.0 * * @param int $menu_id ID of the menu to display. */ return array( 'primary' => apply_filters( 'jetpack_mobile_theme_menu', $menu_id ) ); } if ( isset( $mods['nav_menu_locations'] ) && ! empty( $mods['nav_menu_locations'] ) ) return $mods['nav_menu_locations']; return false; } /* This function grabs the custom background image from the user's current theme so that Minileven can display it. */ function minileven_get_background() { $theme_slug = minileven_actual_current_theme(); $mods = get_option( "theme_mods_$theme_slug" ); if ( ! empty( $mods ) ) { return array( 'color' => isset( $mods['background_color'] ) ? $mods['background_color'] : null, 'image' => isset( $mods['background_image'] ) ? $mods['background_image'] : null, 'repeat' => isset( $mods['background_repeat'] ) ? $mods['background_repeat'] : null, 'position' => isset( $mods['background_position_x'] ) ? $mods['background_position_x'] : null, 'attachment' => isset( $mods['attachment'] ) ? $mods['attachment'] : null, ); } return false; } /** * If the user has set a static front page, show all posts on the front page, instead of a static page. */ if ( '1' == get_option( 'wp_mobile_static_front_page' ) ) add_filter( 'pre_option_page_on_front', '__return_zero' ); /** * Retrieves the IDs for images in a gallery. * * @uses get_post_galleries() first, if available. Falls back to shortcode parsing, * then as last option uses a get_posts() call. * * @return array List of image IDs from the post gallery. */ function minileven_get_gallery_images() { $images = array(); if ( function_exists( 'get_post_galleries' ) ) { $galleries = get_post_galleries( get_the_ID(), false ); if ( isset( $galleries[0]['ids'] ) ) $images = explode( ',', $galleries[0]['ids'] ); } else { $pattern = get_shortcode_regex(); preg_match( "/$pattern/s", get_the_content(), $match ); $atts = shortcode_parse_atts( $match[3] ); if ( isset( $atts['ids'] ) ) $images = explode( ',', $atts['ids'] ); } if ( ! $images ) { $images = get_posts( array( 'fields' => 'ids', 'numberposts' => 999, 'order' => 'ASC', 'orderby' => 'menu_order', 'post_mime_type' => 'image', 'post_parent' => get_the_ID(), 'post_type' => 'attachment', ) ); } return $images; } /** * Allow plugins to filter where Featured Images are displayed. * Default has Featured Images disabled on single view and pages. * * @uses is_search() * @uses apply_filters() * @return bool */ function minileven_show_featured_images() { $enabled = ( is_home() || is_search() || is_archive() ) ? true : false; /** * Filter where featured images are displayed in the Mobile Theme. * * By setting $enabled to true or false using functions like is_home() or * is_archive(), you can control where featured images are be displayed. * * @since 3.2.0 * * @param bool $enabled True if featured images should be displayed, false if not. */ return (bool) apply_filters( 'minileven_show_featured_images', $enabled ); }
riddya85/rentail_upwrk
wp-content/plugins/jetpack/modules/minileven/theme/pub/minileven/functions.php
PHP
gpl-2.0
8,400
<?php /** * @package Joomla.Site * @subpackage com_newsfeeds * * @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; /** * HTML View class for the Newsfeeds component * * @package Joomla.Site * @subpackage com_newsfeeds * @since 1.0 */ class NewsfeedsViewNewsfeed extends JViewLegacy { /** * @var object * @since 1.6 */ protected $state; /** * @var object * @since 1.6 */ protected $item; /** * @var boolean * @since 1.6 */ protected $print; /** * @since 1.6 */ public function display($tpl = null) { $app = JFactory::getApplication(); $user = JFactory::getUser(); // Get view related request variables. $print = $app->input->getBool('print'); // Get model data. $state = $this->get('State'); $item = $this->get('Item'); if ($item) { // Get Category Model data $categoryModel = JModelLegacy::getInstance('Category', 'NewsfeedsModel', array('ignore_request' => true)); $categoryModel->setState('category.id', $item->catid); $categoryModel->setState('list.ordering', 'a.name'); $categoryModel->setState('list.direction', 'asc'); // TODO: $items is not used. Remove this line? $items = $categoryModel->getItems(); } // Check for errors. // @TODO Maybe this could go into JComponentHelper::raiseErrors($this->get('Errors')) if (count($errors = $this->get('Errors'))) { JError::raiseWarning(500, implode("\n", $errors)); return false; } // Add router helpers. $item->slug = $item->alias ? ($item->id . ':' . $item->alias) : $item->id; $item->catslug = $item->category_alias ? ($item->catid . ':' . $item->category_alias) : $item->catid; $item->parent_slug = $item->category_alias ? ($item->parent_id . ':' . $item->parent_alias) : $item->parent_id; // check if cache directory is writeable $cacheDir = JPATH_CACHE . '/'; if (!is_writable($cacheDir)) { JError::raiseNotice('0', JText::_('COM_NEWSFEEDS_CACHE_DIRECTORY_UNWRITABLE')); return; } // Merge newsfeed params. If this is single-newsfeed view, menu params override newsfeed params // Otherwise, newsfeed params override menu item params $params = $state->get('params'); $newsfeed_params = clone $item->params; $active = $app->getMenu()->getActive(); $temp = clone ($params); // Check to see which parameters should take priority if ($active) { $currentLink = $active->link; // If the current view is the active item and an newsfeed view for this feed, then the menu item params take priority if (strpos($currentLink, 'view=newsfeed') && (strpos($currentLink, '&id='.(string) $item->id))) { // $item->params are the newsfeed params, $temp are the menu item params // Merge so that the menu item params take priority $newsfeed_params->merge($temp); $item->params = $newsfeed_params; // Load layout from active query (in case it is an alternative menu item) if (isset($active->query['layout'])) { $this->setLayout($active->query['layout']); } } else { // Current view is not a single newsfeed, so the newsfeed params take priority here // Merge the menu item params with the newsfeed params so that the newsfeed params take priority $temp->merge($newsfeed_params); $item->params = $temp; // Check for alternative layouts (since we are not in a single-newsfeed menu item) if ($layout = $item->params->get('newsfeed_layout')) { $this->setLayout($layout); } } } else { // Merge so that newsfeed params take priority $temp->merge($newsfeed_params); $item->params = $temp; // Check for alternative layouts (since we are not in a single-newsfeed menu item) if ($layout = $item->params->get('newsfeed_layout')) { $this->setLayout($layout); } } // Check the access to the newsfeed $levels = $user->getAuthorisedViewLevels(); if (!in_array($item->access, $levels) or ((in_array($item->access, $levels) and (!in_array($item->category_access, $levels))))) { JError::raiseWarning(403, JText::_('JERROR_ALERTNOAUTHOR')); return; } // Get the current menu item $params = $app->getParams(); // Get the newsfeed $newsfeed = $item; $temp = new JRegistry; $temp->loadString($item->params); $params->merge($temp); try { $feed = new JFeedFactory; $this->rssDoc = $feed->getFeed($newsfeed->link); } catch (InvalidArgumentException $e) { $msg = JText::_('COM_NEWSFEEDS_ERRORS_FEED_NOT_RETRIEVED'); } catch (RunTimeException $e) { $msg = JText::_('COM_NEWSFEEDS_ERRORS_FEED_NOT_RETRIEVED'); } if (empty($this->rssDoc)) { $msg = JText::_('COM_NEWSFEEDS_ERRORS_FEED_NOT_RETRIEVED'); } $feed_display_order = $params->get('feed_display_order', 'des'); if ($feed_display_order == 'asc') { $newsfeed->items = array_reverse($newsfeed->items); } //Escape strings for HTML output $this->pageclass_sfx = htmlspecialchars($params->get('pageclass_sfx')); $this->assignRef('params', $params); $this->assignRef('newsfeed', $newsfeed); $this->assignRef('state', $state); $this->assignRef('item', $item); $this->assignRef('user', $user); if (!empty($msg)) { $this->assignRef('msg', $msg); } $this->print = $print; $item->tags = new JHelperTags; $item->tags->getItemTags('com_newsfeeds.newsfeed', $item->id); $this->_prepareDocument(); parent::display($tpl); } /** * Prepares the document * * @return void * @since 1.6 */ protected function _prepareDocument() { $app = JFactory::getApplication(); $menus = $app->getMenu(); $pathway = $app->getPathway(); $title = null; // Because the application sets a default page title, // we need to get it from the menu item itself $menu = $menus->getActive(); if ($menu) { $this->params->def('page_heading', $this->params->get('page_title', $menu->title)); } else { $this->params->def('page_heading', JText::_('COM_NEWSFEEDS_DEFAULT_PAGE_TITLE')); } $title = $this->params->get('page_title', ''); $id = (int) @$menu->query['id']; // if the menu item does not concern this newsfeed if ($menu && ($menu->query['option'] != 'com_newsfeeds' || $menu->query['view'] != 'newsfeed' || $id != $this->item->id)) { // If this is not a single newsfeed menu item, set the page title to the newsfeed title if ($this->item->name) { $title = $this->item->name; } $path = array(array('title' => $this->item->name, 'link' => '')); $category = JCategories::getInstance('Newsfeeds')->get($this->item->catid); while (($menu->query['option'] != 'com_newsfeeds' || $menu->query['view'] == 'newsfeed' || $id != $category->id) && $category->id > 1) { $path[] = array('title' => $category->title, 'link' => NewsfeedsHelperRoute::getCategoryRoute($category->id)); $category = $category->getParent(); } $path = array_reverse($path); foreach ($path as $item) { $pathway->addItem($item['title'], $item['link']); } } if (empty($title)) { $title = $app->getCfg('sitename'); } elseif ($app->getCfg('sitename_pagetitles', 0) == 1) { $title = JText::sprintf('JPAGETITLE', $app->getCfg('sitename'), $title); } elseif ($app->getCfg('sitename_pagetitles', 0) == 2) { $title = JText::sprintf('JPAGETITLE', $title, $app->getCfg('sitename')); } if (empty($title)) { $title = $this->item->name; } $this->document->setTitle($title); if ($this->item->metadesc) { $this->document->setDescription($this->item->metadesc); } elseif (!$this->item->metadesc && $this->params->get('menu-meta_description')) { $this->document->setDescription($this->params->get('menu-meta_description')); } if ($this->item->metakey) { $this->document->setMetadata('keywords', $this->item->metakey); } elseif (!$this->item->metakey && $this->params->get('menu-meta_keywords')) { $this->document->setMetadata('keywords', $this->params->get('menu-meta_keywords')); } if ($this->params->get('robots')) { $this->document->setMetadata('robots', $this->params->get('robots')); } if ($app->getCfg('MetaTitle') == '1') { $this->document->setMetaData('title', $this->item->name); } if ($app->getCfg('MetaAuthor') == '1') { $this->document->setMetaData('author', $this->item->author); } $mdata = $this->item->metadata->toArray(); foreach ($mdata as $k => $v) { if ($v) { $this->document->setMetadata($k, $v); } } } }
RCBiczok/ArticleRefs
src/test/lib/joomla/3_1_5/components/com_newsfeeds/views/newsfeed/view.html.php
PHP
gpl-3.0
8,625
/********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2003, 2004, 2005, 2006, 2008 The Sakai Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ package org.sakaiproject.message.api; import java.util.Collection; import java.util.Stack; import org.sakaiproject.entity.api.AttachmentContainer; import org.sakaiproject.site.api.Group; import org.sakaiproject.time.api.Time; import org.sakaiproject.user.api.User; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * <p> * MessageHeader is the base Interface for a Sakai Message headers. Header fields common to all message service message headers are defined here. * </p> */ public interface MessageHeader extends AttachmentContainer { /** * <p> * MessageAccess enumerates different access modes for the message: channel-wide or grouped. * </p> */ public class MessageAccess { private final String m_id; private MessageAccess(String id) { m_id = id; } public String toString() { return m_id; } static public MessageAccess fromString(String access) { // if (PUBLIC.m_id.equals(access)) return PUBLIC; if (CHANNEL.m_id.equals(access)) return CHANNEL; if (GROUPED.m_id.equals(access)) return GROUPED; return null; } /** public access to the message: pubview */ // public static final MessageAccess PUBLIC = new MessageAccess("public"); /** channel (site) level access to the message */ public static final MessageAccess CHANNEL = new MessageAccess("channel"); /** grouped access; only members of the getGroup() groups (authorization groups) have access */ public static final MessageAccess GROUPED = new MessageAccess("grouped"); } /** * Access the unique (within the channel) message id. * * @return The unique (within the channel) message id. */ String getId(); /** * Access the date/time the message was sent to the channel. * * @return The date/time the message was sent to the channel. */ Time getDate(); /** * Access the message order of the message was sent to the channel. * * @return The message order of the message was sent to the channel. */ Integer getMessage_order(); /** * Access the User who sent the message to the channel. * * @return The User who sent the message to the channel. */ User getFrom(); /** * Access the draft status of the message. * * @return True if the message is a draft, false if not. */ boolean getDraft(); /** * Access the groups defined for this message. * * @return A Collection (String) of group refs (authorization group ids) defined for this message; empty if none are defined. */ Collection<String> getGroups(); /** * Access the groups, as Group objects, defined for this message. * * @return A Collection (Group) of group objects defined for this message; empty if none are defined. */ Collection<Group> getGroupObjects(); /** * Access the access mode for the message - how we compute who has access to the message. * * @return The MessageAccess access mode for the message. */ MessageAccess getAccess(); /** * Serialize the resource into XML, adding an element to the doc under the top of the stack element. * * @param doc * The DOM doc to contain the XML (or null for a string return). * @param stack * The DOM elements, the top of which is the containing element of the new "resource" element. * @return The newly added element. */ Element toXml(Document doc, Stack stack); }
conder/sakai
message/message-api/api/src/java/org/sakaiproject/message/api/MessageHeader.java
Java
apache-2.0
4,259
cask 'midi-monitor' do version '1.3.2' sha256 '1b2f0a2e1892247c3a5c0c9fc48c682dfcbd4e15881a26eeaaf6026c7f61f24c' url "https://www.snoize.com/MIDIMonitor/MIDIMonitor_#{version.dots_to_underscores}.zip" appcast 'https://www.snoize.com/MIDIMonitor/MIDIMonitor.xml', checkpoint: 'eb0ebc4edfa5274c5a051c7753c3bcf924cc75392ec9a69d33176184732a29a5' name 'MIDI Monitor' homepage 'https://www.snoize.com/MIDIMonitor/' depends_on macos: '>= :lion' app 'MIDI Monitor.app' uninstall quit: [ 'com.snoize.MIDIMonitor', 'com.snoize.MIDIMonitorDriver', 'com.snoize.MIDISpyFramework', 'com.snoize.SnoizeMIDI', ] zap delete: [ '~/Library/Preferences/com.snoize.MIDIMonitor.plist', '~/Library/Caches/com.snoize.MIDIMonitor', '~/Library/Saved Application State/com.snoize.MIDIMonitor.savedState', ] end
vitorgalvao/homebrew-cask
Casks/midi-monitor.rb
Ruby
bsd-2-clause
978
// #docregion import { Component } from '@angular/core'; import { DataService } from './data.service'; @Component({ selector: 'hero-di', template: `<h1>Hero: {{name}}</h1>` }) export class HeroComponent { name = ''; constructor(dataService: DataService) { this.name = dataService.getHeroName(); } } // #enddocregion
juleskremer/angular.io
public/docs/_examples/cb-ts-to-js/ts/src/app/hero-di.component.ts
TypeScript
mit
333
import css from './source.css'; __export__ = css; export default css;
webpack-contrib/css-loader
test/fixtures/postcss-present-env/source.js
JavaScript
mit
72
def f(x): """ Returns ------- object """ return 42
smmribeiro/intellij-community
python/testData/intentions/returnTypeInNewNumpyDocString_after.py
Python
apache-2.0
75
// errorcheck // Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // issue 5358: incorrect error message when using f(g()) form on ... args. package main func f(x int, y ...int) {} func g() (int, []int) func main() { f(g()) // ERROR "as type int in|incompatible type" }
vsekhar/elastic-go
test/fixedbugs/issue5358.go
GO
bsd-3-clause
384
'use strict'; module.exports = function (t, a) { var x; a.throws(function () { t(0); }, TypeError, "0"); a.throws(function () { t(false); }, TypeError, "false"); a.throws(function () { t(''); }, TypeError, "''"); a(t(x = {}), x, "Object"); a(t(x = function () {}), x, "Function"); a(t(x = new String('raz')), x, "String object"); //jslint: ignore a(t(x = new Date()), x, "Date"); a.throws(function () { t(); }, TypeError, "Undefined"); a.throws(function () { t(null); }, TypeError, "null"); };
yuyang545262477/Resume
项目二电商首页/node_modules/es5-ext/test/object/valid-object.js
JavaScript
mit
506
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ package org.tensorflow.op.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotation used by classes to make TensorFlow operations conveniently accessible via {@code * org.tensorflow.op.Ops}. * * <p>An annotation processor (TODO: not yet implemented) builds the {@code Ops} class by * aggregating all classes annotated as {@code @Operator}s. Each annotated class <b>must</b> have at * least one public static factory method named {@code create} that accepts a {@link * org.tensorflow.op.Scope} as its first argument. The processor then adds a convenience method in * the {@code Ops} class. For example: * * <pre>{@code * @Operator * public final class MyOp implements Op { * public static MyOp create(Scope scope, Operand operand) { * ... * } * } * }</pre> * * <p>results in a method in the {@code Ops} class * * <pre>{@code * import org.tensorflow.op.Ops; * ... * Ops ops = new Ops(graph); * ... * ops.myOp(operand); * // and has exactly the same effect as calling * // MyOp.create(ops.getScope(), operand); * }</pre> */ @Documented @Target(ElementType.TYPE) @Retention(RetentionPolicy.SOURCE) public @interface Operator { /** * Specify an optional group within the {@code Ops} class. * * <p>By default, an annotation processor will create convenience methods directly in the {@code * Ops} class. An annotated operator may optionally choose to place the method within a group. For * example: * * <pre>{@code * @Operator(group="math") * public final class Add extends PrimitiveOp implements Operand { * ... * } * }</pre> * * <p>results in the {@code add} method placed within a {@code math} group within the {@code Ops} * class. * * <pre>{@code * ops.math().add(...); * }</pre> * * <p>The group name must be a <a * href="https://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.8">valid Java * identifier</a>. */ String group() default ""; /** * Name for the wrapper method used in the {@code Ops} class. * * <p>By default, a processor derives the method name in the {@code Ops} class from the class name * of the operator. This attribute allow you to provide a different name instead. For example: * * <pre>{@code * @Operator(name="myOperation") * public final class MyRealOperation implements Operand { * public static MyRealOperation create(...) * } * }</pre> * * <p>results in this method added to the {@code Ops} class * * <pre>{@code * ops.myOperation(...); * // and is the same as calling * // MyRealOperation.create(...) * }</pre> * * <p>The name must be a <a * href="https://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.8">valid Java * identifier</a>. */ String name() default ""; }
nburn42/tensorflow
tensorflow/java/src/main/java/org/tensorflow/op/annotation/Operator.java
Java
apache-2.0
3,654
<?php PHPExcel_Autoloader::register(); // As we always try to run the autoloader before anything else, we can use it to do a few // simple checks and initialisations //PHPExcel_Shared_ZipStreamWrapper::register(); // check mbstring.func_overload if (ini_get('mbstring.func_overload') & 2) { throw new PHPExcel_Exception('Multibyte function overloading in PHP must be disabled for string functions (2).'); } PHPExcel_Shared_String::buildCharacterSets(); /** * PHPExcel * * Copyright (c) 2006 - 2015 PHPExcel * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * @category PHPExcel * @package PHPExcel * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL * @version ##VERSION##, ##DATE## */ class PHPExcel_Autoloader { /** * Register the Autoloader with SPL * */ public static function register() { if (function_exists('__autoload')) { // Register any existing autoloader function with SPL, so we don't get any clashes spl_autoload_register('__autoload'); } // Register ourselves with SPL if (version_compare(PHP_VERSION, '5.3.0') >= 0) { return spl_autoload_register(array('PHPExcel_Autoloader', 'load'), true, true); } else { return spl_autoload_register(array('PHPExcel_Autoloader', 'load')); } } /** * Autoload a class identified by name * * @param string $pClassName Name of the object to load */ public static function load($pClassName) { if ((class_exists($pClassName, false)) || (strpos($pClassName, 'PHPExcel') !== 0)) { // Either already loaded, or not a PHPExcel class request return false; } $pClassFilePath = PHPEXCEL_ROOT . str_replace('_', DIRECTORY_SEPARATOR, $pClassName) . '.php'; if ((file_exists($pClassFilePath) === false) || (is_readable($pClassFilePath) === false)) { // Can't load return false; } require($pClassFilePath); } }
yysun2000/delibelight
yc/lib/PHPExcel/Autoloader.php
PHP
mit
2,884
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Numerics.Tests { public class op_leftshiftTest { private static int s_samples = 10; private static Random s_random = new Random(100); [Fact] public static void RunLeftShiftTests() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // LeftShift Method - Large BigIntegers - large + Shift for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = GetRandomPosByteArray(s_random, 2); VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<"); } // LeftShift Method - Large BigIntegers - small + Shift for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = new byte[] { (byte)s_random.Next(1, 32) }; VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<"); } // LeftShift Method - Large BigIntegers - 32 bit Shift for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = new byte[] { (byte)32 }; VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<"); } // LeftShift Method - Large BigIntegers - large - Shift for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = GetRandomNegByteArray(s_random, 2); VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<"); } // LeftShift Method - Large BigIntegers - small - Shift for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = new byte[] { unchecked((byte)s_random.Next(-31, 0)) }; VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<"); } // LeftShift Method - Large BigIntegers - -32 bit Shift for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = new byte[] { (byte)0xe0 }; VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<"); } // LeftShift Method - Large BigIntegers - 0 bit Shift for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = new byte[] { (byte)0 }; VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<"); } // LeftShift Method - Small BigIntegers - large + Shift for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = GetRandomPosByteArray(s_random, 2); VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<"); } // LeftShift Method - Small BigIntegers - small + Shift for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = new byte[] { (byte)s_random.Next(1, 32) }; VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<"); } // LeftShift Method - Small BigIntegers - 32 bit Shift for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = new byte[] { (byte)32 }; VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<"); } // LeftShift Method - Small BigIntegers - large - Shift for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = GetRandomNegByteArray(s_random, 2); VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<"); } // LeftShift Method - Small BigIntegers - small - Shift for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = new byte[] { unchecked((byte)s_random.Next(-31, 0)) }; VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<"); } // LeftShift Method - Small BigIntegers - -32 bit Shift for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = new byte[] { (byte)0xe0 }; VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<"); } // LeftShift Method - Small BigIntegers - 0 bit Shift for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = new byte[] { (byte)0 }; VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<"); } // LeftShift Method - Positive BigIntegers - Shift to 0 for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomPosByteArray(s_random, 100); tempByteArray2 = BitConverter.GetBytes(s_random.Next(-1000, -8 * tempByteArray1.Length)); VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<"); } // LeftShift Method - Negative BigIntegers - Shift to -1 for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomNegByteArray(s_random, 100); tempByteArray2 = BitConverter.GetBytes(s_random.Next(-1000, -8 * tempByteArray1.Length)); VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<"); } } private static void VerifyLeftShiftString(string opstring) { StackCalc sc = new StackCalc(opstring); while (sc.DoNextOperation()) { Assert.Equal(sc.snCalc.Peek().ToString(), sc.myCalc.Peek().ToString()); } } private static byte[] GetRandomByteArray(Random random) { return GetRandomByteArray(random, random.Next(0, 1024)); } private static byte[] GetRandomByteArray(Random random, int size) { return MyBigIntImp.GetRandomByteArray(random, size); } private static Byte[] GetRandomPosByteArray(Random random, int size) { byte[] value = new byte[size]; for (int i = 0; i < value.Length; ++i) { value[i] = (byte)random.Next(0, 256); } value[value.Length - 1] &= 0x7F; return value; } private static Byte[] GetRandomNegByteArray(Random random, int size) { byte[] value = new byte[size]; for (int i = 0; i < value.Length; ++i) { value[i] = (byte)random.Next(0, 256); } value[value.Length - 1] |= 0x80; return value; } private static String Print(byte[] bytes) { return MyBigIntImp.Print(bytes); } } }
DnlHarvey/corefx
src/System.Runtime.Numerics/tests/BigInteger/op_leftshift.cs
C#
mit
8,031
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Form\Guess; /** * Base class for guesses made by TypeGuesserInterface implementation * * Each instance contains a confidence value about the correctness of the guess. * Thus an instance with confidence HIGH_CONFIDENCE is more likely to be * correct than an instance with confidence LOW_CONFIDENCE. * * @author Bernhard Schussek <bernhard.schussek@symfony.com> */ abstract class Guess { /** * Marks an instance with a value that is very likely to be correct * @var integer */ const HIGH_CONFIDENCE = 2; /** * Marks an instance with a value that is likely to be correct * @var integer */ const MEDIUM_CONFIDENCE = 1; /** * Marks an instance with a value that may be correct * @var integer */ const LOW_CONFIDENCE = 0; /** * The list of allowed confidence values * @var array */ private static $confidences = array( self::HIGH_CONFIDENCE, self::MEDIUM_CONFIDENCE, self::LOW_CONFIDENCE, ); /** * The confidence about the correctness of the value * * One of HIGH_CONFIDENCE, MEDIUM_CONFIDENCE and LOW_CONFIDENCE. * * @var integer */ private $confidence; /** * Returns the guess most likely to be correct from a list of guesses * * If there are multiple guesses with the same, highest confidence, the * returned guess is any of them. * * @param array $guesses A list of guesses * * @return Guess The guess with the highest confidence */ public static function getBestGuess(array $guesses) { usort($guesses, function ($a, $b) { return $b->getConfidence() - $a->getConfidence(); }); return count($guesses) > 0 ? $guesses[0] : null; } /** * Constructor * * @param integer $confidence The confidence */ public function __construct($confidence) { if (!in_array($confidence, self::$confidences)) { throw new \UnexpectedValueException(sprintf('The confidence should be one of "%s"', implode('", "', self::$confidences))); } $this->confidence = $confidence; } /** * Returns the confidence that the guessed value is correct * * @return integer One of the constants HIGH_CONFIDENCE, MEDIUM_CONFIDENCE * and LOW_CONFIDENCE */ public function getConfidence() { return $this->confidence; } }
winze/CMS-experience
vendor/symfony/src/Symfony/Component/Form/Guess/Guess.php
PHP
mit
2,752
// Boost.TypeErasure library // // Copyright 2011 Steven Watanabe // // Distributed under the Boost Software License Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // $Id$ #if !defined(BOOST_PP_IS_ITERATING) #ifndef BOOST_TYPE_ERASURE_CALLABLE_HPP_INCLUDED #define BOOST_TYPE_ERASURE_CALLABLE_HPP_INCLUDED #include <boost/utility/declval.hpp> #include <boost/mpl/vector.hpp> #include <boost/mpl/push_back.hpp> #include <boost/preprocessor/cat.hpp> #include <boost/preprocessor/dec.hpp> #include <boost/preprocessor/iteration/iterate.hpp> #include <boost/preprocessor/repetition/enum.hpp> #include <boost/preprocessor/repetition/enum_params.hpp> #include <boost/preprocessor/repetition/enum_trailing_params.hpp> #include <boost/preprocessor/repetition/enum_binary_params.hpp> #include <boost/preprocessor/repetition/enum_trailing_binary_params.hpp> #include <boost/type_erasure/config.hpp> #include <boost/type_erasure/call.hpp> #include <boost/type_erasure/concept_interface.hpp> #include <boost/type_erasure/rebind_any.hpp> #include <boost/type_erasure/param.hpp> namespace boost { namespace type_erasure { template<class Sig, class F = _self> struct callable; namespace detail { template<class Sig> struct result_of_callable; } #if defined(BOOST_TYPE_ERASURE_DOXYGEN) /** * The @ref callable concept allows an @ref any to hold function objects. * @c Sig is interpreted in the same way as for Boost.Function, except * that the arguments and return type are allowed to be placeholders. * @c F must be a @ref placeholder. * * Multiple instances of @ref callable can be used * simultaneously. Overload resolution works normally. * Note that unlike Boost.Function, @ref callable * does not provide result_type. It does, however, * support @c boost::result_of. */ template<class Sig, class F = _self> struct callable { /** * @c R is the result type of @c Sig and @c T is the argument * types of @c Sig. */ static R apply(F& f, T... arg); }; #elif !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) && !defined(BOOST_NO_CXX11_RVALUE_REFERENCES) template<class R, class... T, class F> struct callable<R(T...), F> { static R apply(F& f, T... arg) { return f(std::forward<T>(arg)...); } }; template<class... T, class F> struct callable<void(T...), F> { static void apply(F& f, T... arg) { f(std::forward<T>(arg)...); } }; template<class R, class F, class Base, class Enable, class... T> struct concept_interface<callable<R(T...), F>, Base, F, Enable> : Base { template<class Sig> struct result : ::boost::type_erasure::detail::result_of_callable<Sig> {}; typedef void _boost_type_erasure_is_callable; typedef ::boost::mpl::vector<R> _boost_type_erasure_callable_results; typedef char (&_boost_type_erasure_callable_size)[1]; _boost_type_erasure_callable_size _boost_type_erasure_deduce_callable( typename ::boost::type_erasure::as_param<Base, T>::type...); typename ::boost::type_erasure::rebind_any<Base, R>::type operator()(typename ::boost::type_erasure::as_param<Base, T>::type... arg) { return ::boost::type_erasure::call(callable<R(T...), F>(), *this, ::std::forward<typename ::boost::type_erasure::as_param<Base, T>::type>(arg)...); } }; template<class R, class F, class Base, class Enable, class... T> struct concept_interface<callable<R(T...), const F>, Base, F, Enable> : Base { template<class Sig> struct result : ::boost::type_erasure::detail::result_of_callable<Sig> {}; typedef void _boost_type_erasure_is_callable; typedef ::boost::mpl::vector<R> _boost_type_erasure_callable_results; typedef char (&_boost_type_erasure_callable_size)[1]; _boost_type_erasure_callable_size _boost_type_erasure_deduce_callable( typename ::boost::type_erasure::as_param<Base, T>::type...) const; typename ::boost::type_erasure::rebind_any<Base, R>::type operator()( typename ::boost::type_erasure::as_param<Base, T>::type... arg) const { return ::boost::type_erasure::call(callable<R(T...), const F>(), *this, ::std::forward<typename ::boost::type_erasure::as_param<Base, T>::type>(arg)...); } }; template<class R, class F, class Base, class... T> struct concept_interface< callable<R(T...), F>, Base, F, typename Base::_boost_type_erasure_is_callable > : Base { typedef typename ::boost::mpl::push_back< typename Base::_boost_type_erasure_callable_results, R >::type _boost_type_erasure_callable_results; typedef char (&_boost_type_erasure_callable_size)[ ::boost::mpl::size<_boost_type_erasure_callable_results>::value]; using Base::_boost_type_erasure_deduce_callable; _boost_type_erasure_callable_size _boost_type_erasure_deduce_callable( typename ::boost::type_erasure::as_param<Base, T>::type...); using Base::operator(); typename ::boost::type_erasure::rebind_any<Base, R>::type operator()(typename ::boost::type_erasure::as_param<Base, T>::type... arg) { return ::boost::type_erasure::call(callable<R(T...), F>(), *this, ::std::forward<typename ::boost::type_erasure::as_param<Base, T>::type>(arg)...); } }; template<class R, class F, class Base, class... T> struct concept_interface< callable<R(T...), const F>, Base, F, typename Base::_boost_type_erasure_is_callable > : Base { typedef typename ::boost::mpl::push_back< typename Base::_boost_type_erasure_callable_results, R >::type _boost_type_erasure_callable_results; typedef char (&_boost_type_erasure_callable_size)[ ::boost::mpl::size<_boost_type_erasure_callable_results>::value]; using Base::_boost_type_erasure_deduce_callable; _boost_type_erasure_callable_size _boost_type_erasure_deduce_callable( typename ::boost::type_erasure::as_param<Base, T>::type...) const; using Base::operator(); typename ::boost::type_erasure::rebind_any<Base, R>::type operator()(typename ::boost::type_erasure::as_param<Base, T>::type... arg) const { return ::boost::type_erasure::call(callable<R(T...), const F>(), *this, ::std::forward<typename ::boost::type_erasure::as_param<Base, T>::type>(arg)...); } }; namespace detail { template<class This, class... T> struct result_of_callable<This(T...)> { typedef typename ::boost::mpl::at_c< typename This::_boost_type_erasure_callable_results, sizeof(::boost::declval<This>(). _boost_type_erasure_deduce_callable(::boost::declval<T>()...)) - 1 >::type type; }; } #else /** INTERNAL ONLY */ #define BOOST_PP_FILENAME_1 <boost/type_erasure/callable.hpp> /** INTERNAL ONLY */ #define BOOST_PP_ITERATION_LIMITS (0, BOOST_PP_DEC(BOOST_TYPE_ERASURE_MAX_ARITY)) #include BOOST_PP_ITERATE() #endif } } #endif #else #define N BOOST_PP_ITERATION() #define BOOST_TYPE_ERASURE_DECLVAL(z, n, data) ::boost::declval<BOOST_PP_CAT(T, n)>() #define BOOST_TYPE_ERASURE_REBIND(z, n, data)\ typename ::boost::type_erasure::as_param<Base, BOOST_PP_CAT(T, n)>::type BOOST_PP_CAT(arg, n) #ifdef BOOST_NO_CXX11_RVALUE_REFERENCES #define BOOST_TYPE_ERASURE_FORWARD(z, n, data) BOOST_PP_CAT(BOOST_PP_TUPLE_ELEM(2, 1, data), n) #define BOOST_TYPE_ERASURE_FORWARD_REBIND(z, n, data) BOOST_PP_CAT(arg, n) #else #define BOOST_TYPE_ERASURE_FORWARD(z, n, data) ::std::forward<BOOST_PP_CAT(BOOST_PP_TUPLE_ELEM(2, 0, data), n)>(BOOST_PP_CAT(BOOST_PP_TUPLE_ELEM(2, 1, data), n)) #define BOOST_TYPE_ERASURE_FORWARD_REBIND(z, n, data) ::std::forward<typename ::boost::type_erasure::as_param<Base, BOOST_PP_CAT(T, n)>::type>(BOOST_PP_CAT(arg, n)) #endif template<class R BOOST_PP_ENUM_TRAILING_PARAMS(N, class T), class F> struct callable<R(BOOST_PP_ENUM_PARAMS(N, T)), F> { static R apply(F& f BOOST_PP_ENUM_TRAILING_BINARY_PARAMS(N, T, arg)) { return f(BOOST_PP_ENUM(N, BOOST_TYPE_ERASURE_FORWARD, (T, arg))); } }; template<BOOST_PP_ENUM_PARAMS(N, class T) BOOST_PP_COMMA_IF(N) class F> struct callable<void(BOOST_PP_ENUM_PARAMS(N, T)), F> { static void apply(F& f BOOST_PP_ENUM_TRAILING_BINARY_PARAMS(N, T, arg)) { f(BOOST_PP_ENUM(N, BOOST_TYPE_ERASURE_FORWARD, (T, arg))); } }; template<class R BOOST_PP_ENUM_TRAILING_PARAMS(N, class T), class F, class Base, class Enable> struct concept_interface< callable<R(BOOST_PP_ENUM_PARAMS(N, T)), F>, Base, F, Enable > : Base { template<class Sig> struct result : ::boost::type_erasure::detail::result_of_callable<Sig> {}; typedef void _boost_type_erasure_is_callable; typedef ::boost::mpl::vector<R> _boost_type_erasure_callable_results; typedef char (&_boost_type_erasure_callable_size)[1]; _boost_type_erasure_callable_size _boost_type_erasure_deduce_callable( BOOST_PP_ENUM(N, BOOST_TYPE_ERASURE_REBIND, ~)); typename ::boost::type_erasure::rebind_any<Base, R>::type operator()(BOOST_PP_ENUM(N, BOOST_TYPE_ERASURE_REBIND, ~)) { return ::boost::type_erasure::call( callable<R(BOOST_PP_ENUM_PARAMS(N, T)), F>(), *this BOOST_PP_ENUM_TRAILING(N, BOOST_TYPE_ERASURE_FORWARD_REBIND, ~)); } }; template<class R BOOST_PP_ENUM_TRAILING_PARAMS(N, class T), class F, class Base, class Enable> struct concept_interface< callable<R(BOOST_PP_ENUM_PARAMS(N, T)), const F>, Base, F, Enable > : Base { template<class Sig> struct result : ::boost::type_erasure::detail::result_of_callable<Sig> {}; typedef void _boost_type_erasure_is_callable; typedef ::boost::mpl::vector<R> _boost_type_erasure_callable_results; typedef char (&_boost_type_erasure_callable_size)[1]; _boost_type_erasure_callable_size _boost_type_erasure_deduce_callable( BOOST_PP_ENUM(N, BOOST_TYPE_ERASURE_REBIND, ~)) const; typename ::boost::type_erasure::rebind_any<Base, R>::type operator()(BOOST_PP_ENUM(N, BOOST_TYPE_ERASURE_REBIND, ~)) const { return ::boost::type_erasure::call( callable<R(BOOST_PP_ENUM_PARAMS(N, T)), const F>(), *this BOOST_PP_ENUM_TRAILING(N, BOOST_TYPE_ERASURE_FORWARD_REBIND, ~)); } }; template<class R BOOST_PP_ENUM_TRAILING_PARAMS(N, class T), class F, class Base> struct concept_interface< callable<R(BOOST_PP_ENUM_PARAMS(N, T)), F>, Base, F, typename Base::_boost_type_erasure_is_callable > : Base { typedef typename ::boost::mpl::push_back< typename Base::_boost_type_erasure_callable_results, R >::type _boost_type_erasure_callable_results; typedef char (&_boost_type_erasure_callable_size)[ ::boost::mpl::size<_boost_type_erasure_callable_results>::value]; using Base::_boost_type_erasure_deduce_callable; _boost_type_erasure_callable_size _boost_type_erasure_deduce_callable( BOOST_PP_ENUM(N, BOOST_TYPE_ERASURE_REBIND, ~)); using Base::operator(); typename ::boost::type_erasure::rebind_any<Base, R>::type operator()(BOOST_PP_ENUM(N, BOOST_TYPE_ERASURE_REBIND, ~)) { return ::boost::type_erasure::call( callable<R(BOOST_PP_ENUM_PARAMS(N, T)), F>(), *this BOOST_PP_ENUM_TRAILING(N, BOOST_TYPE_ERASURE_FORWARD_REBIND, ~)); } }; template<class R BOOST_PP_ENUM_TRAILING_PARAMS(N, class T), class F, class Base> struct concept_interface< callable<R(BOOST_PP_ENUM_PARAMS(N, T)), const F>, Base, F, typename Base::_boost_type_erasure_is_callable > : Base { typedef typename ::boost::mpl::push_back< typename Base::_boost_type_erasure_callable_results, R >::type _boost_type_erasure_callable_results; typedef char (&_boost_type_erasure_callable_size)[ ::boost::mpl::size<_boost_type_erasure_callable_results>::value]; using Base::_boost_type_erasure_deduce_callable; _boost_type_erasure_callable_size _boost_type_erasure_deduce_callable( BOOST_PP_ENUM(N, BOOST_TYPE_ERASURE_REBIND, ~)) const; using Base::operator(); typename ::boost::type_erasure::rebind_any<Base, R>::type operator()(BOOST_PP_ENUM(N, BOOST_TYPE_ERASURE_REBIND, ~)) const { return ::boost::type_erasure::call( callable<R(BOOST_PP_ENUM_PARAMS(N, T)), const F>(), *this BOOST_PP_ENUM_TRAILING(N, BOOST_TYPE_ERASURE_FORWARD_REBIND, ~)); } }; namespace detail { template<class This BOOST_PP_ENUM_TRAILING_PARAMS(N, class T)> struct result_of_callable<This(BOOST_PP_ENUM_PARAMS(N, T))> { typedef typename ::boost::mpl::at_c< typename This::_boost_type_erasure_callable_results, sizeof(::boost::declval<This>(). _boost_type_erasure_deduce_callable( BOOST_PP_ENUM(N, BOOST_TYPE_ERASURE_DECLVAL, ~))) - 1 >::type type; }; } #undef BOOST_TYPE_ERASURE_DECLVAL #undef BOOST_TYPE_ERASURE_REBIND #undef N #endif
rkq/cxxexp
third-party/src/boost_1_56_0/boost/type_erasure/callable.hpp
C++
mit
13,033