code_text
stringlengths 604
999k
| repo_name
stringlengths 4
100
| file_path
stringlengths 4
873
| language
stringclasses 23
values | license
stringclasses 15
values | size
int32 1.02k
999k
|
---|---|---|---|---|---|
.noUiSlider,.noUiSlider *{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;display:block;cursor:default}.noUiSlider{position:relative}.noUiSlider a{position:absolute;z-index:1}.noUiSlider a:nth-child(2){background:inherit!important}.noUiSlider.vertical a{width:100%;bottom:0}.noUiSlider.horizontal a{height:100%;right:0}@media screen and (-ms-high-contrast:active),(-ms-high-contrast:none){.noUiSlider:before,body.TOUCH,.noUiSlider div{-ms-touch-action:none}.noUiSlider:before{display:block;position:absolute;width:150%;left:-25%;height:400%;top:-150%;content:"";z-index:-1}.noUiSlider.vertical:before{width:400%;left:-150%;height:150%;top:-25%}}.noUiSlider{border:1px solid #908d84;border-radius:3px}.noUiSlider.connect a,.noUiSlider.connect.lower{background:#b2a98f}.noUiSlider,.noUiSlider.connect.lower a{background:#d9d7cb;box-shadow:inset 0 1px 7px #b6b4a8}.noUiSlider.disabled,.noUiSlider.disabled.connect.lower a{background:#ccc;box-shadow:none}.noUiSlider div{height:18px;width:18px;border:1px solid #99968f;border-radius:3px;background:#efefe7}.noUiSlider.disabled div{background:transparent}.noUiSlider.horizontal{width:300px;height:10px}.noUiSlider.horizontal div{margin:-5px 0 0 -9px}.noUiSlider.vertical{width:10px;height:300px}.noUiSlider.vertical div{margin:-9px 0 0 -5px} | thejsj/cdnjs | ajax/libs/noUiSlider/3.0.4/nouislider.fox.min.css | CSS | mit | 1,385 |
/*
* Test to make sure that we properly are erroring whenever we try to write
* beyond the size of the integer.
*/
var mod_ctio = require('../../../ctio.js');
var mod_assert = require('assert');
var tb = new Buffer(16); /* Largest buffer we'll need */
var cases = [
{ func:
function () {
mod_ctio.wsint8(0x80, 'big', tb, 0);
}, test: '+int8_t' },
{ func:
function () {
mod_ctio.wsint8(-0x81, 'big', tb, 0);
}, test: '-int8_t' },
{ func:
function () {
mod_ctio.wsint16(0x8000, 'big', tb, 0);
}, test: '+int16_t' },
{ func:
function () {
mod_ctio.wsint16(-0x8001, 'big', tb, 0);
}, test: '-int16_t' },
{ func:
function () {
mod_ctio.wsint32(0x80000000, 'big', tb, 0);
}, test: '+int32_t' },
{ func:
function () {
mod_ctio.wsint32(-0x80000001, 'big', tb, 0);
}, test: '-int32_t' },
{ func:
function () {
mod_ctio.wsint64([ 0x80000000, 0 ], 'big', tb, 0);
}, test: '+int64_t' },
{ func:
function () {
mod_ctio.wsint64([ -0x80000000, -1 ], 'big', tb, 0);
}, test: '-int64_t' }
];
function test()
{
var ii;
for (ii = 0; ii < cases.length; ii++)
mod_assert.throws(cases[ii]['func'], Error, cases[ii]['test']);
}
test();
| interactiveinstitute/watthappened | node_modules/couchapp/node_modules/request/node_modules/http-signature/node_modules/ctype/tst/ctio/int/tst.wbounds.js | JavaScript | mit | 1,165 |
//
// UIApplication+PNAdditions.m
// pubnub
//
// Created by Sergey Mamontov on 8/4/13.
//
//
#if __IPHONE_OS_VERSION_MIN_REQUIRED
#import "UIApplication+PNAdditions.h"
// ARC check
#if !__has_feature(objc_arc)
#error PubNub application category must be built with ARC.
// You can turn on ARC for only PubNub files by adding '-fobjc-arc' to the build phase for each of its files.
#endif
#pragma mark Public interface implementation
@implementation UIApplication (PNAdditions)
#pragma mark - Class methods
+ (BOOL)pn_canRunInBackground {
static BOOL canRunInBackground;
static dispatch_once_t dispatchOnceToken;
dispatch_once(&dispatchOnceToken, ^{
// Retrieve application information Property List
NSDictionary *applicationInformation = [[NSBundle mainBundle] infoDictionary];
if ([applicationInformation objectForKey:@"UIBackgroundModes"]) {
NSArray *backgroundModes = [applicationInformation valueForKey:@"UIBackgroundModes"];
NSArray *suitableModes = @[@"audio", @"location", @"voip", @"bluetooth-central", @"bluetooth-peripheral"];
[backgroundModes enumerateObjectsUsingBlock:^(id mode, NSUInteger modeIdx, BOOL *modeEnumeratorStop) {
canRunInBackground = [suitableModes containsObject:mode];
*modeEnumeratorStop = canRunInBackground;
}];
}
});
return canRunInBackground;
}
#pragma mark -
@end
#endif
| opentable/pubnub | iOS/tests/SendMessage/pubnub/libs/PubNub/Misc/Categories/UIApplication+PNAdditions.m | Matlab | mit | 1,459 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('projects', '0002_auto_20140903_0920'),
('contenttypes', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Reference',
fields=[
('id', models.AutoField(verbose_name='ID', auto_created=True, serialize=False, primary_key=True)),
('object_id', models.PositiveIntegerField()),
('ref', models.BigIntegerField()),
('created_at', models.DateTimeField(default=django.utils.timezone.now)),
('content_type', models.ForeignKey(related_name='+', to='contenttypes.ContentType')),
('project', models.ForeignKey(related_name='references', to='projects.Project')),
],
options={
'ordering': ['created_at'],
},
bases=(models.Model,),
),
migrations.AlterUniqueTogether(
name='reference',
unique_together=set([('project', 'ref')]),
),
]
| mattcongy/itshop | docker-images/taigav2/taiga-back/taiga/projects/references/migrations/0001_initial.py | Python | mit | 1,199 |
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
// ===========================================================================
// File: StrongName.cpp
//
// Wrappers for signing and hashing functions needed to implement strong names
// ===========================================================================
#include "common.h"
#include <imagehlp.h>
#include <winwrap.h>
#include <windows.h>
#include <wincrypt.h>
#include <stddef.h>
#include <stdio.h>
#include <malloc.h>
#include <cor.h>
#include <corimage.h>
#include <metadata.h>
#include <daccess.h>
#include <limits.h>
#include <ecmakey.h>
#include <sha1.h>
#include "strongname.h"
#include "ex.h"
#include "pedecoder.h"
#include "strongnameholders.h"
#include "strongnameinternal.h"
#include "common.h"
#include "classnames.h"
// Debug logging.
#if !defined(_DEBUG) || defined(DACCESS_COMPILE)
#define SNLOG(args)
#endif // !_DEBUG || DACCESS_COMPILE
#ifndef DACCESS_COMPILE
// Debug logging.
#if defined(_DEBUG)
#include <stdarg.h>
BOOLEAN g_fLoggingInitialized = FALSE;
DWORD g_dwLoggingFlags = FALSE;
#define SNLOG(args) Log args
void Log(__in_z const WCHAR *wszFormat, ...)
{
if (g_fLoggingInitialized && !g_dwLoggingFlags)
return;
DWORD dwError = GetLastError();
if (!g_fLoggingInitialized) {
g_dwLoggingFlags = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_MscorsnLogging);
g_fLoggingInitialized = TRUE;
}
if (!g_dwLoggingFlags) {
SetLastError(dwError);
return;
}
va_list pArgs;
WCHAR wszBuffer[1024];
static WCHAR wszPrefix[] = W("SN: ");
wcscpy_s(wszBuffer, COUNTOF(wszBuffer), wszPrefix);
va_start(pArgs, wszFormat);
_vsnwprintf_s(&wszBuffer[COUNTOF(wszPrefix) - 1],
COUNTOF(wszBuffer) - COUNTOF(wszPrefix),
_TRUNCATE,
wszFormat,
pArgs);
wszBuffer[COUNTOF(wszBuffer) - 1] = W('\0');
va_end(pArgs);
if (g_dwLoggingFlags & 1)
wprintf(W("%s"), wszBuffer);
if (g_dwLoggingFlags & 2)
WszOutputDebugString(wszBuffer);
if (g_dwLoggingFlags & 4)
{
MAKE_UTF8PTR_FROMWIDE_NOTHROW(szMessage, wszBuffer);
if(szMessage != NULL)
LOG((LF_SECURITY, LL_INFO100, szMessage));
}
SetLastError(dwError);
}
#endif // _DEBUG
// Size in bytes of strong name token.
#define SN_SIZEOF_TOKEN 8
enum StrongNameCachedCsp {
None = -1,
Sha1CachedCsp = 0,
Sha2CachedCsp = Sha1CachedCsp + 1,
CachedCspCount = Sha2CachedCsp + 1
};
// We cache a couple of things on a per thread basis: the last error encountered
// and (potentially) CSP contexts. The following structure tracks these and is
// allocated lazily as needed.
struct SN_THREAD_CTX {
DWORD m_dwLastError;
#if !defined(FEATURE_CORECLR) || (defined(CROSSGEN_COMPILE) && !defined(PLATFORM_UNIX))
HCRYPTPROV m_hProv[CachedCspCount];
#endif // !FEATURE_CORECLR || (CROSSGEN_COMPILE && !PLATFORM_UNIX)
};
#endif // !DACCESS_COMPILE
// Macro containing common code used at the start of most APIs.
#define SN_COMMON_PROLOG() do { \
HRESULT __hr = InitStrongName(); \
if (FAILED(__hr)) { \
SetStrongNameErrorInfo(__hr); \
retVal = FALSE; \
goto Exit; \
} \
SetStrongNameErrorInfo(S_OK); \
} while (0)
// Macro to return an error from a SN entrypoint API
#define SN_ERROR(__hr) do { \
if (FAILED(__hr)) { \
SetStrongNameErrorInfo(__hr); \
retVal = FALSE; \
goto Exit; \
} \
} while (false)
// Determine the size of a PublicKeyBlob structure given the size of the key
// portion.
#define SN_SIZEOF_KEY(_pKeyBlob) (offsetof(PublicKeyBlob, PublicKey) + GET_UNALIGNED_VAL32(&(_pKeyBlob)->cbPublicKey))
// We allow a special abbreviated form of the Microsoft public key (16 bytes
// long: 0 for both alg ids, 4 for key length and 4 bytes of 0 for the key
// itself). This allows us to build references to system libraries that are
// platform neutral (so a 3rd party can build mscorlib replacements). The
// special zero PK is just shorthand for the local runtime's real system PK,
// which is always used to perform the signature verification, so no security
// hole is opened by this. Therefore we need to store a copy of the real PK (for
// this platform) here.
// the actual definition of the microsoft key is in separate file to allow custom keys
#include "thekey.h"
#define SN_THE_KEY() ((PublicKeyBlob*)g_rbTheKey)
#define SN_SIZEOF_THE_KEY() sizeof(g_rbTheKey)
#define SN_THE_KEYTOKEN() ((PublicKeyBlob*)g_rbTheKeyToken)
// Determine if the given public key blob is the neutral key.
#define SN_IS_NEUTRAL_KEY(_pk) (SN_SIZEOF_KEY((PublicKeyBlob*)(_pk)) == sizeof(g_rbNeutralPublicKey) && \
memcmp((_pk), g_rbNeutralPublicKey, sizeof(g_rbNeutralPublicKey)) == 0)
#define SN_IS_THE_KEY(_pk) (SN_SIZEOF_KEY((PublicKeyBlob*)(_pk)) == sizeof(g_rbTheKey) && \
memcmp((_pk), g_rbTheKey, sizeof(g_rbTheKey)) == 0)
#ifdef FEATURE_CORECLR
// Silverlight platform key
#define SN_THE_SILVERLIGHT_PLATFORM_KEYTOKEN() ((PublicKeyBlob*)g_rbTheSilverlightPlatformKeyToken)
#define SN_IS_THE_SILVERLIGHT_PLATFORM_KEY(_pk) (SN_SIZEOF_KEY((PublicKeyBlob*)(_pk)) == sizeof(g_rbTheSilverlightPlatformKey) && \
memcmp((_pk), g_rbTheSilverlightPlatformKey, sizeof(g_rbTheSilverlightPlatformKey)) == 0)
// Silverlight key
#define SN_IS_THE_SILVERLIGHT_KEY(_pk) (SN_SIZEOF_KEY((PublicKeyBlob*)(_pk)) == sizeof(g_rbTheSilverlightKey) && \
memcmp((_pk), g_rbTheSilverlightKey, sizeof(g_rbTheSilverlightKey)) == 0)
#define SN_THE_SILVERLIGHT_KEYTOKEN() ((PublicKeyBlob*)g_rbTheSilverlightKeyToken)
#ifdef FEATURE_WINDOWSPHONE
// Microsoft.Phone.* key
#define SN_THE_MICROSOFT_PHONE_KEYTOKEN() ((PublicKeyBlob*)g_rbTheMicrosoftPhoneKeyToken)
#define SN_IS_THE_MICROSOFT_PHONE_KEY(_pk) (SN_SIZEOF_KEY((PublicKeyBlob*)(_pk)) == sizeof(g_rbTheMicrosoftPhoneKey) && \
memcmp((_pk), g_rbTheMicrosoftPhoneKey, sizeof(g_rbTheMicrosoftPhoneKey)) == 0)
// Microsoft.Xna.* key
#define SN_THE_MICROSOFT_XNA_KEYTOKEN() ((PublicKeyBlob*)g_rbTheMicrosoftXNAKeyToken)
#define SN_IS_THE_MICROSOFT_XNA_KEY(_pk) (SN_SIZEOF_KEY((PublicKeyBlob*)(_pk)) == sizeof(g_rbTheMicrosoftXNAKey) && \
memcmp((_pk), g_rbTheMicrosoftXNAKey, sizeof(g_rbTheMicrosoftXNAKey)) == 0)
#endif // FEATURE_WINDOWSPHONE
#endif // FEATURE_CORECLR
#if !defined(FEATURE_CORECLR) || (defined(CROSSGEN_COMPILE) && !defined(PLATFORM_UNIX))
#ifdef FEATURE_STRONGNAME_MIGRATION
#include "caparser.h"
#include "custattr.h"
#include "cahlprinternal.h"
#endif // FEATURE_STRONGNAME_MIGRATION
// The maximum length of CSP name we support (in characters).
#define SN_MAX_CSP_NAME 1024
// If we're being built as a standalone library, then we shouldn't redirect through the hosting APIs
#if !STRONGNAME_IN_VM
#undef MapViewOfFile
#undef UnmapViewOfFile
#define CLRMapViewOfFile MapViewOfFile
#define CLRUnmapViewOfFile UnmapViewOfFile
#if FEATURE_STANDALONE_SN && !FEATURE_CORECLR
// We will need to call into shim, therefore include new hosting APIs
#include "metahost.h"
#include "clrinternal.h"
#endif //FEATURE_STANDALONE_SN && !FEATURE_CORECLR
#define DONOT_DEFINE_ETW_CALLBACK
#endif // !STRONGNAME_IN_VM
#include "eventtracebase.h"
#ifndef DACCESS_COMPILE
// Flag indicating whether the initialization of the strong name APIs has been completed.
BOOLEAN g_bStrongNamesInitialized = FALSE;
// Flag indicating whether it's OK to cache the results of verifying an assembly
// whose file is accessible to users.
BOOLEAN g_fCacheVerify = TRUE;
// Algorithm IDs for hashing and signing. Like the CSP name, these values are
// read from the registry at initialization time.
ALG_ID g_uHashAlgId;
ALG_ID g_uSignAlgId;
// Flag read from the registry at initialization time. It controls the key spec
// to be used. AT_SIGNATURE will be the default.
DWORD g_uKeySpec;
// CSP provider type. PROV_RSA_FULL will be the default.
DWORD g_uProvType;
// Critical section used to serialize some non-thread safe crypto APIs.
CRITSEC_COOKIE g_rStrongNameMutex = NULL;
// Name of CSP to use. This is read from the registry at initialization time. If
// not found we look up a CSP by hashing and signing algorithms (see below) or
// use the default CSP.
BOOLEAN g_bHasCSPName = FALSE;
WCHAR g_wszCSPName[SN_MAX_CSP_NAME + 1] = {0};
// Flag read from the registry at initialization time. Controls whether we use
// machine or user based key containers.
BOOLEAN g_bUseMachineKeyset = TRUE;
#ifdef FEATURE_STRONGNAME_DELAY_SIGNING_ALLOWED
// Verification Skip Records
//
// These are entries in the registry (usually set up by SN) that control whether
// an assembly needs to pass signature verification to be considered valid (i.e.
// return TRUE from StrongNameSignatureVerification). This is useful during
// development when it's not feasible to fully sign each assembly on each build.
// Assemblies to be skipped can be specified by name and public key token, all
// assemblies with a given public key token or just all assemblies. Each entry
// can be further qualified by a list of user names to which the records
// applies. When matching against an entry, the most specific one wins.
//
// We read these entries at startup time and place them into a global, singly
// linked, NULL terminated list.
// Structure used to represent each record we find in the registry.
struct SN_VER_REC {
SN_VER_REC *m_pNext; // Pointer to next record (or NULL)
WCHAR *m_wszAssembly; // Assembly name/public key token as a string
WCHAR *m_mszUserList; // Pointer to multi-string list of valid users (or NULL)
WCHAR *m_wszTestPublicKey; // Test public key to use during strong name verification (or NULL)
};
// Head of the list of entries we found in the registry during initialization.
SN_VER_REC *g_pVerificationRecords = NULL;
#endif // FEATURE_STRONGNAME_DELAY_SIGNING_ALLOWED
#ifdef FEATURE_STRONGNAME_MIGRATION
struct SN_REPLACEMENT_KEY_REC {
SN_REPLACEMENT_KEY_REC *m_pNext;
BYTE *m_pbReplacementKey;
ULONG m_cbReplacementKey;
};
struct SN_REVOCATION_REC {
SN_REVOCATION_REC *m_pNext;
BYTE *m_pbRevokedKey;
ULONG m_cbRevokedKey;
SN_REPLACEMENT_KEY_REC *m_pReplacementKeys;
};
SN_REVOCATION_REC *g_pRevocationRecords = NULL;
#endif // FEATURE_STRONGNAME_MIGRATION
#endif // #ifndef DACCESS_COMPILE
#include "thetestkey.h"
#ifndef DACCESS_COMPILE
// The actions that can be performed upon opening a CSP with LocateCSP.
#define SN_OPEN_CONTAINER 0
#define SN_IGNORE_CONTAINER 1
#define SN_CREATE_CONTAINER 2
#define SN_DELETE_CONTAINER 3
#define SN_HASH_SHA1_ONLY 4
// Macro to aid in setting flags for CryptAcquireContext based on container
// actions above.
#define SN_CAC_FLAGS(_act) \
(((_act) == SN_OPEN_CONTAINER ? 0 : \
((_act) == SN_HASH_SHA1_ONLY) || ((_act) == SN_IGNORE_CONTAINER) ? CRYPT_VERIFYCONTEXT : \
(_act) == SN_CREATE_CONTAINER ? CRYPT_NEWKEYSET : \
(_act) == SN_DELETE_CONTAINER ? CRYPT_DELETEKEYSET : \
0) | \
(g_bUseMachineKeyset ? CRYPT_MACHINE_KEYSET : 0))
// Substitute a strong name error if the error we're wrapping is not transient
FORCEINLINE HRESULT SubstituteErrorIfNotTransient(HRESULT hrOriginal, HRESULT hrSubstitute)
{
return Exception::IsTransient(hrOriginal) ? hrOriginal : hrSubstitute;
}
// Private routine prototypes.
SN_THREAD_CTX *GetThreadContext();
VOID SetStrongNameErrorInfo(DWORD dwStatus);
HCRYPTPROV LocateCSP(LPCWSTR wszKeyContainer,
DWORD dwAction,
ALG_ID uHashAlgId = 0,
ALG_ID uSignAlgId = 0);
VOID FreeCSP(HCRYPTPROV hProv);
HCRYPTPROV LookupCachedCSP(StrongNameCachedCsp cspNumber);
VOID CacheCSP(HCRYPTPROV hProv, StrongNameCachedCsp cspNumber);
BOOLEAN IsCachedCSP(HCRYPTPROV hProv);
HRESULT ReadRegistryConfig();
BOOLEAN LoadCryptoApis();
#ifdef FEATURE_STRONGNAME_DELAY_SIGNING_ALLOWED
HRESULT ReadVerificationRecords();
#ifdef FEATURE_STRONGNAME_MIGRATION
HRESULT ReadRevocationRecords();
#endif // FEATURE_STRONGNAME_MIGRATION
SN_VER_REC *GetVerificationRecord(__in_z __deref LPWSTR wszAssemblyName, PublicKeyBlob *pPublicKey);
#endif // FEATURE_STRONGNAME_DELAY_SIGNING_ALLOWED
BOOLEAN IsValidUser(__in_z WCHAR *mszUserList);
BOOLEAN GetKeyContainerName(LPCWSTR *pwszKeyContainer, BOOLEAN *pbTempContainer);
VOID FreeKeyContainerName(LPCWSTR wszKeyContainer, BOOLEAN bTempContainer);
HRESULT GetMetadataImport(__in const SN_LOAD_CTX *pLoadCtx,
__in mdAssembly *ptkAssembly,
__out IMDInternalImport **ppMetaDataImport);
HRESULT FindPublicKey(const SN_LOAD_CTX *pLoadCtx,
__out_ecount_opt(cchAssemblyName) LPWSTR wszAssemblyName,
DWORD cchAssemblyName,
__out PublicKeyBlob **ppPublicKey,
DWORD *pcbPublicKey = NULL);
PublicKeyBlob *GetPublicKeyFromHex(LPCWSTR wszPublicKeyHexString);
BOOLEAN RehashModules(SN_LOAD_CTX *pLoadCtx, LPCWSTR szFilePath);
HRESULT VerifySignature(SN_LOAD_CTX *pLoadCtx,
DWORD dwInFlags,
PublicKeyBlob *pRealEcmaPublicKey,
DWORD *pdwOutFlags);
HRESULT InitStrongNameCriticalSection();
HRESULT InitStrongName();
typedef BOOLEAN (*HashFunc)(HCRYPTHASH hHash, PBYTE start, DWORD length, DWORD flags, void* cookie);
BOOLEAN ComputeHash(SN_LOAD_CTX *pLoadCtx, HCRYPTHASH hHash, HashFunc func, void* cookie);
bool VerifyKeyMatchesAssembly(PublicKeyBlob * pAssemblySignaturePublicKey, __in_z LPCWSTR wszKeyContainer, BYTE *pbKeyBlob, ULONG cbKeyBlob, DWORD dwFlags);
#ifdef FEATURE_STRONGNAME_MIGRATION
HRESULT GetVerifiedSignatureKey(__in SN_LOAD_CTX *pLoadCtx, __out PublicKeyBlob **ppPublicKey, __out DWORD *pcbPublicKey = NULL);
#endif // FEATURE_STRONGNAME_MIGRATION
#if defined(_DEBUG) && !defined(DACCESS_COMPILE)
void DbgCount(__in_z WCHAR *szCounterName)
{
#ifndef FEATURE_CORECLR
if (g_fLoggingInitialized && !(g_dwLoggingFlags & 4))
return;
DWORD dwError = GetLastError();
if (!g_fLoggingInitialized) {
g_dwLoggingFlags = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_MscorsnLogging);
g_fLoggingInitialized = TRUE;
}
if (!(g_dwLoggingFlags & 4)) {
SetLastError(dwError);
return;
}
HKEY hKey = NULL;
DWORD dwCounter = 0;
DWORD dwBytes;
if (WszRegCreateKeyEx(HKEY_LOCAL_MACHINE,
SN_CONFIG_KEY_W W("\\Counters"),
0,
NULL,
0,
KEY_ALL_ACCESS,
NULL,
&hKey,
NULL) != ERROR_SUCCESS)
goto End;
WszRegQueryValueEx(hKey, szCounterName, NULL, NULL, (BYTE*)&dwCounter, &dwBytes);
dwCounter++;
WszRegSetValueEx(hKey, szCounterName, NULL, REG_DWORD, (BYTE*)&dwCounter, sizeof(DWORD));
End:
if (hKey)
RegCloseKey(hKey);
SetLastError(dwError);
#endif //#ifndef FEATURE_CORECLR
}
void HexDump(BYTE *pbData,
DWORD cbData)
{
if (g_dwLoggingFlags == 0)
return;
DWORD dwRow, dwCol;
WCHAR wszBuffer[1024];
WCHAR *wszPtr = wszBuffer;
#define SN_PUSH0(_fmt) do { wszPtr += swprintf_s(wszPtr, COUNTOF(wszBuffer) - (wszPtr - wszBuffer), _fmt); } while (false)
#define SN_PUSH1(_fmt, _arg1) do { wszPtr += swprintf_s(wszPtr, COUNTOF(wszBuffer) - (wszPtr - wszBuffer), _fmt, _arg1); } while (false)
wszBuffer[0] = W('\0');
for (dwRow = 0; dwRow < ((cbData + 15) / 16); dwRow++) {
SN_PUSH1(W("%08p "), pbData + (16 * dwRow));
for (dwCol = 0; dwCol < 16; dwCol++)
if (((dwRow * 16) + dwCol) < cbData)
SN_PUSH1(W("%02X "), pbData[(dwRow * 16) + dwCol]);
else
SN_PUSH0(W(" "));
for (dwCol = 0; dwCol < 16; dwCol++)
if (((dwRow * 16) + dwCol) < cbData) {
unsigned char c = pbData[(dwRow * 16) + dwCol];
if ((c >= 32) && (c <= 127))
SN_PUSH1(W("%c"), c);
else
SN_PUSH0(W("."));
} else
SN_PUSH0(W(" "));
SN_PUSH0(W("\n"));
}
#undef SN_PUSH1
#undef SN_PUSH0
_ASSERTE(wszPtr < &wszBuffer[COUNTOF(wszBuffer)]);
Log(W("%s"), wszBuffer);
}
#else // _DEBUG && !DACCESS_COMPILE
#define HexDump(x)
#define DbgCount(x)
#endif // _DEBUG && !DACCESS_COMPILE
BOOLEAN CalculateSize(HCRYPTHASH hHash, PBYTE start, DWORD length, DWORD flags, void* cookie)
{
*(size_t*)cookie += length;
return TRUE;
}
struct CopyDataBufferDesc
{
PBYTE pbData;
DWORD cbDataSize;
};
BOOLEAN CopyData(HCRYPTHASH hHash, PBYTE start, DWORD length, DWORD flags, void* cookie)
{
_ASSERTE(cookie);
CopyDataBufferDesc *pBuffer = reinterpret_cast<CopyDataBufferDesc *>(cookie);
_ASSERTE(pBuffer->pbData);
memcpy_s(pBuffer->pbData, pBuffer->cbDataSize, start, length);
pBuffer->pbData += length;
_ASSERTE(pBuffer->cbDataSize >= length);
pBuffer->cbDataSize = pBuffer->cbDataSize >= length ? pBuffer->cbDataSize - length : 0;
return TRUE;
}
BOOLEAN CalcHash(HCRYPTHASH hHash, PBYTE start, DWORD length, DWORD flags, void* cookie)
{
return CryptHashData(hHash, start, length, flags);
}
VOID
WINAPI Fls_Callback (
IN PVOID lpFlsData
)
{
STATIC_CONTRACT_SO_TOLERANT;
SN_THREAD_CTX *pThreadCtx = (SN_THREAD_CTX*)lpFlsData;
if (pThreadCtx != NULL) {
for(ULONG i = 0; i < CachedCspCount; i++)
{
if (pThreadCtx->m_hProv[i])
CryptReleaseContext(pThreadCtx->m_hProv[i], 0);
}
delete pThreadCtx;
}
}
HRESULT InitStrongNameCriticalSection()
{
if (g_rStrongNameMutex)
return S_OK;
CRITSEC_COOKIE pv = ClrCreateCriticalSection(CrstStrongName, CRST_DEFAULT);
if (pv == NULL)
return E_OUTOFMEMORY;
if (InterlockedCompareExchangeT(&g_rStrongNameMutex, pv, NULL) != NULL)
ClrDeleteCriticalSection(pv);
return S_OK;
}
HRESULT InitStrongName()
{
HRESULT hr = S_OK;
if (g_bStrongNamesInitialized)
return hr;
// Read CSP configuration info from the registry (if provided).
hr = ReadRegistryConfig();
if (FAILED(hr))
return hr;
// Associate a callback for freeing our TLS data.
ClrFlsAssociateCallback(TlsIdx_StrongName, Fls_Callback);
g_bStrongNamesInitialized = TRUE;
return hr;
}
// Generate a new key pair for strong name use.
SNAPI StrongNameKeyGen(LPCWSTR wszKeyContainer, // [in] desired key container name, must be a non-empty string
DWORD dwFlags, // [in] flags (see below)
BYTE **ppbKeyBlob, // [out] public/private key blob
ULONG *pcbKeyBlob)
{
BOOLEAN retVal = FALSE;
BEGIN_ENTRYPOINT_VOIDRET;
SN_COMMON_PROLOG();
if (wszKeyContainer == NULL && ppbKeyBlob == NULL)
SN_ERROR(E_INVALIDARG);
if (ppbKeyBlob != NULL && pcbKeyBlob == NULL)
SN_ERROR(E_POINTER);
DWORD dwKeySize;
// We set a key size of 1024 if we're using the default
// signing algorithm (RSA), otherwise we leave it at the default.
if (g_uSignAlgId == CALG_RSA_SIGN)
dwKeySize = 1024;
else
dwKeySize = 0;
retVal = StrongNameKeyGenEx(wszKeyContainer, dwFlags, dwKeySize, ppbKeyBlob, pcbKeyBlob);
Exit:
END_ENTRYPOINT_VOIDRET;
return retVal;
}
// Generate a new key pair with the specified key size for strong name use.
SNAPI StrongNameKeyGenEx(LPCWSTR wszKeyContainer, // [in] desired key container name, must be a non-empty string
DWORD dwFlags, // [in] flags (see below)
DWORD dwKeySize, // [in] desired key size.
BYTE **ppbKeyBlob, // [out] public/private key blob
ULONG *pcbKeyBlob)
{
BOOLEAN retVal = FALSE;
BEGIN_ENTRYPOINT_VOIDRET;
HCRYPTPROV hProv = NULL;
HCRYPTKEY hKey = NULL;
BOOLEAN bTempContainer = FALSE;
SNLOG((W("StrongNameKeyGenEx(\"%s\", %08X, %08X, %08X, %08X)\n"), wszKeyContainer, dwFlags, dwKeySize, ppbKeyBlob, pcbKeyBlob));
SN_COMMON_PROLOG();
if (wszKeyContainer == NULL && ppbKeyBlob == NULL)
SN_ERROR(E_INVALIDARG);
if (ppbKeyBlob != NULL && pcbKeyBlob == NULL)
SN_ERROR(E_POINTER);
// Check to see if a temporary container name is needed.
_ASSERTE((wszKeyContainer != NULL) || !(dwFlags & SN_LEAVE_KEY));
if (!GetKeyContainerName(&wszKeyContainer, &bTempContainer))
{
goto Exit;
}
// Open a CSP and container.
hProv = LocateCSP(wszKeyContainer, SN_CREATE_CONTAINER);
if (!hProv)
goto Error;
// Generate the new key pair, try for exportable first.
// Note: The key size in bits is encoded in the upper
// 16-bits of a DWORD (and OR'd together with other flags for the
// CryptGenKey call).
if (!CryptGenKey(hProv, g_uKeySpec, (dwKeySize << 16) | CRYPT_EXPORTABLE, &hKey)) {
SNLOG((W("Couldn't create exportable key, trying for non-exportable: %08X\n"), GetLastError()));
if (!CryptGenKey(hProv, g_uKeySpec, dwKeySize << 16, &hKey)) {
SNLOG((W("Couldn't create key pair: %08X\n"), GetLastError()));
goto Error;
}
}
#if defined(_DEBUG) && !defined(DACCESS_COMPILE)
if (g_bHasCSPName) {
ALG_ID uAlgId;
DWORD dwAlgIdLen = sizeof(uAlgId);
// Check that signature algorithm used was the one we expected.
if (CryptGetKeyParam(hKey, KP_ALGID, (BYTE*)&uAlgId, &dwAlgIdLen, 0)) {
_ASSERTE(uAlgId == g_uSignAlgId);
} else
SNLOG((W("Failed to get key params: %08X\n"), GetLastError()));
}
#endif // _DEBUG
// If the user wants the key pair back, attempt to export it.
if (ppbKeyBlob) {
// Calculate length of blob first;
if (!CryptExportKey(hKey, 0, PRIVATEKEYBLOB, 0, NULL, pcbKeyBlob)) {
SNLOG((W("Couldn't export key pair: %08X\n"), GetLastError()));
goto Error;
}
// Allocate a buffer of the right size.
*ppbKeyBlob = new (nothrow) BYTE[*pcbKeyBlob];
if (*ppbKeyBlob == NULL) {
SetLastError(E_OUTOFMEMORY);
goto Error;
}
// Export the key pair.
if (!CryptExportKey(hKey, 0, PRIVATEKEYBLOB, 0, *ppbKeyBlob, pcbKeyBlob)) {
SNLOG((W("Couldn't export key pair: %08X\n"), GetLastError()));
delete[] *ppbKeyBlob;
*ppbKeyBlob = NULL;
goto Error;
}
}
// Destroy the key handle (but not the key pair itself).
CryptDestroyKey(hKey);
hKey = NULL;
// Release the CSP.
FreeCSP(hProv);
// If the user didn't explicitly want to keep the key pair around, delete the
// key container.
if (!(dwFlags & SN_LEAVE_KEY) || bTempContainer)
LocateCSP(wszKeyContainer, SN_DELETE_CONTAINER);
// Free temporary key container name if allocated.
FreeKeyContainerName(wszKeyContainer, bTempContainer);
retVal = TRUE;
goto Exit;
Error:
SetStrongNameErrorInfo(HRESULT_FROM_GetLastError());
if (hKey)
CryptDestroyKey(hKey);
if (hProv) {
FreeCSP(hProv);
if (!(dwFlags & SN_LEAVE_KEY) || bTempContainer)
LocateCSP(wszKeyContainer, SN_DELETE_CONTAINER);
}
FreeKeyContainerName(wszKeyContainer, bTempContainer);
Exit:
END_ENTRYPOINT_VOIDRET;
return retVal;
}
// Import key pair into a key container.
SNAPI StrongNameKeyInstall(LPCWSTR wszKeyContainer,// [in] desired key container name, must be a non-empty string
BYTE *pbKeyBlob, // [in] public/private key pair blob
ULONG cbKeyBlob)
{
BOOLEAN retVal = FALSE;
BEGIN_ENTRYPOINT_VOIDRET;
HCRYPTPROV hProv = NULL;
HCRYPTKEY hKey = NULL;
SNLOG((W("StrongNameKeyInstall(\"%s\", %08X, %08X)\n"), wszKeyContainer, pbKeyBlob, cbKeyBlob));
SN_COMMON_PROLOG();
if (wszKeyContainer == NULL)
SN_ERROR(E_POINTER);
if (pbKeyBlob == NULL)
SN_ERROR(E_POINTER);
if (cbKeyBlob == 0)
SN_ERROR(E_INVALIDARG);
// Open a CSP and container.
hProv = LocateCSP(wszKeyContainer, SN_CREATE_CONTAINER);
if (!hProv) {
SetStrongNameErrorInfo(HRESULT_FROM_GetLastError());
goto Exit;
}
// Import the key pair.
if (!CryptImportKey(hProv,
pbKeyBlob,
cbKeyBlob,
0, 0, &hKey)) {
SetStrongNameErrorInfo(HRESULT_FROM_GetLastError());
FreeCSP(hProv);
goto Exit;
}
// Release the CSP.
FreeCSP(hProv);
retVal = TRUE;
Exit:
END_ENTRYPOINT_VOIDRET;
return retVal;
}
// Delete a key pair.
SNAPI StrongNameKeyDelete(LPCWSTR wszKeyContainer) // [in] desired key container name
{
BOOLEAN retVal = FALSE;
BEGIN_ENTRYPOINT_VOIDRET;
HCRYPTPROV hProv;
SNLOG((W("StrongNameKeyDelete(\"%s\")\n"), wszKeyContainer));
SN_COMMON_PROLOG();
if (wszKeyContainer == NULL)
SN_ERROR(E_POINTER);
// Open and delete the named container.
hProv = LocateCSP(wszKeyContainer, SN_DELETE_CONTAINER);
if (hProv) {
// Returned handle isn't actually valid in the delete case, so we're
// finished.
retVal = TRUE;
} else {
SetStrongNameErrorInfo(CORSEC_E_CONTAINER_NOT_FOUND);
retVal = FALSE;
}
Exit:
END_ENTRYPOINT_VOIDRET;
return retVal;
}
// Retrieve the public portion of a key pair.
SNAPI StrongNameGetPublicKey (LPCWSTR wszKeyContainer, // [in] desired key container name
BYTE *pbKeyBlob, // [in] public/private key blob (optional)
ULONG cbKeyBlob,
BYTE **ppbPublicKeyBlob, // [out] public key blob
ULONG *pcbPublicKeyBlob)
{
LIMITED_METHOD_CONTRACT;
BOOLEAN retVal = FALSE;
BEGIN_ENTRYPOINT_VOIDRET;
retVal = StrongNameGetPublicKeyEx(
wszKeyContainer,
pbKeyBlob,
cbKeyBlob,
ppbPublicKeyBlob,
pcbPublicKeyBlob,
0,
0);
END_ENTRYPOINT_VOIDRET;
return retVal;
}
// Holder for any HCRYPTPROV handles allocated by the strong name APIs
typedef Wrapper<HCRYPTPROV, DoNothing, FreeCSP, 0> HandleStrongNameCspHolder;
SNAPI StrongNameGetPublicKeyEx (LPCWSTR wszKeyContainer, // [in] desired key container name
BYTE *pbKeyBlob, // [in] public/private key blob (optional)
ULONG cbKeyBlob,
BYTE **ppbPublicKeyBlob, // [out] public key blob
ULONG *pcbPublicKeyBlob,
ULONG uHashAlgId,
ULONG uReserved) // reserved for future use as uSigAlgId (signature algorithm id)
{
BOOLEAN retVal = FALSE;
BEGIN_ENTRYPOINT_VOIDRET;
HandleStrongNameCspHolder hProv(NULL);
CapiKeyHolder hKey(NULL);
DWORD dwKeyLen;
PublicKeyBlob *pKeyBlob;
DWORD dwSigAlgIdLen;
SNLOG((W("StrongNameGetPublicKeyEx(\"%s\", %08X, %08X, %08X, %08X, %08X)\n"), wszKeyContainer, pbKeyBlob, cbKeyBlob, ppbPublicKeyBlob, pcbPublicKeyBlob, uHashAlgId));
SN_COMMON_PROLOG();
if (wszKeyContainer == NULL && pbKeyBlob == NULL)
SN_ERROR(E_INVALIDARG);
if (pbKeyBlob != NULL && !(StrongNameIsEcmaKey(pbKeyBlob, cbKeyBlob) || StrongNameIsValidKeyPair(pbKeyBlob, cbKeyBlob)))
SN_ERROR(E_INVALIDARG);
if (ppbPublicKeyBlob == NULL)
SN_ERROR(E_POINTER);
if (pcbPublicKeyBlob == NULL)
SN_ERROR(E_POINTER);
if (uReserved != 0)
SN_ERROR(E_INVALIDARG);
bool fHashAlgorithmValid;
fHashAlgorithmValid = uHashAlgId == 0 ||
(GET_ALG_CLASS(uHashAlgId) == ALG_CLASS_HASH && GET_ALG_SID(uHashAlgId) >= ALG_SID_SHA1 && GET_ALG_SID(uHashAlgId) <= ALG_SID_SHA_512);
if(!fHashAlgorithmValid)
SN_ERROR(E_INVALIDARG);
if(uHashAlgId == 0)
uHashAlgId = g_uHashAlgId;
// If we're handed a platform neutral public key, just hand it right back to
// the user. Well, hand back a copy at least.
if (pbKeyBlob && cbKeyBlob && SN_IS_NEUTRAL_KEY(pbKeyBlob)) {
*pcbPublicKeyBlob = sizeof(g_rbNeutralPublicKey);
*ppbPublicKeyBlob = (BYTE*)g_rbNeutralPublicKey;
retVal = TRUE;
goto Exit;
}
// Open a CSP. Create a key container if a public/private key blob is
// provided, otherwise we assume a key container already exists.
if (pbKeyBlob)
hProv = LocateCSP(NULL, SN_IGNORE_CONTAINER);
else
hProv = LocateCSP(wszKeyContainer, SN_OPEN_CONTAINER);
if (!hProv)
goto Error;
// If a key blob was provided, import the key pair into the container.
if (pbKeyBlob) {
if (!CryptImportKey(hProv,
pbKeyBlob,
cbKeyBlob,
0, 0, &hKey))
goto Error;
} else {
#if !defined(FEATURE_CORESYSTEM)
// Else fetch the signature key pair from the container.
if (!CryptGetUserKey(hProv, g_uKeySpec, &hKey))
goto Error;
#else // FEATURE_CORESYSTEM
SetLastError(E_NOTIMPL);
goto Error;
#endif // !FEATURE_CORESYSTEM
}
// Determine the length of the public key part as a blob.
if (!CryptExportKey(hKey, 0, PUBLICKEYBLOB, 0, NULL, &dwKeyLen))
goto Error;
#ifdef _PREFAST_
#pragma warning(push)
#pragma warning(disable:22011) // Suppress this PREFast warning which gets triggered by the offset macro expansion.
#endif
// And then the length of the PublicKeyBlob structure we return to the
// caller.
*pcbPublicKeyBlob = offsetof(PublicKeyBlob, PublicKey) + dwKeyLen;
#ifdef _PREFAST_
#pragma warning(pop)
#endif
// Allocate a large enough buffer.
*ppbPublicKeyBlob = new (nothrow) BYTE[*pcbPublicKeyBlob];
if (*ppbPublicKeyBlob == NULL) {
SetLastError(E_OUTOFMEMORY);
goto Error;
}
pKeyBlob = (PublicKeyBlob*)*ppbPublicKeyBlob;
// Extract the public part as a blob.
if (!CryptExportKey(hKey, 0, PUBLICKEYBLOB, 0, pKeyBlob->PublicKey, &dwKeyLen)) {
delete[] *ppbPublicKeyBlob;
*ppbPublicKeyBlob = NULL;
goto Error;
}
// Extract key's signature algorithm and store it in the key blob.
dwSigAlgIdLen = sizeof(unsigned int);
ALG_ID SigAlgID;
if (!CryptGetKeyParam(hKey, KP_ALGID, (BYTE*)&SigAlgID, &dwSigAlgIdLen, 0)) {
delete[] *ppbPublicKeyBlob;
*ppbPublicKeyBlob = NULL;
goto Error;
}
SET_UNALIGNED_VAL32(&pKeyBlob->SigAlgID, SigAlgID);
// Fill in the other public key blob fields.
SET_UNALIGNED_VAL32(&pKeyBlob->HashAlgID, uHashAlgId);
SET_UNALIGNED_VAL32(&pKeyBlob->cbPublicKey, dwKeyLen);
retVal = TRUE;
goto Exit;
Error:
SetStrongNameErrorInfo(HRESULT_FROM_GetLastError());
Exit:
END_ENTRYPOINT_VOIDRET;
return retVal;
}
// Hash and sign a manifest.
SNAPI StrongNameSignatureGeneration(LPCWSTR wszFilePath, // [in] valid path to the PE file for the assembly
LPCWSTR wszKeyContainer, // [in] desired key container name
BYTE *pbKeyBlob, // [in] public/private key blob (optional)
ULONG cbKeyBlob,
BYTE **ppbSignatureBlob, // [out] signature blob
ULONG *pcbSignatureBlob)
{
BOOL fRetVal = FALSE;
BEGIN_ENTRYPOINT_VOIDRET;
fRetVal = StrongNameSignatureGenerationEx(wszFilePath, wszKeyContainer, pbKeyBlob, cbKeyBlob, ppbSignatureBlob, pcbSignatureBlob, 0);
END_ENTRYPOINT_VOIDRET;
return fRetVal;
}
HRESULT FindAssemblySignaturePublicKey(const SN_LOAD_CTX *pLoadCtx,
__out PublicKeyBlob **ppPublicKey)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
HRESULT hr;
StrongNameBufferHolder<PublicKeyBlob> result = NULL;
IfFailRet(FindPublicKey(pLoadCtx, NULL, 0, &result));
#ifdef FEATURE_STRONGNAME_MIGRATION
PublicKeyBlob *pSignaturePublicKey = NULL;
IfFailRet(GetVerifiedSignatureKey((SN_LOAD_CTX*) pLoadCtx, &pSignaturePublicKey));
if(hr != S_FALSE)
{
result = pSignaturePublicKey;
}
#endif // FEATURE_STRONGNAME_MIGRATION
*ppPublicKey = result.Extract();
return S_OK;
}
SNAPI StrongNameSignatureGenerationEx(LPCWSTR wszFilePath, // [in] valid path to the PE file for the assembly
LPCWSTR wszKeyContainer, // [in] desired key container name
BYTE *pbKeyBlob, // [in] public/private key blob (optional)
ULONG cbKeyBlob,
BYTE **ppbSignatureBlob, // [out] signature blob
ULONG *pcbSignatureBlob,
DWORD dwFlags) // [in] modifer flags
{
BOOLEAN retVal = FALSE;
BEGIN_ENTRYPOINT_VOIDRET;
HandleStrongNameCspHolder hProv(NULL);
CapiHashHolder hHash(NULL);
NewArrayHolder<BYTE> pbSig(NULL);
ULONG cbSig = 0;
SN_LOAD_CTX sLoadCtx;
BOOLEAN bImageLoaded = FALSE;
ALG_ID uHashAlgId;
StrongNameBufferHolder<PublicKeyBlob> pSignatureKey = NULL;
SNLOG((W("StrongNameSignatureGenerationEx(\"%s\", \"%s\", %08X, %08X, %08X, %08X, %08X)\n"), wszFilePath, wszKeyContainer, pbKeyBlob, cbKeyBlob, ppbSignatureBlob, pcbSignatureBlob, dwFlags));
SN_COMMON_PROLOG();
uHashAlgId = g_uHashAlgId;
if (pbKeyBlob != NULL && !StrongNameIsValidKeyPair(pbKeyBlob, cbKeyBlob))
SN_ERROR(E_INVALIDARG);
if (ppbSignatureBlob != NULL && pcbSignatureBlob == NULL)
SN_ERROR(E_POINTER);
if (wszFilePath != NULL) {
// Map the assembly into memory.
sLoadCtx.m_fReadOnly = FALSE;
if (!LoadAssembly(&sLoadCtx, wszFilePath))
goto Error;
bImageLoaded = TRUE;
// If we've asked to recalculate the file hashes of linked modules we have
// to load the metadata engine and search for file references.
if (dwFlags & SN_SIGN_ALL_FILES)
if (!RehashModules(&sLoadCtx, wszFilePath))
goto Error;
// If no key pair is provided, then we were only called to re-compute the hashes of
// linked modules in the assembly.
if (!wszKeyContainer && !pbKeyBlob)
{
retVal = TRUE;
goto Exit;
}
HRESULT hr;
if(FAILED(hr = FindAssemblySignaturePublicKey(&sLoadCtx, &pSignatureKey)))
{
SN_ERROR(hr);
}
// Ecma key has an algorithm of zero, so we ignore that case.
ALG_ID uKeyHashAlgId = GET_UNALIGNED_VAL32(&pSignatureKey->HashAlgID);
if(uKeyHashAlgId != 0)
{
uHashAlgId = uKeyHashAlgId;
}
}
if (wszKeyContainer || pbKeyBlob) { // We have a key pair in a container, or in a blob
// Open a CSP. If a public/private key blob is provided, use CRYPT_VERIFYCONTEXT,
// otherwise we assume the key container already exists.
if (pbKeyBlob)
hProv = LocateCSP(NULL, SN_IGNORE_CONTAINER, uHashAlgId);
else
hProv = LocateCSP(wszKeyContainer, SN_OPEN_CONTAINER, uHashAlgId);
if (hProv.GetValue() == NULL)
goto Error;
// If a key blob was provided, import the key pair into the container.
// This might be the real key or the test-sign key. In the case of test signing,
// there's no way to specify hash algorithm, so we use the one from the
// assembly signature public key (in the metadata table, or the migration attribute).
if (pbKeyBlob) {
// The provider holds a reference to the key, so we don't need to
// keep one around.
CapiKeyHolder hKey(NULL);
if (!CryptImportKey(hProv,
pbKeyBlob,
cbKeyBlob,
0,
0,
&hKey))
goto Error;
}
// Create a hash object.
if (!CryptCreateHash(hProv, uHashAlgId, 0, 0, &hHash))
goto Error;
// Compute size of the signature blob.
if (!CryptSignHashW(hHash, g_uKeySpec, NULL, 0, NULL, &cbSig))
goto Error;
// If the caller only wants the size of the signature, return it now and
// exit.
// RSA signature length is independent of the hash size, so hash algorithm
// doesn't matter here (we don't know the algorithm if the assembly path was passed in as NULL)
if (wszFilePath == NULL) {
*pcbSignatureBlob = cbSig;
retVal = TRUE;
goto Exit;
}
}
// Verify that the public key of the assembly being signed matches the private key we're signing with
if ((wszKeyContainer != NULL || pbKeyBlob != NULL) && !VerifyKeyMatchesAssembly(pSignatureKey, wszKeyContainer, pbKeyBlob, cbKeyBlob, dwFlags))
{
SetLastError(StrongNameErrorInfo());
goto Error;
}
// We set a bit in the header to indicate we're fully signing the assembly.
if (!(dwFlags & SN_TEST_SIGN))
sLoadCtx.m_pCorHeader->Flags |= VAL32(COMIMAGE_FLAGS_STRONGNAMESIGNED);
else
sLoadCtx.m_pCorHeader->Flags &= ~VAL32(COMIMAGE_FLAGS_STRONGNAMESIGNED);
// Destroy the old hash object and create a new one
// because CryptoAPI says you can't reuse a hash once you've signed it
// Note that this seems to work with MS-based CSPs but breaks on
// at least newer nCipher CSPs.
if (!CryptCreateHash(hProv, uHashAlgId, 0, 0, &hHash))
goto Error;
// Compute a hash over the image.
if (!ComputeHash(&sLoadCtx, hHash, CalcHash, NULL))
goto Error;
// Allocate the blob.
pbSig = new (nothrow) BYTE[cbSig];
if (pbSig == NULL) {
SetLastError(E_OUTOFMEMORY);
goto Error;
}
// Compute a signature blob over the hash of the manifest.
if (!CryptSignHashW(hHash, g_uKeySpec, NULL, 0, pbSig, &cbSig))
goto Error;
// Check the signature size
if (sLoadCtx.m_cbSignature != cbSig) {
SetLastError(CORSEC_E_SIGNATURE_MISMATCH);
goto Error;
}
// If the user hasn't asked for the signature to be returned as a pointer, write it to file.
if (!ppbSignatureBlob)
{
memcpy_s(sLoadCtx.m_pbSignature, sLoadCtx.m_cbSignature, pbSig, cbSig);
//
// Memory-mapped IO in Windows doesn't guarantee that it will update
// the file's "Modified" timestamp, so we update it ourselves.
//
_ASSERTE(sLoadCtx.m_hFile != INVALID_HANDLE_VALUE);
FILETIME ft;
SYSTEMTIME st;
GetSystemTime(&st);
// We don't care if updating the timestamp fails for any reason.
if(SystemTimeToFileTime(&st, &ft))
{
SetFileTime(sLoadCtx.m_hFile, (LPFILETIME) NULL, (LPFILETIME) NULL, &ft);
}
}
// Unmap the image (automatically recalculates and updates the image
// checksum).
bImageLoaded = FALSE;
if (!UnloadAssembly(&sLoadCtx))
goto Error;
if (ppbSignatureBlob) {
*ppbSignatureBlob = pbSig.Extract();
*pcbSignatureBlob = cbSig;
}
retVal = TRUE;
goto Exit;
Error:
SetStrongNameErrorInfo(HRESULT_FROM_GetLastError());
Exit:
if (bImageLoaded)
UnloadAssembly(&sLoadCtx);
END_ENTRYPOINT_VOIDRET;
return retVal;
}
//
// Generate the digest of a delay signed assembly, which can be signed with StrongNameDigestSign. The digest
// algorithm is determined from the HashAlgID of the assembly's public key blob.
//
// Parameters:
// wszFilePath - path to the delay signed assembly to generate the digest of
// ppbDigestBlob - on success this will point to a buffer that contains the digest of the wszFilePath
// assembly. This buffer should be freed with StrongNameFreeBuffer.
// pcbDigestBlob - on success this will point to the size of the digest buffer in *ppbDigestBlob
// dwFlags - flags used to control signing. This is the same set of flags used by
// StrongNameSignatureGenerationEx
//
bool StrongNameDigestGenerate_Internal(_In_z_ LPCWSTR wszFilePath,
_Outptr_result_bytebuffer_(*pcbDigestBlob) BYTE** ppbDigestBlob,
_Out_ ULONG* pcbDigestBlob,
DWORD dwFlags)
{
// Load up the assembly and find its public key - this tells us which hash algorithm we need to use
// Note that it cannot be loaded read-only since we need to toggle the fully siged bit in order to
// calculate the correct hash for the signature.
StrongNameAssemblyLoadHolder assembly(wszFilePath, false /* read only */);
if (!assembly.IsLoaded())
{
return false;
}
// If we were asked to do a full rehashing of all modules that needs to be done before calculating the digest
if ((dwFlags & SN_SIGN_ALL_FILES) == SN_SIGN_ALL_FILES)
{
if (!RehashModules(assembly.GetLoadContext(), wszFilePath))
{
return false;
}
}
// During signature verification, the fully signed bit will be set in the assembly's COR header.
// Therefore, when calculating the digest of the assembly we must toggle this bit in order to make the
// digest match what will be calculated during verificaiton. However, we do not want to persist the
// bit flip on disk, since we're not actually signing the assembly now. We'll save the current COR
// flags, flip the bit for digesting, and then restore the COR flags before we finish calculating the
// digest.
class AssemblyFlagsHolder
{
private:
IMAGE_COR20_HEADER* m_pHeader;
DWORD m_originalFlags;
public:
AssemblyFlagsHolder(_In_ IMAGE_COR20_HEADER* pHeader)
: m_pHeader(pHeader),
m_originalFlags(pHeader->Flags)
{
}
~AssemblyFlagsHolder()
{
m_pHeader->Flags = m_originalFlags;
}
} flagsHolder(assembly.GetLoadContext()->m_pCorHeader);
assembly.GetLoadContext()->m_pCorHeader->Flags |= VAL32(COMIMAGE_FLAGS_STRONGNAMESIGNED);
StrongNameBufferHolder<PublicKeyBlob> pPublicKey;
HRESULT hrPublicKey = FindAssemblySignaturePublicKey(assembly.GetLoadContext(), &pPublicKey);
if (FAILED(hrPublicKey))
{
SetStrongNameErrorInfo(hrPublicKey);
return false;
}
// Generate the digest of the assembly
HandleStrongNameCspHolder hProv(LocateCSP(nullptr, SN_IGNORE_CONTAINER, pPublicKey->HashAlgID));
if (!hProv)
{
SetStrongNameErrorInfo(HRESULT_FROM_GetLastError());
return false;
}
CapiHashHolder hHash;
if (!CryptCreateHash(hProv, pPublicKey->HashAlgID, NULL, 0, &hHash))
{
SetStrongNameErrorInfo(HRESULT_FROM_GetLastError());
return false;
}
if (!ComputeHash(assembly.GetLoadContext(), hHash, CalcHash, nullptr))
{
return false;
}
// Figure out how big the resulting digest is so that we can pass it back out
DWORD hashSize = 0;
DWORD dwordSize = sizeof(hashSize);
if (!CryptGetHashParam(hHash, HP_HASHSIZE, reinterpret_cast<BYTE*>(&hashSize), &dwordSize, 0))
{
SetStrongNameErrorInfo(HRESULT_FROM_GetLastError());
return false;
}
StrongNameBufferHolder<BYTE> pbHash(new (nothrow)BYTE[hashSize]);
if (!pbHash)
{
SetStrongNameErrorInfo(E_OUTOFMEMORY);
return false;
}
if (!CryptGetHashParam(hHash, HP_HASHVAL, pbHash, &hashSize, 0))
{
SetStrongNameErrorInfo(HRESULT_FROM_GetLastError());
return false;
}
*ppbDigestBlob = pbHash.Extract();
*pcbDigestBlob = hashSize;
return true;
}
SNAPI StrongNameDigestGenerate(_In_z_ LPCWSTR wszFilePath,
_Outptr_result_bytebuffer_(*pcbDigestBlob) BYTE** ppbDigestBlob,
_Out_ ULONG* pcbDigestBlob,
DWORD dwFlags)
{
BOOLEAN retVal = FALSE;
BEGIN_ENTRYPOINT_VOIDRET;
SNLOG((W("StrongNameDigestGenerate(\"%s\", %08X, %08X, %04X)\n"), wszFilePath, ppbDigestBlob, pcbDigestBlob, dwFlags));
SN_COMMON_PROLOG();
if (wszFilePath == nullptr)
SN_ERROR(E_POINTER);
if (ppbDigestBlob == nullptr)
SN_ERROR(E_POINTER);
if (pcbDigestBlob == nullptr)
SN_ERROR(E_POINTER);
retVal = StrongNameDigestGenerate_Internal(wszFilePath, ppbDigestBlob, pcbDigestBlob, dwFlags);
END_ENTRYPOINT_VOIDRET;
Exit:
return retVal;
}
//
// Sign an the digest of an assembly calculated by StrongNameDigestGenerate
//
// Parameters:
// wszKeyContainer - name of the key container that holds the key pair used to generate the signature. If
// both a key container and key blob are specified, the key container name is ignored.
// pbKeyBlob - raw key pair to be used to generate the signature. If both a key pair and a key
// container are given, the key blob will be used.
// cbKeyBlob - size of the key pair in pbKeyBlob
// pbDigestBlob - digest of the assembly, calculated by StrongNameDigestGenerate
// cbDigestBlob - size of the digest blob
// hashAlgId - algorithm ID of the hash algorithm used to generate the digest blob
// ppbSignatureBlob - on success this will point to a buffer that contains a signature over the blob. This
// buffer should be freed with StrongNameFreeBuffer.
// pcbSignatureBlob - on success this will point to the size of the signature blob in *ppbSignatureBlob
// dwFlags - flags used to control signing. This is the same set of flags used by
// StrongNameSignatureGenerationEx
//
bool StrongNameDigestSign_Internal(_In_opt_z_ LPCWSTR wszKeyContainer,
_In_reads_bytes_opt_(cbKeyBlob) BYTE* pbKeyBlob,
ULONG cbKeyBlob,
_In_reads_bytes_(cbDigestBlob) BYTE* pbDigestBlob,
ULONG cbDigestBlob,
DWORD hashAlgId,
_Outptr_result_bytebuffer_(*pcbSignatureBlob) BYTE** ppbSignatureBlob,
_Out_ ULONG* pcbSignatureBlob,
DWORD dwFlags)
{
//
// Get the key we'll be signing with loaded into CAPI
//
HandleStrongNameCspHolder hProv;
CapiKeyHolder hKey;
if (pbKeyBlob != nullptr)
{
hProv = LocateCSP(nullptr, SN_IGNORE_CONTAINER, hashAlgId);
if (hProv != NULL)
{
if (!CryptImportKey(hProv, pbKeyBlob, cbKeyBlob, 0, 0, &hKey))
{
SetStrongNameErrorInfo(HRESULT_FROM_GetLastError());
return false;
}
}
}
else
{
hProv = LocateCSP(wszKeyContainer, SN_OPEN_CONTAINER, hashAlgId);
}
if (!hProv)
{
SetStrongNameErrorInfo(HRESULT_FROM_GetLastError());
return false;
}
//
// Get the pre-calculated digest loaded into a CAPI Hash object
//
CapiHashHolder hHash;
if (!CryptCreateHash(hProv, hashAlgId, 0, 0, &hHash))
{
SetStrongNameErrorInfo(HRESULT_FROM_GetLastError());
return false;
}
DWORD hashSize = 0;
DWORD cbHashSize = sizeof(hashSize);
if (!CryptGetHashParam(hHash, HP_HASHSIZE, reinterpret_cast<BYTE*>(&hashSize), &cbHashSize, 0))
{
SetStrongNameErrorInfo(HRESULT_FROM_GetLastError());
return false;
}
if (hashSize != cbDigestBlob)
{
SetStrongNameErrorInfo(NTE_BAD_HASH);
return false;
}
if (!CryptSetHashParam(hHash, HP_HASHVAL, pbDigestBlob, 0))
{
SetStrongNameErrorInfo(HRESULT_FROM_GetLastError());
return false;
}
//
// Sign the hash
//
DWORD cbSignature = 0;
if (!CryptSignHashW(hHash, g_uKeySpec, nullptr, 0, nullptr, &cbSignature))
{
SetStrongNameErrorInfo(HRESULT_FROM_GetLastError());
return false;
}
// CAPI has a quirk where some CSPs do not allow you to sign a hash object once you've asked for the size
// of the signature. To work in those cases, we must create a new hash object to sign.
if (!CryptCreateHash(hProv, hashAlgId, 0, 0, &hHash))
{
SetStrongNameErrorInfo(HRESULT_FROM_GetLastError());
return false;
}
if (!CryptGetHashParam(hHash, HP_HASHSIZE, reinterpret_cast<BYTE*>(&hashSize), &cbHashSize, 0))
{
SetStrongNameErrorInfo(HRESULT_FROM_GetLastError());
return false;
}
if (hashSize != cbDigestBlob)
{
SetStrongNameErrorInfo(NTE_BAD_HASH);
return false;
}
if (!CryptSetHashParam(hHash, HP_HASHVAL, pbDigestBlob, 0))
{
SetStrongNameErrorInfo(HRESULT_FROM_GetLastError());
return false;
}
// Now that we've got a fresh hash object to sign, we can compute the final signature
StrongNameBufferHolder<BYTE> pbSignature(new (nothrow)BYTE[cbSignature]);
if (pbSignature == nullptr)
{
SetStrongNameErrorInfo(E_OUTOFMEMORY);
return false;
}
if (!CryptSignHashW(hHash, g_uKeySpec, nullptr, 0, pbSignature, &cbSignature))
{
SetStrongNameErrorInfo(HRESULT_FROM_GetLastError());
return false;
}
*ppbSignatureBlob = pbSignature.Extract();
*pcbSignatureBlob = cbSignature;
return true;
}
SNAPI StrongNameDigestSign(_In_opt_z_ LPCWSTR wszKeyContainer,
_In_reads_bytes_opt_(cbKeyBlob) BYTE* pbKeyBlob,
ULONG cbKeyBlob,
_In_reads_bytes_(cbDigestBlob) BYTE* pbDigestBlob,
ULONG cbDigestBlob,
DWORD hashAlgId,
_Outptr_result_bytebuffer_(*pcbSignatureBlob) BYTE** ppbSignatureBlob,
_Out_ ULONG* pcbSignatureBlob,
DWORD dwFlags)
{
BOOLEAN retVal = FALSE;
BEGIN_ENTRYPOINT_VOIDRET;
SNLOG((W("StrongNameDigestSign(\"%s\", %08X, %04X, %08X, %04X, %04X, %08X, %08X, %04X)\n"), wszKeyContainer, pbKeyBlob, cbKeyBlob, pbDigestBlob, cbDigestBlob, hashAlgId, ppbSignatureBlob, pcbSignatureBlob, dwFlags));
SN_COMMON_PROLOG();
if (wszKeyContainer == nullptr && pbKeyBlob == nullptr)
SN_ERROR(E_POINTER);
if (pbKeyBlob != nullptr && !StrongNameIsValidKeyPair(pbKeyBlob, cbKeyBlob))
SN_ERROR(E_INVALIDARG);
if (pbDigestBlob == nullptr)
SN_ERROR(E_POINTER);
if (ppbSignatureBlob == nullptr)
SN_ERROR(E_POINTER);
if (pcbSignatureBlob == nullptr)
SN_ERROR(E_POINTER);
*ppbSignatureBlob = nullptr;
*pcbSignatureBlob = 0;
retVal = StrongNameDigestSign_Internal(wszKeyContainer, pbKeyBlob, cbKeyBlob, pbDigestBlob, cbDigestBlob, hashAlgId, ppbSignatureBlob, pcbSignatureBlob, dwFlags);
END_ENTRYPOINT_VOIDRET;
Exit:
return retVal;
}
//
// Embed a digest signature generated with StrongNameDigestSign into a delay signed assembly, completing
// the signing process for that assembly.
//
// Parameters:
// wszFilePath - path to the assembly to sign
// pbSignatureBlob - signature blob to embed in the assembly
// cbSignatureBlob - size of the signature blob
//
bool StrongNameDigestEmbed_Internal(_In_z_ LPCWSTR wszFilePath,
_In_reads_bytes_(cbSignatureBlob) BYTE* pbSignatureBlob,
ULONG cbSignatureBlob)
{
StrongNameAssemblyLoadHolder assembly(wszFilePath, false);
if (!assembly.IsLoaded())
{
SetStrongNameErrorInfo(HRESULT_FROM_GetLastError());
return false;
}
memcpy_s(assembly.GetLoadContext()->m_pbSignature, assembly.GetLoadContext()->m_cbSignature, pbSignatureBlob, cbSignatureBlob);
assembly.GetLoadContext()->m_pCorHeader->Flags |= VAL32(COMIMAGE_FLAGS_STRONGNAMESIGNED);
FILETIME ft = { 0 };
SYSTEMTIME st = { 0 };
GetSystemTime(&st);
if (SystemTimeToFileTime(&st, &ft))
{
SetFileTime(assembly.GetLoadContext()->m_hFile, nullptr, nullptr, &ft);
}
return true;
}
SNAPI StrongNameDigestEmbed(_In_z_ LPCWSTR wszFilePath, // [in] valid path to the PE file for the assembly to update
_In_reads_bytes_(cbSignatureBlob) BYTE* pbSignatureBlob, // [in] signatuer blob for the assembly
ULONG cbSignatureBlob)
{
BOOLEAN retVal = FALSE;
BEGIN_ENTRYPOINT_VOIDRET;
SNLOG((W("StrongNameDigestEmbed(\"%s\", %08X, %04X)\n"), wszFilePath, pbSignatureBlob, cbSignatureBlob));
SN_COMMON_PROLOG();
if (wszFilePath == nullptr)
SN_ERROR(E_POINTER);
if (pbSignatureBlob == nullptr)
SN_ERROR(E_POINTER);
retVal = StrongNameDigestEmbed_Internal(wszFilePath, pbSignatureBlob, cbSignatureBlob);
END_ENTRYPOINT_VOIDRET;
Exit:
return retVal;
}
// Create a strong name token from an assembly file.
SNAPI StrongNameTokenFromAssembly(LPCWSTR wszFilePath, // [in] valid path to the PE file for the assembly
BYTE **ppbStrongNameToken, // [out] strong name token
ULONG *pcbStrongNameToken)
{
BOOL fRetValue = FALSE;
BEGIN_ENTRYPOINT_VOIDRET;
fRetValue = StrongNameTokenFromAssemblyEx(wszFilePath,
ppbStrongNameToken,
pcbStrongNameToken,
NULL,
NULL);
END_ENTRYPOINT_VOIDRET;
return fRetValue;
}
// Create a strong name token from an assembly file and additionally return the full public key.
SNAPI StrongNameTokenFromAssemblyEx(LPCWSTR wszFilePath, // [in] valid path to the PE file for the assembly
BYTE **ppbStrongNameToken, // [out] strong name token
ULONG *pcbStrongNameToken,
BYTE **ppbPublicKeyBlob, // [out] public key blob
ULONG *pcbPublicKeyBlob)
{
BOOLEAN retVal = FALSE;
BEGIN_ENTRYPOINT_VOIDRET;
SN_LOAD_CTX sLoadCtx;
BOOLEAN fMapped = FALSE;
BOOLEAN fSetErrorInfo = TRUE;
PublicKeyBlob *pPublicKey = NULL;
HRESULT hrKey = S_OK;
SNLOG((W("StrongNameTokenFromAssemblyEx(\"%s\", %08X, %08X, %08X, %08X)\n"), wszFilePath, ppbStrongNameToken, pcbStrongNameToken, ppbPublicKeyBlob, pcbPublicKeyBlob));
SN_COMMON_PROLOG();
if (wszFilePath == NULL)
SN_ERROR(E_POINTER);
if (ppbStrongNameToken == NULL)
SN_ERROR(E_POINTER);
if (pcbStrongNameToken == NULL)
SN_ERROR(E_POINTER);
// Map the assembly into memory.
sLoadCtx.m_fReadOnly = TRUE;
if (!LoadAssembly(&sLoadCtx, wszFilePath))
goto Error;
fMapped = TRUE;
// Read the public key used to sign the assembly from the assembly metadata.
hrKey = FindPublicKey(&sLoadCtx, NULL, 0, &pPublicKey);
if (FAILED(hrKey))
{
SetStrongNameErrorInfo(hrKey);
fSetErrorInfo = FALSE;
goto Error;
}
// Unload the assembly.
fMapped = FALSE;
if (!UnloadAssembly(&sLoadCtx))
goto Error;
// Now we have a public key blob, we can call our more direct API to do the
// actual work.
if (!StrongNameTokenFromPublicKey((BYTE*)pPublicKey,
SN_SIZEOF_KEY(pPublicKey),
ppbStrongNameToken,
pcbStrongNameToken)) {
fSetErrorInfo = FALSE;
goto Error;
}
if (pcbPublicKeyBlob)
*pcbPublicKeyBlob = SN_SIZEOF_KEY(pPublicKey);
// Return public key information.
if (ppbPublicKeyBlob)
*ppbPublicKeyBlob = (BYTE*)pPublicKey;
else
delete [] (BYTE*)pPublicKey;
retVal = TRUE;
goto Exit;
Error:
if (fSetErrorInfo)
SetStrongNameErrorInfo(HRESULT_FROM_GetLastError());
if (pPublicKey)
delete [] (BYTE*)pPublicKey;
if (fMapped)
UnloadAssembly(&sLoadCtx);
Exit:
END_ENTRYPOINT_VOIDRET;
return retVal;
}
bool StrongNameSignatureVerificationEx2_Internal(LPCWSTR wszFilePath,
BOOLEAN fForceVerification,
BYTE *pbEcmaPublicKey,
DWORD cbEcmaPublicKey,
BOOLEAN *pfWasVerified)
{
StrongNameAssemblyLoadHolder assembly(wszFilePath, true);
if (!assembly.IsLoaded())
{
SetStrongNameErrorInfo(HRESULT_FROM_GetLastError());
return false;
}
else
{
DWORD dwOutFlags = 0;
HRESULT hrVerify = VerifySignature(assembly.GetLoadContext(),
SN_INFLAG_INSTALL | SN_INFLAG_ALL_ACCESS | (fForceVerification ? SN_INFLAG_FORCE_VER : 0),
reinterpret_cast<PublicKeyBlob *>(pbEcmaPublicKey),
&dwOutFlags);
if (FAILED(hrVerify))
{
SetStrongNameErrorInfo(hrVerify);
return false;
}
if (pfWasVerified)
{
*pfWasVerified = (dwOutFlags & SN_OUTFLAG_WAS_VERIFIED) != 0;
}
return true;
}
}
//
// Verify the signature of a strongly named assembly, providing a mapping from the ECMA key to a real key
//
// Arguments:
// wszFilePath - valid path to the PE file for the assembly
// fForceVerification - verify even if settings in the registry disable it
// pbEcmaPublicKey - mapping from the ECMA public key to the real key used for verification
// cbEcmaPublicKey - length of the real ECMA public key
// fWasVerified - [out] set to false if verify succeeded due to registry settings
//
// Return Value:
// TRUE if the signature was successfully verified, FALSE otherwise
//
SNAPI StrongNameSignatureVerificationEx2(LPCWSTR wszFilePath,
BOOLEAN fForceVerification,
BYTE *pbEcmaPublicKey,
DWORD cbEcmaPublicKey,
BOOLEAN *pfWasVerified)
{
BOOLEAN retVal = FALSE;
BEGIN_ENTRYPOINT_VOIDRET;
SNLOG((W("StrongNameSignatureVerificationEx2(\"%s\", %d, %08X, %08X, %08X)\n"), wszFilePath, fForceVerification, pbEcmaPublicKey, cbEcmaPublicKey, pfWasVerified));
SN_COMMON_PROLOG();
if (wszFilePath == NULL)
SN_ERROR(E_POINTER);
if (pbEcmaPublicKey == NULL)
SN_ERROR(E_POINTER);
if (!StrongNameIsValidPublicKey(pbEcmaPublicKey, cbEcmaPublicKey, false))
SN_ERROR(CORSEC_E_INVALID_PUBLICKEY);
retVal = StrongNameSignatureVerificationEx2_Internal(wszFilePath, fForceVerification, pbEcmaPublicKey, cbEcmaPublicKey, pfWasVerified);
Exit:
END_ENTRYPOINT_VOIDRET;
return retVal;
}
// Verify a strong name/manifest against a public key blob.
SNAPI StrongNameSignatureVerificationEx(LPCWSTR wszFilePath, // [in] valid path to the PE file for the assembly
BOOLEAN fForceVerification, // [in] verify even if settings in the registry disable it
BOOLEAN *pfWasVerified) // [out] set to false if verify succeeded due to registry settings
{
BOOLEAN fRet = FALSE;
BEGIN_ENTRYPOINT_VOIDRET;
fRet = StrongNameSignatureVerificationEx2(wszFilePath,
fForceVerification,
const_cast<BYTE *>(g_rbTheKey),
COUNTOF(g_rbTheKey),
pfWasVerified);
END_ENTRYPOINT_VOIDRET;
return fRet;
}
// Verify a strong name/manifest against a public key blob.
SNAPI StrongNameSignatureVerification(LPCWSTR wszFilePath, // [in] valid path to the PE file for the assembly
DWORD dwInFlags, // [in] flags modifying behaviour
DWORD *pdwOutFlags) // [out] additional output info
{
BOOLEAN retVal = TRUE;
BEGIN_ENTRYPOINT_VOIDRET;
SN_LOAD_CTX sLoadCtx;
BOOLEAN fMapped = FALSE;
SNLOG((W("StrongNameSignatureVerification(\"%s\", %08X, %08X, %08X)\n"), wszFilePath, dwInFlags, pdwOutFlags));
SN_COMMON_PROLOG();
if (wszFilePath == NULL)
SN_ERROR(E_POINTER);
// Map the assembly into memory.
sLoadCtx.m_fReadOnly = TRUE;
if (LoadAssembly(&sLoadCtx, wszFilePath))
{
fMapped = TRUE;
}
else
{
SetStrongNameErrorInfo(HRESULT_FROM_GetLastError());
retVal = FALSE;
}
// Go to common code to process the verification.
if (fMapped)
{
HRESULT hrVerify = VerifySignature(&sLoadCtx, dwInFlags, reinterpret_cast<PublicKeyBlob *>(const_cast<BYTE *>(g_rbTheKey)), pdwOutFlags);
if (FAILED(hrVerify))
{
SetStrongNameErrorInfo(hrVerify);
retVal = FALSE;
}
// Unmap the image. Only set error information if VerifySignature succeeded, since we do not want to
// overwrite its error information with the error code from UnloadAssembly.
if (!UnloadAssembly(&sLoadCtx))
{
if (retVal)
SetStrongNameErrorInfo(HRESULT_FROM_GetLastError());
retVal = FALSE;
}
}
// SN_COMMON_PROLOG requires an Exit location
Exit:
END_ENTRYPOINT_VOIDRET;
return retVal;
}
// Verify a strong name/manifest against a public key blob when the assembly is
// already memory mapped.
SNAPI StrongNameSignatureVerificationFromImage(BYTE *pbBase, // [in] base address of mapped manifest file
DWORD dwLength, // [in] length of mapped image in bytes
DWORD dwInFlags, // [in] flags modifying behaviour
DWORD *pdwOutFlags) // [out] additional output info
{
BOOLEAN retVal = TRUE;
BEGIN_ENTRYPOINT_VOIDRET
SN_LOAD_CTX sLoadCtx;
BOOLEAN fMapped = FALSE;
SNLOG((W("StrongNameSignatureVerificationFromImage(%08X, %08X, %08X, %08X)\n"), pbBase, dwLength, dwInFlags, pdwOutFlags));
SN_COMMON_PROLOG();
if (pbBase == NULL)
SN_ERROR(E_POINTER);
// We don't need to map the image, it's already in memory. But we do need to
// set up a load context for some of the following routines. LoadAssembly
// copes with this case for us.
sLoadCtx.m_pbBase = pbBase;
sLoadCtx.m_dwLength = dwLength;
sLoadCtx.m_fReadOnly = TRUE;
if (LoadAssembly(&sLoadCtx, NULL, dwInFlags))
{
fMapped = TRUE;
}
else
{
SetStrongNameErrorInfo(HRESULT_FROM_GetLastError());
retVal = FALSE;
}
if (fMapped)
{
// Go to common code to process the verification.
HRESULT hrVerify = VerifySignature(&sLoadCtx, dwInFlags, reinterpret_cast<PublicKeyBlob *>(const_cast<BYTE *>(g_rbTheKey)), pdwOutFlags);
if (FAILED(hrVerify))
{
SetStrongNameErrorInfo(hrVerify);
retVal = FALSE;
}
// Unmap the image.
if (!UnloadAssembly(&sLoadCtx))
{
SetStrongNameErrorInfo(HRESULT_FROM_GetLastError());
retVal = FALSE;
}
}
// SN_COMMON_PROLOG requires an Exit location
Exit:
END_ENTRYPOINT_VOIDRET;
return retVal;
}
// Find portions of an assembly to hash.
BOOLEAN CollectBlob(SN_LOAD_CTX *pLoadCtx, PBYTE pbBlob, DWORD* pcbBlob)
{
// Calculate the required size
DWORD cbRequired = 0;
BOOLEAN bRetval = ComputeHash(pLoadCtx, (HCRYPTHASH)INVALID_HANDLE_VALUE, CalculateSize, &cbRequired);
if (!bRetval)
return FALSE;
if (*pcbBlob < cbRequired) {
*pcbBlob = cbRequired;
SetLastError( E_INVALIDARG );
return FALSE;
}
CopyDataBufferDesc buffer = { pbBlob, *pcbBlob };
if (!ComputeHash(pLoadCtx, (HCRYPTHASH)INVALID_HANDLE_VALUE, CopyData, &buffer))
return FALSE;
*pcbBlob = cbRequired;
return TRUE;
}
// ensure that the symbol will be exported properly
extern "C" SNAPI StrongNameGetBlob(LPCWSTR wszFilePath,
PBYTE pbBlob,
DWORD *cbBlob);
SNAPI StrongNameGetBlob(LPCWSTR wszFilePath, // [in] valid path to the PE file for the assembly
PBYTE pbBlob, // [in] buffer to fill with blob
DWORD *cbBlob) // [in/out] size of buffer/number of bytes put into buffer
{
BOOLEAN retVal = FALSE;
BEGIN_ENTRYPOINT_VOIDRET;
SN_LOAD_CTX sLoadCtx;
BOOLEAN fMapped = FALSE;
SNLOG((W("StrongNameGetBlob(\"%s\", %08X, %08X)\n"), wszFilePath, pbBlob, cbBlob));
SN_COMMON_PROLOG();
if (wszFilePath == NULL)
SN_ERROR(E_POINTER);
if (pbBlob == NULL)
SN_ERROR(E_POINTER);
if (cbBlob == NULL)
SN_ERROR(E_POINTER);
// Map the assembly into memory.
sLoadCtx.m_fReadOnly = TRUE;
if (!LoadAssembly(&sLoadCtx, wszFilePath, 0, FALSE))
goto Error;
fMapped = TRUE;
if (!CollectBlob(&sLoadCtx, pbBlob, cbBlob))
goto Error;
// Unmap the image.
fMapped = FALSE;
if (!UnloadAssembly(&sLoadCtx))
goto Error;
retVal = TRUE;
goto Exit;
Error:
SetStrongNameErrorInfo(HRESULT_FROM_GetLastError());
if (fMapped)
UnloadAssembly(&sLoadCtx);
Exit:
END_ENTRYPOINT_VOIDRET;
return retVal;
}
// ensure that the symbol will be exported properly
extern "C" SNAPI StrongNameGetBlobFromImage(BYTE *pbBase,
DWORD dwLength,
PBYTE pbBlob,
DWORD *cbBlob);
SNAPI StrongNameGetBlobFromImage(BYTE *pbBase, // [in] base address of mapped manifest file
DWORD dwLength, // [in] length of mapped image in bytes
PBYTE pbBlob, // [in] buffer to fill with blob
DWORD *cbBlob) // [in/out] size of buffer/number of bytes put into buffer
{
BOOLEAN retVal = FALSE;
BEGIN_ENTRYPOINT_VOIDRET;
SN_LOAD_CTX sLoadCtx;
BOOLEAN fMapped = FALSE;
SNLOG((W("StrongNameGetBlobFromImage(%08X, %08X, %08X, %08X)\n"), pbBase, dwLength, pbBlob, cbBlob));
SN_COMMON_PROLOG();
if (pbBase == NULL)
SN_ERROR(E_POINTER);
if (pbBlob == NULL)
SN_ERROR(E_POINTER);
if (cbBlob == NULL)
SN_ERROR(E_POINTER);
// We don't need to map the image, it's already in memory. But we do need to
// set up a load context for some of the following routines. LoadAssembly
// copes with this case for us.
sLoadCtx.m_pbBase = pbBase;
sLoadCtx.m_dwLength = dwLength;
sLoadCtx.m_fReadOnly = TRUE;
if (!LoadAssembly(&sLoadCtx, NULL, 0, FALSE))
goto Error;
fMapped = TRUE;
// Go to common code to process the verification.
if (!CollectBlob(&sLoadCtx, pbBlob, cbBlob))
goto Error;
// Unmap the image.
fMapped = FALSE;
if (!UnloadAssembly(&sLoadCtx))
goto Error;
retVal = TRUE;
goto Exit;
Error:
SetStrongNameErrorInfo(HRESULT_FROM_GetLastError());
if (fMapped)
UnloadAssembly(&sLoadCtx);
Exit:
END_ENTRYPOINT_VOIDRET;
return retVal;
}
// Verify that two assemblies differ only by signature blob.
SNAPI StrongNameCompareAssemblies(LPCWSTR wszAssembly1, // [in] file name of first assembly
LPCWSTR wszAssembly2, // [in] file name of second assembly
DWORD *pdwResult) // [out] result of comparison
{
BOOLEAN retVal = FALSE;
BEGIN_ENTRYPOINT_VOIDRET;
SN_LOAD_CTX sLoadCtx1;
SN_LOAD_CTX sLoadCtx2;
size_t dwSkipOffsets[3];
size_t dwSkipLengths[3];
BOOLEAN bMappedAssem1 = FALSE;
BOOLEAN bMappedAssem2 = FALSE;
BOOLEAN bIdentical;
BOOLEAN bSkipping;
DWORD i, j;
SNLOG((W("StrongNameCompareAssemblies(\"%s\", \"%s\", %08X)\n"), wszAssembly1, wszAssembly2, pdwResult));
SN_COMMON_PROLOG();
if (wszAssembly1 == NULL)
SN_ERROR(E_POINTER);
if (wszAssembly2 == NULL)
SN_ERROR(E_POINTER);
if (pdwResult == NULL)
SN_ERROR(E_POINTER);
// Map each assembly.
sLoadCtx1.m_fReadOnly = TRUE;
if (!LoadAssembly(&sLoadCtx1, wszAssembly1))
goto Error;
bMappedAssem1 = TRUE;
sLoadCtx2.m_fReadOnly = TRUE;
if (!LoadAssembly(&sLoadCtx2, wszAssembly2))
goto Error;
bMappedAssem2 = TRUE;
// If the files aren't even the same length then they must be different.
if (sLoadCtx1.m_dwLength != sLoadCtx2.m_dwLength)
goto ImagesDiffer;
// Check that the signatures are located at the same offset and are the same
// length in each assembly.
if (sLoadCtx1.m_pCorHeader->StrongNameSignature.VirtualAddress !=
sLoadCtx2.m_pCorHeader->StrongNameSignature.VirtualAddress)
goto ImagesDiffer;
if (sLoadCtx1.m_pCorHeader->StrongNameSignature.Size !=
sLoadCtx2.m_pCorHeader->StrongNameSignature.Size)
goto ImagesDiffer;
// Set up list of image ranges to skip in the upcoming comparison.
// First there's the signature blob.
dwSkipOffsets[0] = sLoadCtx1.m_pbSignature - sLoadCtx1.m_pbBase;
dwSkipLengths[0] = sLoadCtx1.m_cbSignature;
// Then there's the checksum.
if (sLoadCtx1.m_pNtHeaders->OptionalHeader.Magic != sLoadCtx2.m_pNtHeaders->OptionalHeader.Magic)
goto ImagesDiffer;
if (sLoadCtx1.m_pNtHeaders->OptionalHeader.Magic == VAL16(IMAGE_NT_OPTIONAL_HDR32_MAGIC))
dwSkipOffsets[1] = (BYTE*)&((IMAGE_NT_HEADERS32*)sLoadCtx1.m_pNtHeaders)->OptionalHeader.CheckSum - sLoadCtx1.m_pbBase;
else if (sLoadCtx1.m_pNtHeaders->OptionalHeader.Magic == VAL16(IMAGE_NT_OPTIONAL_HDR64_MAGIC))
dwSkipOffsets[1] = (BYTE*)&((IMAGE_NT_HEADERS64*)sLoadCtx1.m_pNtHeaders)->OptionalHeader.CheckSum - sLoadCtx1.m_pbBase;
else {
SetLastError(CORSEC_E_INVALID_IMAGE_FORMAT);
goto Error;
}
dwSkipLengths[1] = sizeof(DWORD);
// Skip the COM+ 2.0 PE header extension flags field. It's updated by the
// signing operation.
dwSkipOffsets[2] = (BYTE*)&sLoadCtx1.m_pCorHeader->Flags - sLoadCtx1.m_pbBase;
dwSkipLengths[2] = sizeof(DWORD);
// Compare the two mapped images, skipping the ranges we defined above.
bIdentical = TRUE;
for (i = 0; i < sLoadCtx1.m_dwLength; i++) {
// Determine if we're skipping the check on the current byte.
bSkipping = FALSE;
for (j = 0; j < (sizeof(dwSkipOffsets) / sizeof(dwSkipOffsets[0])); j++)
if ((i >= dwSkipOffsets[j]) && (i < (dwSkipOffsets[j] + dwSkipLengths[j]))) {
bSkipping = TRUE;
break;
}
// Perform comparisons as desired.
if (sLoadCtx1.m_pbBase[i] != sLoadCtx2.m_pbBase[i])
if (bSkipping)
bIdentical = FALSE;
else
goto ImagesDiffer;
}
// The assemblies are the same.
*pdwResult = bIdentical ? SN_CMP_IDENTICAL : SN_CMP_SIGONLY;
UnloadAssembly(&sLoadCtx1);
UnloadAssembly(&sLoadCtx2);
retVal = TRUE;
goto Exit;
Error:
SetStrongNameErrorInfo(HRESULT_FROM_GetLastError());
if (bMappedAssem1)
UnloadAssembly(&sLoadCtx1);
if (bMappedAssem2)
UnloadAssembly(&sLoadCtx2);
goto Exit;
ImagesDiffer:
if (bMappedAssem1)
UnloadAssembly(&sLoadCtx1);
if (bMappedAssem2)
UnloadAssembly(&sLoadCtx2);
*pdwResult = SN_CMP_DIFFERENT;
retVal = TRUE;
Exit:
END_ENTRYPOINT_VOIDRET;
return retVal;
}
// Compute the size of buffer needed to hold a hash for a given hash algorithm.
SNAPI StrongNameHashSize(ULONG ulHashAlg, // [in] hash algorithm
DWORD *pcbSize) // [out] size of the hash in bytes
{
BOOLEAN retVal = FALSE;
BEGIN_ENTRYPOINT_VOIDRET;
HCRYPTPROV hProv = NULL;
HCRYPTHASH hHash = NULL;
DWORD dwSize;
SNLOG((W("StrongNameHashSize(%08X, %08X)\n"), ulHashAlg, pcbSize));
SN_COMMON_PROLOG();
if (pcbSize == NULL)
SN_ERROR(E_POINTER);
// Default hashing algorithm ID if necessary.
if (ulHashAlg == 0)
ulHashAlg = CALG_SHA1;
// Find a CSP supporting the required algorithm.
hProv = LocateCSP(NULL, SN_IGNORE_CONTAINER, ulHashAlg);
if (!hProv)
goto Error;
// Create a hash object.
if (!CryptCreateHash(hProv, ulHashAlg, 0, 0, &hHash))
goto Error;
// And ask for the size of the hash.
dwSize = sizeof(DWORD);
if (!CryptGetHashParam(hHash, HP_HASHSIZE, (BYTE*)pcbSize, &dwSize, 0))
goto Error;
// Cleanup and exit.
CryptDestroyHash(hHash);
FreeCSP(hProv);
retVal = TRUE;
goto Exit;
Error:
SetStrongNameErrorInfo(HRESULT_FROM_GetLastError());
if (hHash)
CryptDestroyHash(hHash);
if (hProv)
FreeCSP(hProv);
Exit:
END_ENTRYPOINT_VOIDRET;
return retVal;
}
// Compute the size that needs to be allocated for a signature in an assembly.
SNAPI StrongNameSignatureSize(BYTE *pbPublicKeyBlob, // [in] public key blob
ULONG cbPublicKeyBlob,
DWORD *pcbSize) // [out] size of the signature in bytes
{
BOOLEAN retVal = FALSE;
BEGIN_ENTRYPOINT_VOIDRET;
PublicKeyBlob *pPublicKey = (PublicKeyBlob*)pbPublicKeyBlob;
ALG_ID uHashAlgId;
ALG_ID uSignAlgId;
HCRYPTPROV hProv = NULL;
HCRYPTHASH hHash = NULL;
HCRYPTKEY hKey = NULL;
LPCWSTR wszKeyContainer = NULL;
BOOLEAN bTempContainer = FALSE;
DWORD dwKeyLen;
DWORD dwBytes;
SNLOG((W("StrongNameSignatureSize(%08X, %08X, %08X)\n"), pbPublicKeyBlob, cbPublicKeyBlob, pcbSize));
SN_COMMON_PROLOG();
if (pbPublicKeyBlob == NULL)
SN_ERROR(E_POINTER);
if (!StrongNameIsValidPublicKey(pbPublicKeyBlob, cbPublicKeyBlob, false))
SN_ERROR(CORSEC_E_INVALID_PUBLICKEY);
if (pcbSize == NULL)
SN_ERROR(E_POINTER);
// Special case neutral key.
if (SN_IS_NEUTRAL_KEY(pPublicKey))
pPublicKey = SN_THE_KEY();
// Determine hashing/signing algorithms.
uHashAlgId = GET_UNALIGNED_VAL32(&pPublicKey->HashAlgID);
uSignAlgId = GET_UNALIGNED_VAL32(&pPublicKey->SigAlgID);
// Default hashing and signing algorithm IDs if necessary.
if (uHashAlgId == 0)
uHashAlgId = CALG_SHA1;
if (uSignAlgId == 0)
uSignAlgId = CALG_RSA_SIGN;
// Create a temporary key container name.
if (!GetKeyContainerName(&wszKeyContainer, &bTempContainer))
goto Exit;
// Find a CSP supporting the required algorithms and create a temporary key
// container.
hProv = LocateCSP(wszKeyContainer, SN_CREATE_CONTAINER, uHashAlgId, uSignAlgId);
if (!hProv)
goto Error;
// Import the public key (we need to do this in order to determine the key
// length reliably).
if (!CryptImportKey(hProv,
pPublicKey->PublicKey,
GET_UNALIGNED_VAL32(&pPublicKey->cbPublicKey),
0, 0, &hKey))
goto Error;
// Query the key attributes (it's the length we're interested in).
dwBytes = sizeof(dwKeyLen);
if (!CryptGetKeyParam(hKey, KP_KEYLEN, (BYTE*)&dwKeyLen, &dwBytes, 0))
goto Error;
// Delete the key container.
if (LocateCSP(wszKeyContainer, SN_DELETE_CONTAINER) == NULL) {
SetLastError(CORSEC_E_CONTAINER_NOT_FOUND);
goto Error;
}
// Take shortcut for the typical case
if ((uSignAlgId == CALG_RSA_SIGN) && (dwKeyLen % 8 == 0)) {
// The signature size known for CALG_RSA_SIGN
*pcbSize = dwKeyLen / 8;
}
else {
// Recreate the container so we can create a temporary key pair.
hProv = LocateCSP(wszKeyContainer, SN_CREATE_CONTAINER, uHashAlgId, uSignAlgId);
if (!hProv)
goto Error;
// Create the temporary key pair.
if (!CryptGenKey(hProv, g_uKeySpec, dwKeyLen << 16, &hKey))
goto Error;
// Create a hash.
if (!CryptCreateHash(hProv, uHashAlgId, 0, 0, &hHash))
goto Error;
// Compute size of the signature blob.
if (!CryptSignHashW(hHash, g_uKeySpec, NULL, 0, NULL, pcbSize))
goto Error;
CryptDestroyHash(hHash);
if (bTempContainer)
LocateCSP(wszKeyContainer, SN_DELETE_CONTAINER);
}
SNLOG((W("Signature size for hashalg %08X, %08X key (%08X bits) is %08X bytes\n"), uHashAlgId, uSignAlgId, dwKeyLen, *pcbSize));
CryptDestroyKey(hKey);
FreeCSP(hProv);
FreeKeyContainerName(wszKeyContainer, bTempContainer);
retVal = TRUE;
goto Exit;
Error:
SetStrongNameErrorInfo(HRESULT_FROM_GetLastError());
if (hHash)
CryptDestroyHash(hHash);
if (hKey)
CryptDestroyKey(hKey);
if (hProv)
FreeCSP(hProv);
if (bTempContainer)
LocateCSP(wszKeyContainer, SN_DELETE_CONTAINER);
FreeKeyContainerName(wszKeyContainer, bTempContainer);
Exit:
END_ENTRYPOINT_VOIDRET;
return retVal;
}
// Locate CSP based on criteria specified in the registry (CSP name etc).
// Optionally create or delete a named key container within that CSP.
HCRYPTPROV LocateCSP(LPCWSTR wszKeyContainer,
DWORD dwAction,
ALG_ID uHashAlgId,
ALG_ID uSignAlgId)
{
DWORD i;
DWORD dwType;
WCHAR wszName[SN_MAX_CSP_NAME + 1];
DWORD dwNameLength;
HCRYPTPROV hProv;
BOOLEAN bFirstAlg;
BOOLEAN bFoundHash;
BOOLEAN bFoundSign;
PROV_ENUMALGS rAlgs;
HCRYPTPROV hRetProv;
DWORD dwAlgsLen;
DWORD dwProvType = g_uProvType;
// If a CSP name has been provided (and we're not opening a CSP just to do a
// SHA1 hash or a verification), open the CSP directly.
if (g_bHasCSPName &&
(dwAction != SN_HASH_SHA1_ONLY))
{
if (StrongNameCryptAcquireContext(&hProv,
wszKeyContainer ? wszKeyContainer : NULL,
g_wszCSPName,
dwProvType,
SN_CAC_FLAGS(dwAction)))
return (dwAction == SN_DELETE_CONTAINER) ? (HCRYPTPROV)~0 : hProv;
else {
SNLOG((W("Failed to open CSP '%s': %08X\n"), g_wszCSPName, GetLastError()));
return NULL;
}
}
// Set up hashing and signing algorithms to look for based upon input
// parameters. Or if these haven't been supplied use the configured defaults
// instead.
if (uHashAlgId == 0)
uHashAlgId = g_uHashAlgId;
if (uSignAlgId == 0)
uSignAlgId = g_uSignAlgId;
// If default hashing and signing algorithms have been selected (SHA1 and
// RSA), we select the default CSP for the RSA_FULL type.
// For SHA2 and RSA, we select the default CSP For RSA_AES.
// Otherwise, you just get the first CSP that supports the algorithms
// you specified (with no guarantee that the selected CSP is a default of any type).
// This is because we have no way of forcing the enumeration to just give us default
// CSPs.
bool fUseDefaultCsp = false;
StrongNameCachedCsp cachedCspNumber = None;
// We know what container to use for SHA1 algorithms with RSA
if (((uHashAlgId == CALG_SHA1) && (uSignAlgId == CALG_RSA_SIGN)) ||
(dwAction == SN_HASH_SHA1_ONLY)) {
fUseDefaultCsp = true;
cachedCspNumber = Sha1CachedCsp;
dwProvType = PROV_RSA_FULL;
SNLOG((W("Attempting to open default provider\n")));
}
// We know what container to use for SHA2 algorithms with RSA
if ((uHashAlgId == CALG_SHA_256 || uHashAlgId == CALG_SHA_384 || uHashAlgId == CALG_SHA_512)
&& uSignAlgId == CALG_RSA_SIGN) {
fUseDefaultCsp = true;
cachedCspNumber = Sha2CachedCsp;
dwProvType = PROV_RSA_AES;
SNLOG((W("Attempting to open default SHA2 provider\n")));
}
if (fUseDefaultCsp)
{
// If we're not trying to create/open/delete a key container, see if a
// CSP is cached.
if (wszKeyContainer == NULL && dwAction != SN_DELETE_CONTAINER) {
hProv = LookupCachedCSP(cachedCspNumber);
if (hProv) {
SNLOG((W("Found provider in cache\n")));
return hProv;
}
}
if (StrongNameCryptAcquireContext(&hProv,
wszKeyContainer ? wszKeyContainer : NULL,
NULL,
dwProvType,
SN_CAC_FLAGS(dwAction))) {
// If we're not trying to create/open/delete a key container, cache
// the CSP returned.
if (wszKeyContainer == NULL && dwAction != SN_DELETE_CONTAINER)
CacheCSP(hProv, cachedCspNumber);
return (dwAction == SN_DELETE_CONTAINER) ? (HCRYPTPROV)~0 : hProv;
} else {
SNLOG((W("Failed to open: %08X\n"), GetLastError()));
return NULL;
}
}
HRESULT hr = InitStrongNameCriticalSection();
if (FAILED(hr)) {
SetLastError(hr);
return NULL;
}
// Some crypto APIs are non thread safe (e.g. enumerating CSP
// hashing/signing algorithms). Use a mutex to serialize these operations.
// The following usage is GC-safe and exception-safe:
{
CRITSEC_Holder csh(g_rStrongNameMutex);
for (i = 0; ; i++) {
// Enumerate all CSPs.
dwNameLength = sizeof(wszName);
if (CryptEnumProvidersW(i, 0, 0, &dwType, wszName, &dwNameLength)) {
// Open the currently selected CSP.
SNLOG((W("Considering CSP '%s'\n"), wszName));
if (StrongNameCryptAcquireContext(&hProv,
NULL,
wszName,
dwType,
CRYPT_SILENT |
CRYPT_VERIFYCONTEXT |
(g_bUseMachineKeyset ? CRYPT_MACHINE_KEYSET : 0))) {
// Enumerate all the algorithms the CSP supports.
bFirstAlg = TRUE;
bFoundHash = FALSE;
bFoundSign = FALSE;
for (;;) {
dwAlgsLen = sizeof(rAlgs);
if (CryptGetProvParam(hProv,
PP_ENUMALGS, (BYTE*)&rAlgs, &dwAlgsLen,
bFirstAlg ? CRYPT_FIRST : 0)) {
if (rAlgs.aiAlgid == uHashAlgId)
bFoundHash = TRUE;
else if (rAlgs.aiAlgid == uSignAlgId)
bFoundSign = TRUE;
if (bFoundHash && bFoundSign) {
// Found a CSP that supports the required
// algorithms. Re-open the context with access to
// the required key container.
SNLOG((W("CSP matches\n")));
if (StrongNameCryptAcquireContext(&hRetProv,
wszKeyContainer ? wszKeyContainer : NULL,
wszName,
dwType,
CRYPT_SILENT |
SN_CAC_FLAGS(dwAction))) {
CryptReleaseContext(hProv, 0);
return (dwAction == SN_DELETE_CONTAINER) ? (HCRYPTPROV)~0 : hRetProv;
} else {
SNLOG((W("Failed to re-open for container: %08X\n"), GetLastError()));
break;
}
}
bFirstAlg = FALSE;
} else {
_ASSERTE(GetLastError() == ERROR_NO_MORE_ITEMS);
break;
}
}
CryptReleaseContext(hProv, 0);
} else
SNLOG((W("Failed to open CSP: %08X\n"), GetLastError()));
} else if (GetLastError() == ERROR_NO_MORE_ITEMS)
break;
}
// csh for g_rStrongNameMutex goes out of scope here
}
// No matching CSP found.
SetLastError(CORSEC_E_NO_SUITABLE_CSP);
return NULL;
}
// Release a CSP acquired through LocateCSP.
VOID FreeCSP(HCRYPTPROV hProv)
{
// If the CSP is currently cached, don't release it yet.
if (!IsCachedCSP(hProv))
CryptReleaseContext(hProv, 0);
}
// Locate a cached CSP for this thread.
HCRYPTPROV LookupCachedCSP(StrongNameCachedCsp cspNumber)
{
SN_THREAD_CTX *pThreadCtx = GetThreadContext();
if (pThreadCtx == NULL)
return NULL;
return pThreadCtx->m_hProv[cspNumber];
}
// Update the CSP cache for this thread (freeing any CSP displaced).
VOID CacheCSP(HCRYPTPROV hProv, StrongNameCachedCsp cspNumber)
{
SN_THREAD_CTX *pThreadCtx = GetThreadContext();
if (pThreadCtx == NULL)
return;
if (pThreadCtx->m_hProv[cspNumber])
CryptReleaseContext(pThreadCtx->m_hProv[cspNumber], 0);
pThreadCtx->m_hProv[cspNumber] = hProv;
}
// Determine whether a given CSP is currently cached.
BOOLEAN IsCachedCSP(HCRYPTPROV hProv)
{
SN_THREAD_CTX *pThreadCtx = GetThreadContext();
if (pThreadCtx == NULL)
return FALSE;
for (ULONG i = 0; i < CachedCspCount; i++)
{
if(pThreadCtx->m_hProv[i] == hProv)
{
return TRUE;
}
}
return FALSE;
}
// rehash all files in a multi-module assembly
BOOLEAN RehashModules (SN_LOAD_CTX *pLoadCtx, LPCWSTR wszFilePath) {
HRESULT hr;
ULONG ulHashAlg;
mdAssembly tkAssembly;
HENUMInternal hFileEnum;
mdFile tkFile;
LPCSTR pszFile;
BYTE *pbFileHash;
DWORD cbFileHash;
NewArrayHolder<BYTE> pbNewFileHash(NULL);
DWORD cbNewFileHash = 0;
DWORD cchDirectory;
DWORD cchFullFile;
CHAR szFullFile[MAX_LONGPATH + 1];
WCHAR wszFullFile[MAX_LONGPATH + 1];
LPCWSTR pszSlash;
DWORD cchFile;
IMDInternalImport *pMetaDataImport = NULL;
// Determine the directory the assembly lives in (this is where we'll
// look for linked files).
if (((pszSlash = wcsrchr(wszFilePath, W('\\'))) != NULL) || ((pszSlash = wcsrchr(wszFilePath, W('/'))) != NULL)) {
cchDirectory = (DWORD) (pszSlash - wszFilePath + 1);
cchDirectory = WszWideCharToMultiByte(CP_UTF8, 0, wszFilePath, cchDirectory, szFullFile, MAX_LONGPATH, NULL, NULL);
if (cchDirectory >= MAX_LONGPATH) {
SNLOG((W("Assembly directory name too long\n")));
hr = ERROR_BUFFER_OVERFLOW;
goto Error;
}
} else
cchDirectory = 0;
// Open the scope on the mapped image.
if (FAILED(hr = GetMetadataImport(pLoadCtx, &tkAssembly, &pMetaDataImport)))
{
goto Error;
}
// Determine the hash algorithm used for file references.
if (FAILED(hr = pMetaDataImport->GetAssemblyProps(
tkAssembly, // [IN] The Assembly for which to get the properties
NULL, // [OUT] Pointer to the Originator blob
NULL, // [OUT] Count of bytes in the Originator Blob
&ulHashAlg, // [OUT] Hash Algorithm
NULL, // [OUT] Buffer to fill with name
NULL, // [OUT] Assembly MetaData
NULL))) // [OUT] Flags
{
SNLOG((W("Failed to get assembly 0x%08X info, %08X\n"), tkAssembly, hr));
goto Error;
}
// Enumerate all file references.
if (FAILED(hr = pMetaDataImport->EnumInit(mdtFile, mdTokenNil, &hFileEnum)))
{
SNLOG((W("Failed to enumerate linked files, %08X\n"), hr));
goto Error;
}
for (; pMetaDataImport->EnumNext(&hFileEnum, &tkFile); ) {
// Determine the file name and the location of the hash.
if (FAILED(hr = pMetaDataImport->GetFileProps(
tkFile,
&pszFile,
(const void **)&pbFileHash,
&cbFileHash,
NULL)))
{
SNLOG((W("Failed to get file 0x%08X info, %08X\n"), tkFile, hr));
goto Error;
}
// Build the full filename by appending to the assembly directory we
// calculated earlier.
cchFile = (DWORD) strlen(pszFile);
if ((cchFile + cchDirectory) >= COUNTOF(szFullFile)) {
pMetaDataImport->EnumClose(&hFileEnum);
SNLOG((W("Linked file name too long (%S)\n"), pszFile));
hr = ERROR_BUFFER_OVERFLOW;
goto Error;
}
memcpy_s(&szFullFile[cchDirectory], COUNTOF(szFullFile) - cchDirectory, pszFile, cchFile + 1);
// Allocate enough buffer for the new hash.
if (cbNewFileHash < cbFileHash) {
pbNewFileHash = new (nothrow) BYTE[cbFileHash];
if (pbNewFileHash == NULL) {
hr = E_OUTOFMEMORY;
goto Error;
}
cbNewFileHash = cbFileHash;
}
cchFullFile = WszMultiByteToWideChar(CP_UTF8, 0, szFullFile, -1, wszFullFile, MAX_LONGPATH);
if (cchFullFile == 0 || cchFullFile >= MAX_LONGPATH) {
pMetaDataImport->EnumClose(&hFileEnum);
SNLOG((W("Assembly directory name too long\n")));
hr = ERROR_BUFFER_OVERFLOW;
goto Error;
}
// Compute a new hash for the file.
if (FAILED(hr = GetHashFromFileW(wszFullFile,
(unsigned*)&ulHashAlg,
pbNewFileHash,
cbNewFileHash,
&cbNewFileHash))) {
pMetaDataImport->EnumClose(&hFileEnum);
SNLOG((W("Failed to get compute file hash, %08X\n"), hr));
goto Error;
}
// The new hash has to be the same size (since we used the same
// algorithm).
_ASSERTE(cbNewFileHash == cbFileHash);
// We make the assumption here that the pointer to the file hash
// handed to us by the metadata is a direct pointer and not a
// buffered copy. If this changes, we'll need a new metadata API to
// support updates of this type.
memcpy_s(pbFileHash, cbFileHash, pbNewFileHash, cbFileHash);
}
pMetaDataImport->EnumClose(&hFileEnum);
pMetaDataImport->Release();
return TRUE;
Error:
if (pMetaDataImport)
pMetaDataImport->Release();
if (pbNewFileHash)
pbNewFileHash.Release();
SetLastError(hr);
return FALSE;
}
//
// Check that the public key portion of an assembly's identity matches the private key that it is being
// signed with.
//
// Arguments:
// pAssemblySignaturePublicKey - Assembly signature public key blob
// wszKeyContainer - Key container holding the key the assembly is signed with
// dwFlags - SN_ECMA_SIGN if the assembly is being ECMA signed, SN_TEST_SIGN if it is being test signed
//
// Return Value:
// true if the assembly's public key matches the private key in wszKeyContainer, otherwise false
//
bool VerifyKeyMatchesAssembly(PublicKeyBlob * pAssemblySignaturePublicKey, __in_z LPCWSTR wszKeyContainer, BYTE *pbKeyBlob, ULONG cbKeyBlob, DWORD dwFlags)
{
_ASSERTE(wszKeyContainer != NULL || pbKeyBlob != NULL);
// If we're test signing, then the assembly's public key will not match the private key by design.
// Since there's nothing to check, we can quit early.
if ((dwFlags & SN_TEST_SIGN) == SN_TEST_SIGN)
{
return true;
}
if (SN_IS_NEUTRAL_KEY(pAssemblySignaturePublicKey))
{
// If we're ECMA signing an assembly with the ECMA public key, then by definition the key matches.
if ((dwFlags & SN_ECMA_SIGN) == SN_ECMA_SIGN)
{
return true;
}
// Swap the real public key in for ECMA signing
pAssemblySignaturePublicKey = SN_THE_KEY();
}
// Otherwise, we need to check that the public key from the key container matches the public key from
// the assembly.
StrongNameBufferHolder<BYTE> pbSignaturePublicKey = NULL;
DWORD cbSignaturePublicKey;
if (!StrongNameGetPublicKeyEx(wszKeyContainer, pbKeyBlob, cbKeyBlob, &pbSignaturePublicKey, &cbSignaturePublicKey, GET_UNALIGNED_VAL32(&pAssemblySignaturePublicKey->HashAlgID), 0 /*Should be GET_UNALIGNED_VAL32(&pAssemblySignaturePublicKey->HashAlgID) once we support different signature algorithms*/))
{
// We failed to get the public key for the key in the given key container. StrongNameGetPublicKey
// has already set the error information, so we can just return false here without resetting it.
return false;
}
_ASSERTE(!pbSignaturePublicKey.IsNull() && pAssemblySignaturePublicKey != NULL);
// Do a raw compare on the public key blobs to see if they match
if (SN_SIZEOF_KEY(reinterpret_cast<PublicKeyBlob *>(pbSignaturePublicKey.GetValue())) == SN_SIZEOF_KEY(pAssemblySignaturePublicKey) &&
memcmp(static_cast<void *>(pAssemblySignaturePublicKey),
static_cast<void *>(pbSignaturePublicKey.GetValue()),
cbSignaturePublicKey) == 0)
{
return true;
}
SetStrongNameErrorInfo(SN_E_PUBLICKEY_MISMATCH);
return false;
}
// Map an assembly into memory.
BOOLEAN LoadAssembly(SN_LOAD_CTX *pLoadCtx, LPCWSTR wszFilePath, DWORD inFlags, BOOLEAN fRequireSignature)
{
DWORD dwError = S_OK;
// If a filename is not supplied, the image has already been mapped (and the
// image base and length fields set up correctly).
if (wszFilePath == NULL)
{
pLoadCtx->m_fPreMapped = TRUE;
pLoadCtx->m_pedecoder = new (nothrow) PEDecoder(pLoadCtx->m_pbBase, static_cast<COUNT_T>(pLoadCtx->m_dwLength));
if (pLoadCtx->m_pedecoder == NULL) {
dwError = E_OUTOFMEMORY;
goto Error;
}
}
else {
pLoadCtx->m_hMap = INVALID_HANDLE_VALUE;
pLoadCtx->m_pbBase = NULL;
// Open the file for reading or writing.
pLoadCtx->m_hFile = WszCreateFile(wszFilePath,
GENERIC_READ | (pLoadCtx->m_fReadOnly ? 0 : GENERIC_WRITE),
pLoadCtx->m_fReadOnly ? FILE_SHARE_READ : FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
0,
NULL);
if (pLoadCtx->m_hFile == INVALID_HANDLE_VALUE) {
dwError = HRESULT_FROM_GetLastError();
goto Error;
}
pLoadCtx->m_dwLength = SafeGetFileSize(pLoadCtx->m_hFile, NULL);
if (pLoadCtx->m_dwLength == 0xffffffff) {
dwError = HRESULT_FROM_GetLastError();
goto Error;
}
// Create a mapping handle for the file.
pLoadCtx->m_hMap = WszCreateFileMapping(pLoadCtx->m_hFile, NULL, pLoadCtx->m_fReadOnly ? PAGE_READONLY : PAGE_READWRITE, 0, 0, NULL);
if (pLoadCtx->m_hMap == NULL) {
dwError = HRESULT_FROM_GetLastError();
goto Error;
}
// And map it into memory.
pLoadCtx->m_pbBase = (BYTE*)CLRMapViewOfFile(pLoadCtx->m_hMap, pLoadCtx->m_fReadOnly ? FILE_MAP_READ : FILE_MAP_WRITE, 0, 0, 0);
if (pLoadCtx->m_pbBase == NULL) {
dwError = HRESULT_FROM_GetLastError();
goto Error;
}
pLoadCtx->m_pedecoder = new (nothrow) PEDecoder(pLoadCtx->m_pbBase, static_cast<COUNT_T>(pLoadCtx->m_dwLength));
if (pLoadCtx->m_pedecoder == NULL) {
dwError = E_OUTOFMEMORY;
goto Error;
}
}
if (!pLoadCtx->m_pedecoder->HasContents() || !pLoadCtx->m_pedecoder->CheckCORFormat()) {
dwError = CORSEC_E_INVALID_IMAGE_FORMAT;
goto Error;
}
// Locate standard NT image header.
pLoadCtx->m_pNtHeaders = pLoadCtx->m_pedecoder->GetNTHeaders32();
if (pLoadCtx->m_pNtHeaders == NULL) {
dwError = CORSEC_E_INVALID_IMAGE_FORMAT;
goto Error;
}
pLoadCtx->m_pCorHeader = pLoadCtx->m_pedecoder->GetCorHeader();
if (pLoadCtx->m_pCorHeader == NULL) {
dwError = CORSEC_E_INVALID_IMAGE_FORMAT;
goto Error;
}
// Set up signature pointer (if we require it).
if (fRequireSignature && pLoadCtx->m_pedecoder->HasStrongNameSignature())
{
COUNT_T size = 0;
BYTE* pbSignature = (BYTE*)pLoadCtx->m_pedecoder->GetStrongNameSignature(&size);
// Make sure the signature doesn't point back into the header
if (pbSignature <= reinterpret_cast<BYTE*>(pLoadCtx->m_pCorHeader) &&
pbSignature > reinterpret_cast<BYTE*>(pLoadCtx->m_pCorHeader) - size)
{
dwError = CORSEC_E_INVALID_IMAGE_FORMAT;
goto Error;
}
if (pbSignature >= reinterpret_cast<BYTE*>(pLoadCtx->m_pCorHeader) &&
pbSignature - sizeof(IMAGE_COR20_HEADER) < reinterpret_cast<BYTE*>(pLoadCtx->m_pCorHeader))
{
dwError = CORSEC_E_INVALID_IMAGE_FORMAT;
goto Error;
}
pLoadCtx->m_pbSignature = pbSignature;
pLoadCtx->m_cbSignature = static_cast<DWORD>(size);
}
return TRUE;
Error:
if (!pLoadCtx->m_fPreMapped) {
if (pLoadCtx->m_pbBase)
CLRUnmapViewOfFile(pLoadCtx->m_pbBase);
if (pLoadCtx->m_hMap != INVALID_HANDLE_VALUE)
CloseHandle(pLoadCtx->m_hMap);
if (pLoadCtx->m_hFile != INVALID_HANDLE_VALUE)
CloseHandle(pLoadCtx->m_hFile);
}
SetLastError(dwError);
return FALSE;
}
// Unload an assembly loaded with LoadAssembly (recomputing checksum if
// necessary).
BOOLEAN UnloadAssembly(SN_LOAD_CTX *pLoadCtx)
{
BOOLEAN bResult = TRUE;
if (!pLoadCtx->m_fReadOnly) {
IMAGE_NT_HEADERS *pNtHeaders = NULL;
DWORD dwCheckSum = 0;
// We late bind CheckSumMappedFile to avoid bringing in IMAGEHLP unless
// we need to.
HMODULE hLibrary = WszLoadLibrary(W("imagehlp.dll"));
if (hLibrary) {
IMAGE_NT_HEADERS *(*SN_CheckSumMappedFile)(BYTE*, DWORD, DWORD*, DWORD*);
if ((*(FARPROC*)&SN_CheckSumMappedFile = GetProcAddress(hLibrary, "CheckSumMappedFile")) != NULL) {
DWORD dwOldCheckSum;
pNtHeaders = SN_CheckSumMappedFile(pLoadCtx->m_pbBase,
pLoadCtx->m_dwLength,
&dwOldCheckSum,
&dwCheckSum);
}
FreeLibrary(hLibrary);
}
if (pNtHeaders != NULL) {
if (pNtHeaders->OptionalHeader.Magic == VAL16(IMAGE_NT_OPTIONAL_HDR32_MAGIC))
((IMAGE_NT_HEADERS32*)pNtHeaders)->OptionalHeader.CheckSum = VAL32(dwCheckSum);
else
if (pNtHeaders->OptionalHeader.Magic == VAL16(IMAGE_NT_OPTIONAL_HDR64_MAGIC))
((IMAGE_NT_HEADERS64*)pNtHeaders)->OptionalHeader.CheckSum = VAL32(dwCheckSum);
} else
bResult = FALSE;
if (!pLoadCtx->m_fPreMapped && !FlushViewOfFile(pLoadCtx->m_pbBase, 0))
bResult = FALSE;
}
if (!pLoadCtx->m_fPreMapped) {
if (!CLRUnmapViewOfFile(pLoadCtx->m_pbBase))
bResult = FALSE;
if (!CloseHandle(pLoadCtx->m_hMap))
bResult = FALSE;
if (!CloseHandle(pLoadCtx->m_hFile))
bResult = FALSE;
}
if (pLoadCtx->m_pedecoder != NULL)
{
delete (pLoadCtx->m_pedecoder);
pLoadCtx->m_pedecoder = NULL;
}
return bResult;
}
template<class T>
LONG RegQueryValueT(HKEY hKey, LPCWSTR pValueName, T * pData)
{
DWORD dwLength = sizeof(T);
LONG status = WszRegQueryValueEx(hKey, pValueName, NULL, NULL, (BYTE*) pData, & dwLength);
return status;
}
// Reads CSP configuration info (name of CSP to use, IDs of hashing/signing
// algorithms) from the registry.
HRESULT ReadRegistryConfig()
{
HKEY hKey;
DWORD dwLength;
// Initialize all settings to their default values, in case they've not been
// specified in the registry.
g_bHasCSPName = FALSE;
g_bUseMachineKeyset = TRUE;
g_uKeySpec = AT_SIGNATURE;
g_uHashAlgId = CALG_SHA1;
g_uSignAlgId = CALG_RSA_SIGN;
g_uProvType = PROV_RSA_FULL;
#ifdef FEATURE_STRONGNAME_DELAY_SIGNING_ALLOWED
g_pVerificationRecords = NULL;
#endif
g_fCacheVerify = TRUE;
// Open the configuration key in the registry.
if (WszRegOpenKeyEx(HKEY_LOCAL_MACHINE, SN_CONFIG_KEY_W, 0, KEY_READ, &hKey) != ERROR_SUCCESS)
return S_OK;
// Read the preferred CSP name.
{
// Working set optimization: avoid touching g_wszCSPName (2052 bytes in size) unless registry has value for it
WCHAR tempCSPName[_countof(g_wszCSPName)];
dwLength = sizeof(tempCSPName);
tempCSPName[0] = 0;
// If the registry key value is too long, that means it is invalid.
VERIFY(WszRegQueryValueEx(hKey, SN_CONFIG_CSP_W, NULL, NULL,
(BYTE*) tempCSPName, &dwLength) != ERROR_MORE_DATA);
tempCSPName[COUNTOF(tempCSPName) - 1] = W('\0'); // make sure the string is NULL-terminated
SNLOG((W("Preferred CSP name: '%s'\n"), tempCSPName));
if (tempCSPName[0] != W('\0'))
{
memcpy(g_wszCSPName, tempCSPName, sizeof(g_wszCSPName));
g_bHasCSPName = TRUE;
}
}
// Read the machine vs user key container flag.
DWORD dwUseMachineKeyset = TRUE;
RegQueryValueT(hKey, SN_CONFIG_MACHINE_KEYSET_W, & dwUseMachineKeyset);
SNLOG((W("Use machine keyset: %s\n"), dwUseMachineKeyset ? W("TRUE") : W("FALSE")));
g_bUseMachineKeyset = (BOOLEAN)dwUseMachineKeyset;
// Read the key spec.
RegQueryValueT(hKey, SN_CONFIG_KEYSPEC_W, & g_uKeySpec);
SNLOG((W("Key spec: %08X\n"), g_uKeySpec));
// Read the provider type
RegQueryValueT(hKey, SN_CONFIG_PROV_TYPE_W, & g_uProvType);
SNLOG((W("Provider Type: %08X\n"), g_uProvType));
// Read the hashing algorithm ID.
RegQueryValueT(hKey, SN_CONFIG_HASH_ALG_W, & g_uHashAlgId);
SNLOG((W("Hashing algorithm: %08X\n"), g_uHashAlgId));
// Read the signing algorithm ID.
RegQueryValueT(hKey, SN_CONFIG_SIGN_ALG_W, & g_uSignAlgId);
SNLOG((W("Signing algorithm: %08X\n"), g_uSignAlgId));
// Read the OK to cache verifications flag.
DWORD dwCacheVerify = TRUE;
RegQueryValueT(hKey, SN_CONFIG_CACHE_VERIFY_W, & dwCacheVerify);
SNLOG((W("OK to cache verifications: %s\n"), dwCacheVerify ? W("TRUE") : W("FALSE")));
g_fCacheVerify = (BOOLEAN)dwCacheVerify;
RegCloseKey(hKey);
HRESULT hr = S_OK;
#ifdef FEATURE_STRONGNAME_DELAY_SIGNING_ALLOWED
// Read verify disable records.
IfFailRet(ReadVerificationRecords());
#endif // FEATURE_STRONGNAME_DELAY_SIGNING_ALLOWED
#ifdef FEATURE_STRONGNAME_MIGRATION
IfFailRet(ReadRevocationRecords());
#endif // FEATURE_STRONGNAME_MIGRATION
return hr;
}
#ifdef FEATURE_STRONGNAME_DELAY_SIGNING_ALLOWED
// Read verification records from the registry during startup.
HRESULT ReadVerificationRecords()
{
HKEYHolder hKey;
WCHAR wszSubKey[MAX_PATH_FNAME + 1];
DWORD cchSubKey;
SN_VER_REC *pVerificationRecords = NULL;
HRESULT hr = S_OK;
// Open the verification subkey in the registry.
if (WszRegOpenKeyEx(HKEY_LOCAL_MACHINE, SN_CONFIG_KEY_W W("\\") SN_CONFIG_VERIFICATION_W, 0, KEY_READ, &hKey) != ERROR_SUCCESS)
return hr;
// Assembly specific records are represented as subkeys of the key we've
// just opened.
for (DWORD i = 0; ; i++) {
// Get the name of the next subkey.
cchSubKey = MAX_PATH_FNAME + 1;
FILETIME sFiletime;
if (WszRegEnumKeyEx(hKey, i, wszSubKey, &cchSubKey, NULL, NULL, NULL, &sFiletime) != ERROR_SUCCESS)
break;
// Open the subkey.
HKEYHolder hSubKey;
if (WszRegOpenKeyEx(hKey, wszSubKey, 0, KEY_READ, &hSubKey) == ERROR_SUCCESS) {
NewArrayHolder<WCHAR> mszUserList(NULL);
DWORD cbUserList;
NewArrayHolder<WCHAR> wszTestPublicKey(NULL);
DWORD cbTestPublicKey;
NewArrayHolder<WCHAR> wszAssembly(NULL);
SN_VER_REC *pVerRec;
// Read a list of valid users, if supplied.
if ((WszRegQueryValueEx(hSubKey, SN_CONFIG_USERLIST_W, NULL, NULL, NULL, &cbUserList) == ERROR_SUCCESS) &&
(cbUserList > 0)) {
mszUserList = new (nothrow) WCHAR[cbUserList / sizeof(WCHAR)];
if (!mszUserList) {
hr = E_OUTOFMEMORY;
goto FreeListExit;
}
WszRegQueryValueEx(hSubKey, SN_CONFIG_USERLIST_W, NULL, NULL, (BYTE*)mszUserList.GetValue(), &cbUserList);
}
// Read the test public key, if supplied
if ((WszRegQueryValueEx(hSubKey, SN_CONFIG_TESTPUBLICKEY_W, NULL, NULL, NULL, &cbTestPublicKey) == ERROR_SUCCESS) &&
(cbTestPublicKey > 0)) {
wszTestPublicKey = new (nothrow) WCHAR[cbTestPublicKey / sizeof(WCHAR)];
if (!wszTestPublicKey) {
hr = E_OUTOFMEMORY;
goto FreeListExit;
}
WszRegQueryValueEx(hSubKey, SN_CONFIG_TESTPUBLICKEY_W, NULL, NULL, (BYTE*)wszTestPublicKey.GetValue(), &cbTestPublicKey);
}
size_t dwSubKeyLen = wcslen(wszSubKey);
wszAssembly = new (nothrow) WCHAR[dwSubKeyLen+1];
if (!wszAssembly) {
hr = E_OUTOFMEMORY;
goto FreeListExit;
}
wcsncpy_s(wszAssembly, dwSubKeyLen+1, wszSubKey, _TRUNCATE);
wszAssembly[dwSubKeyLen] = W('\0');
// We've found a valid entry, add it to the local list.
pVerRec = new (nothrow) SN_VER_REC;
if (!pVerRec) {
hr = E_OUTOFMEMORY;
goto FreeListExit;
}
pVerRec->m_mszUserList = mszUserList;
pVerRec->m_wszTestPublicKey = wszTestPublicKey;
pVerRec->m_wszAssembly = wszAssembly;
mszUserList.SuppressRelease();
wszTestPublicKey.SuppressRelease();
wszAssembly.SuppressRelease();
pVerRec->m_pNext = pVerificationRecords;
pVerificationRecords = pVerRec;
SNLOG((W("Verification record for '%s' found in registry\n"), wszSubKey));
}
}
// Initialize the global list of verification records.
PVOID pv = InterlockedCompareExchangeT(&g_pVerificationRecords, pVerificationRecords, NULL);
if (pv == NULL)
return hr;
FreeListExit:
// Iterate over local list of verification records and free allocated memory.
SN_VER_REC *pVerRec = pVerificationRecords;
while (pVerRec) {
delete [] pVerRec->m_mszUserList;
delete [] pVerRec->m_wszTestPublicKey;
delete [] pVerRec->m_wszAssembly;
SN_VER_REC *tmp = pVerRec->m_pNext;
delete pVerRec;
pVerRec = tmp;
}
return hr;
}
#endif // FEATURE_STRONGNAME_DELAY_SIGNING_ALLOWED
#ifdef FEATURE_STRONGNAME_MIGRATION
#define SN_REVOCATION_KEY_NAME_W W("RevokedKeys") // Registry revocation key name
#define SN_REVOKEDKEY_VALUE_NAME_W W("RevokedKey") // Registry value name
HRESULT ReadReplacementKeys(HKEY hKey, SN_REPLACEMENT_KEY_REC **ppReplacementRecords)
{
HRESULT hr = S_OK;
DWORD uValueCount;
DWORD cchMaxValueNameLen;
NewArrayHolder<WCHAR> wszValueName(NULL);
if(RegQueryInfoKey(hKey, NULL, NULL, NULL, NULL, NULL, NULL, &uValueCount, &cchMaxValueNameLen, NULL, NULL, NULL) != ERROR_SUCCESS)
return hr;
cchMaxValueNameLen++; // Add 1 for null character
DWORD cchValueName;
wszValueName = new (nothrow) WCHAR[cchMaxValueNameLen];
if (!wszValueName) {
return E_OUTOFMEMORY;
}
for (DWORD j = 0; j < uValueCount; j++) {
cchValueName = cchMaxValueNameLen;
if (WszRegEnumValue(hKey, j, wszValueName, &cchValueName, NULL, NULL, NULL, NULL) != ERROR_SUCCESS)
break;
if(SString::_wcsicmp(wszValueName, SN_REVOKEDKEY_VALUE_NAME_W) == 0) // Skip over the "RevokedKey" value
continue;
NewArrayHolder<BYTE> pbReplacementKey(NULL);
DWORD cbReplacementKey;
DWORD dwValType;
if ((WszRegQueryValueEx(hKey, wszValueName, NULL, &dwValType, NULL, &cbReplacementKey) == ERROR_SUCCESS) &&
(cbReplacementKey > 0) && (dwValType == REG_BINARY)) {
pbReplacementKey = new (nothrow) BYTE[cbReplacementKey];
if (!pbReplacementKey) {
return E_OUTOFMEMORY;
}
if(WszRegQueryValueEx(hKey, wszValueName, NULL, NULL, (BYTE*)pbReplacementKey.GetValue(), &cbReplacementKey) == ERROR_SUCCESS)
{
NewHolder<SN_REPLACEMENT_KEY_REC> pReplacementRecord(new (nothrow) SN_REPLACEMENT_KEY_REC);
if (pReplacementRecord == NULL) {
return E_OUTOFMEMORY;
}
pReplacementRecord->m_pbReplacementKey = pbReplacementKey.Extract();
pReplacementRecord->m_cbReplacementKey = cbReplacementKey;
// Insert into list
pReplacementRecord->m_pNext = *ppReplacementRecords;
*ppReplacementRecords = pReplacementRecord.Extract();
}
}
}
return hr;
}
// Read revocation records from the registry during startup.
HRESULT ReadRevocationRecordsFromKey(REGSAM samDesired, SN_REVOCATION_REC **ppRevocationRecords)
{
HKEYHolder hKey;
WCHAR wszSubKey[MAX_PATH_FNAME + 1];
DWORD cchSubKey;
HRESULT hr = S_OK;
// Open the revocation subkey in the registry.
if (WszRegOpenKeyEx(HKEY_LOCAL_MACHINE, SN_CONFIG_KEY_W W("\\") SN_REVOCATION_KEY_NAME_W, 0, samDesired, &hKey) != ERROR_SUCCESS)
return hr;
// Assembly specific records are represented as subkeys of the key we've
// just opened.
for (DWORD i = 0; ; i++) {
// Read the next subkey
cchSubKey = MAX_PATH_FNAME + 1; // reset size of buffer, as the following call changes it
if (WszRegEnumKeyEx(hKey, i, wszSubKey, &cchSubKey, NULL, NULL, NULL, NULL) != ERROR_SUCCESS)
break;
// Open the subkey.
HKEYHolder hSubKey;
if (WszRegOpenKeyEx(hKey, wszSubKey, 0, samDesired, &hSubKey) == ERROR_SUCCESS) {
NewArrayHolder<BYTE> pbRevokedKey(NULL);
DWORD cbRevokedKey;
DWORD dwValType;
// Read the "RevokedKey" value
if ((WszRegQueryValueEx(hSubKey, SN_REVOKEDKEY_VALUE_NAME_W, NULL, &dwValType, NULL, &cbRevokedKey) == ERROR_SUCCESS) &&
(cbRevokedKey > 0) && (dwValType == REG_BINARY)) {
pbRevokedKey = new (nothrow) BYTE[cbRevokedKey];
if (!pbRevokedKey) {
return E_OUTOFMEMORY;
}
if(WszRegQueryValueEx(hSubKey, SN_REVOKEDKEY_VALUE_NAME_W, NULL, NULL, (BYTE*)pbRevokedKey.GetValue(), &cbRevokedKey) == ERROR_SUCCESS)
{
// We've found a valid entry, store it
NewHolder<SN_REVOCATION_REC> pRevocationRecord(new (nothrow) SN_REVOCATION_REC);
if (pRevocationRecord == NULL) {
return E_OUTOFMEMORY;
}
pRevocationRecord->m_pbRevokedKey = pbRevokedKey.Extract();
pRevocationRecord->m_cbRevokedKey = cbRevokedKey;
pRevocationRecord->m_pReplacementKeys = NULL;
// Insert into list
pRevocationRecord->m_pNext = *ppRevocationRecords;
*ppRevocationRecords = pRevocationRecord.Extract();
IfFailRet(ReadReplacementKeys(hSubKey, &pRevocationRecord->m_pReplacementKeys));
SNLOG((W("Revocation record '%s' found in registry\n"), wszSubKey));
}
}
}
}
return hr;
}
HRESULT ReadRevocationRecords()
{
HRESULT hr = S_OK;
SYSTEM_INFO systemInfo;
SN_REVOCATION_REC *pRevocationRecords = NULL;
GetNativeSystemInfo(&systemInfo);
// Read both Software\ and Software\WOW6432Node\ on 64-bit systems
if(systemInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64)
{
IfFailGoto(ReadRevocationRecordsFromKey(KEY_READ | KEY_WOW64_64KEY, &pRevocationRecords), FreeListExit);
IfFailGoto(ReadRevocationRecordsFromKey(KEY_READ | KEY_WOW64_32KEY, &pRevocationRecords), FreeListExit);
}
else
{
IfFailGoto(ReadRevocationRecordsFromKey(KEY_READ, &pRevocationRecords), FreeListExit);
}
// Initialize the global list of verification records.
PVOID pv = InterlockedCompareExchangeT(&g_pRevocationRecords, pRevocationRecords, NULL);
if (pv == NULL) // Successfully inserted the list we just created
return hr;
FreeListExit:
// Iterate over local list of verification records and free allocated memory.
SN_REVOCATION_REC *pRevRec = pRevocationRecords;
while (pRevRec) {
if(pRevRec->m_pbRevokedKey)
delete [] pRevRec->m_pbRevokedKey;
SN_REPLACEMENT_KEY_REC *pKeyRec = pRevRec->m_pReplacementKeys;
while (pKeyRec) {
if(pKeyRec->m_pbReplacementKey)
delete [] pKeyRec->m_pbReplacementKey;
SN_REPLACEMENT_KEY_REC *tmp = pKeyRec->m_pNext;
delete pKeyRec;
pKeyRec = tmp;
}
SN_REVOCATION_REC *tmp2 = pRevRec->m_pNext;
delete pRevRec;
pRevRec = tmp2;
}
return hr;
}
#endif // FEATURE_STRONGNAME_MIGRATION
// Check current user name against a multi-string user name list. Return true if
// the name is found (or the list is empty).
BOOLEAN IsValidUser(__in_z WCHAR *mszUserList)
{
HANDLE hToken;
DWORD dwRetLen;
TOKEN_USER *pUser;
WCHAR wszUser[1024];
WCHAR wszDomain[1024];
DWORD cchUser;
DWORD cchDomain;
SID_NAME_USE eSidUse;
WCHAR *wszUserEntry;
// Empty list implies no user name checking.
if (mszUserList == NULL)
return TRUE;
// Get current user name. Don't cache this to avoid threading/impersonation
// problems.
// First look to see if there's a security token on the current thread
// (maybe we're impersonating). If not, we'll get the token from the
// process.
if (!OpenThreadToken(GetCurrentThread(), TOKEN_READ, FALSE, &hToken))
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_READ, &hToken)) {
SNLOG((W("Failed to find a security token, error %08X\n"), GetLastError()));
return FALSE;
}
// Get the user SID. (Calculate buffer size first).
if (!GetTokenInformation(hToken, TokenUser, NULL, 0, &dwRetLen) &&
GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
SNLOG((W("Failed to calculate token information buffer size, error %08X\n"), GetLastError()));
CloseHandle(hToken);
return FALSE;
}
NewArrayHolder<BYTE> pvBuffer = new (nothrow) BYTE[dwRetLen];
if (pvBuffer == NULL)
{
SetLastError(E_OUTOFMEMORY);
return FALSE;
}
if (!GetTokenInformation(hToken, TokenUser, reinterpret_cast<LPVOID>((BYTE*)pvBuffer), dwRetLen, &dwRetLen)) {
SNLOG((W("Failed to acquire token information, error %08X\n"), GetLastError()));
CloseHandle(hToken);
return FALSE;
}
pUser = reinterpret_cast<TOKEN_USER *>(pvBuffer.GetValue());
// Get the user and domain names.
cchUser = sizeof(wszUser) / sizeof(WCHAR);
cchDomain = sizeof(wszDomain) / sizeof(WCHAR);
if (!WszLookupAccountSid(NULL, pUser->User.Sid,
wszUser, &cchUser,
wszDomain, &cchDomain,
&eSidUse)) {
SNLOG((W("Failed to lookup account information, error %08X\n"), GetLastError()));
CloseHandle(hToken);
return FALSE;
}
CloseHandle(hToken);
// Concatenate user and domain name to get a fully qualified account name.
if (((wcslen(wszUser) + wcslen(wszDomain) + 2) * sizeof(WCHAR)) > sizeof(wszDomain)) {
SNLOG((W("Fully qualified account name was too long\n")));
return FALSE;
}
wcscat_s(wszDomain, COUNTOF(wszDomain), W("\\"));
wcscat_s(wszDomain, COUNTOF(wszDomain), wszUser);
SNLOG((W("Current username is '%s'\n"), wszDomain));
// Check current user against each name in the multi-string (packed
// list of nul terminated strings terminated with an additional nul).
wszUserEntry = mszUserList;
while (*wszUserEntry) {
if (!SString::_wcsicmp(wszDomain, wszUserEntry))
return TRUE;
wszUserEntry += wcslen(wszUserEntry) + 1;
}
// No user name match, fail search.
SNLOG((W("No username match\n")));
return FALSE;
}
#ifdef FEATURE_STRONGNAME_DELAY_SIGNING_ALLOWED
// See if there's a verification records for the given assembly.
SN_VER_REC *GetVerificationRecord(__in_z __deref LPWSTR wszAssemblyName, PublicKeyBlob *pPublicKey)
{
SN_VER_REC *pVerRec;
SN_VER_REC *pWildcardVerRec = NULL;
LPWSTR pAssembly = NULL;
BYTE *pbToken;
DWORD cbToken;
WCHAR wszStrongName[(SN_SIZEOF_TOKEN * 2) + 1];
DWORD i;
// Compress the public key to make for a shorter assembly name.
if (!StrongNameTokenFromPublicKey((BYTE*)pPublicKey,
SN_SIZEOF_KEY(pPublicKey),
&pbToken,
&cbToken))
return NULL;
if (cbToken > SN_SIZEOF_TOKEN)
return NULL;
// Turn the token into hex.
for (i = 0; i < cbToken; i++) {
static WCHAR *wszHex = W("0123456789ABCDEF");
wszStrongName[(i * 2) + 0] = wszHex[(pbToken[i] >> 4)];
wszStrongName[(i * 2) + 1] = wszHex[(pbToken[i] & 0x0F)];
}
wszStrongName[i * 2] = W('\0');
delete[] pbToken;
// Build the full assembly name.
size_t nLen = wcslen(wszAssemblyName) + wcslen(W(",")) + wcslen(wszStrongName);
pAssembly = new (nothrow) WCHAR[nLen +1]; // +1 for NULL
if (pAssembly == NULL)
return NULL;
wcscpy_s(pAssembly, nLen + 1, wszAssemblyName);
wcscat_s(pAssembly, nLen + 1, W(","));
wcscat_s(pAssembly, nLen + 1, wszStrongName);
// Iterate over global list of verification records.
for (pVerRec = g_pVerificationRecords; pVerRec; pVerRec = pVerRec->m_pNext) {
// Look for matching assembly name.
if (!SString::_wcsicmp(pAssembly, pVerRec->m_wszAssembly)) {
delete[] pAssembly;
// Check current user against allowed user name list.
if (IsValidUser(pVerRec->m_mszUserList))
return pVerRec;
else
return NULL;
} else if (!wcscmp(W("*,*"), pVerRec->m_wszAssembly)) {
// Found a wildcard record, it'll do if we don't find something more
// specific.
if (pWildcardVerRec == NULL)
pWildcardVerRec = pVerRec;
} else if (!wcsncmp(W("*,"), pVerRec->m_wszAssembly, 2)) {
// Found a wildcard record (with a specific strong name). If the
// strong names match it'll do unless we find something more
// specific (it overrides "*,*" wildcards though).
if (!SString::_wcsicmp(wszStrongName, &pVerRec->m_wszAssembly[2]))
pWildcardVerRec = pVerRec;
}
}
delete[] pAssembly;
// No match on specific assembly name, see if there's a wildcard entry.
if (pWildcardVerRec)
// Check current user against allowed user name list.
if (IsValidUser(pWildcardVerRec->m_mszUserList))
return pWildcardVerRec;
else
return NULL;
return NULL;
}
#endif // FEATURE_STRONGNAME_DELAY_SIGNING_ALLOWED
HRESULT
CallGetMetaDataInternalInterface(
LPVOID pData,
ULONG cbData,
DWORD flags,
REFIID riid,
LPVOID *ppInterface)
{
#ifdef FEATURE_STRONGNAME_STANDALONE_WINRT
return E_NOTIMPL;
#elif STRONGNAME_IN_VM || !FEATURE_STANDALONE_SN
// We link the GetMetaDataInternalInterface, so just call it
return GetMetaDataInternalInterface(
pData,
cbData,
flags,
riid,
ppInterface);
#elif FEATURE_CORECLR
return E_NOTIMPL;
#else
// We late bind the metadata function to avoid having a direct dependence on
// mscoree.dll unless we absolutely need to.
HRESULT hr = S_OK;
ICLRMetaHost *pCLRMetaHost = NULL;
ICLRRuntimeInfo *pCLRRuntimeInfo = NULL;
ICLRRuntimeHostInternal *pCLRRuntimeHostInternal = NULL;
HMODULE hLibrary = WszLoadLibrary(MSCOREE_SHIM_W);
if (hLibrary == NULL)
{
hr = HRESULT_FROM_GetLastError();
SNLOG((W("WszLoadLibrary(\"") MSCOREE_SHIM_W W("\") failed with %08x\n"), hr));
goto ErrExit;
}
typedef HRESULT (__stdcall *PFNCLRCreateInstance)(REFCLSID clsid, REFIID riid, /*iid_is(riid)*/ LPVOID *ppInterface);
PFNCLRCreateInstance pfnCLRCreateInstance = reinterpret_cast<PFNCLRCreateInstance>(GetProcAddress(
hLibrary,
"CLRCreateInstance"));
if (pfnCLRCreateInstance == NULL)
{
hr = HRESULT_FROM_GetLastError();
SNLOG((W("Couldn't find CLRCreateInstance() in ") MSCOREE_SHIM_W W(": %08x\n"), hr));
goto ErrExit;
}
if (FAILED(hr = pfnCLRCreateInstance(CLSID_CLRMetaHost, IID_ICLRMetaHost, (LPVOID *)&pCLRMetaHost)))
{
SNLOG((W("Error calling CLRCreateInstance() in ") MSCOREE_SHIM_W W(": %08x\n"), hr));
goto ErrExit;
}
if (FAILED(hr = pCLRMetaHost->GetRuntime(
W("v") VER_PRODUCTVERSION_NO_QFE_STR_L,
IID_ICLRRuntimeInfo,
(LPVOID *)&pCLRRuntimeInfo)))
{
SNLOG((W("Error calling ICLRMetaHost::GetRuntime() in ") MSCOREE_SHIM_W W(": %08x\n"), hr));
goto ErrExit;
}
if (FAILED(hr = pCLRRuntimeInfo->GetInterface(
CLSID_CLRRuntimeHostInternal,
IID_ICLRRuntimeHostInternal,
(LPVOID *)&pCLRRuntimeHostInternal)))
{
SNLOG((W("Error calling ICLRRuntimeInfo::GetInterface() in ") MSCOREE_SHIM_W W(": %08x\n"), hr));
goto ErrExit;
}
hr = pCLRRuntimeHostInternal->GetMetaDataInternalInterface(
(BYTE *)pData,
cbData,
flags,
riid,
ppInterface);
ErrExit:
if (pCLRMetaHost != NULL)
{
pCLRMetaHost->Release();
}
if (pCLRRuntimeInfo != NULL)
{
pCLRRuntimeInfo->Release();
}
if (pCLRRuntimeHostInternal != NULL)
{
pCLRRuntimeHostInternal->Release();
}
return hr;
#endif
} // CallGetMetaDataInternalInterface
// Load metadata engine and return an importer.
HRESULT
GetMetadataImport(
__in const SN_LOAD_CTX *pLoadCtx,
__in mdAssembly *ptkAssembly,
__out IMDInternalImport **ppMetaDataImport)
{
HRESULT hr = E_FAIL;
BYTE *pMetaData = NULL;
// Locate the COM+ meta data within the header.
if (pLoadCtx->m_pedecoder->CheckCorHeader())
{
pMetaData = (BYTE *)pLoadCtx->m_pedecoder->GetMetadata();
}
if (pMetaData == NULL)
{
SNLOG((W("Couldn't locate the COM+ header\n")));
return CORSEC_E_INVALID_IMAGE_FORMAT;
}
// Open a metadata scope on the memory directly.
ReleaseHolder<IMDInternalImport> pMetaDataImportHolder;
if (FAILED(hr = CallGetMetaDataInternalInterface(
pMetaData,
VAL32(pLoadCtx->m_pCorHeader->MetaData.Size),
ofRead,
IID_IMDInternalImport,
&pMetaDataImportHolder)))
{
SNLOG((W("GetMetaDataInternalInterface() failed with %08x\n"), hr));
return SubstituteErrorIfNotTransient(hr, CORSEC_E_INVALID_IMAGE_FORMAT);
}
// Determine the metadata token for the assembly from the scope.
if (FAILED(hr = pMetaDataImportHolder->GetAssemblyFromScope(ptkAssembly)))
{
SNLOG((W("pMetaData->GetAssemblyFromScope() failed with %08x\n"), hr));
return SubstituteErrorIfNotTransient(hr, CORSEC_E_INVALID_IMAGE_FORMAT);
}
*ppMetaDataImport = pMetaDataImportHolder.Extract();
return S_OK;
}
#if STRONGNAME_IN_VM
// Function to form the fully qualified assembly name from the load context
BOOL FormFullyQualifiedAssemblyName(SN_LOAD_CTX *pLoadCtx, SString &assemblyName)
{
mdAssembly tkAssembly;
// Open a metadata scope on the image.
ReleaseHolder<IMDInternalImport> pMetaDataImport;
HRESULT hr;
if (FAILED(hr = GetMetadataImport(pLoadCtx, &tkAssembly, &pMetaDataImport)))
return FALSE;
if (pMetaDataImport != NULL)
{
PEAssembly::GetFullyQualifiedAssemblyName(pMetaDataImport, tkAssembly, assemblyName);
return TRUE;
}
return FALSE;
}
#endif
// Locate the public key blob located within the metadata of an assembly file
// and return a copy (use delete to deallocate). Optionally get the assembly
// name as well.
HRESULT FindPublicKey(const SN_LOAD_CTX *pLoadCtx,
__out_ecount_opt(cchAssemblyName) LPWSTR wszAssemblyName,
DWORD cchAssemblyName,
__out PublicKeyBlob **ppPublicKey,
DWORD *pcbPublicKey)
{
HRESULT hr = S_OK;
*ppPublicKey = NULL;
// Open a metadata scope on the image.
mdAssembly tkAssembly;
ReleaseHolder<IMDInternalImport> pMetaDataImport;
if (FAILED(hr = GetMetadataImport(pLoadCtx, &tkAssembly, &pMetaDataImport)))
return hr;
// Read the public key location from the assembly properties (it's known as
// the originator property).
PublicKeyBlob *pKey;
DWORD dwKeyLen;
LPCSTR szAssemblyName;
if (FAILED(hr = pMetaDataImport->GetAssemblyProps(tkAssembly, // [IN] The Assembly for which to get the properties
(const void **)&pKey, // [OUT] Pointer to the Originator blob
&dwKeyLen, // [OUT] Count of bytes in the Originator Blob
NULL, // [OUT] Hash Algorithm
&szAssemblyName, // [OUT] Buffer to fill with name
NULL, // [OUT] Assembly MetaData
NULL))) // [OUT] Flags
{
SNLOG((W("Did not get public key property: %08x\n"), hr));
return SubstituteErrorIfNotTransient(hr, CORSEC_E_MISSING_STRONGNAME);
}
if (dwKeyLen == 0)
{
SNLOG((W("No public key stored in metadata\n")));
return CORSEC_E_MISSING_STRONGNAME;
}
// Make a copy of the key blob (because we're going to close the metadata scope).
NewArrayHolder<BYTE> pKeyCopy(new (nothrow) BYTE[dwKeyLen]);
if (pKeyCopy == NULL)
return E_OUTOFMEMORY;
memcpy_s(pKeyCopy, dwKeyLen, pKey, dwKeyLen);
// Copy the assembly name as well (if it was asked for). We also convert
// from UTF8 to UNICODE while we're at it.
if (wszAssemblyName)
WszMultiByteToWideChar(CP_UTF8, 0, szAssemblyName, -1, wszAssemblyName, cchAssemblyName);
*ppPublicKey = reinterpret_cast<PublicKeyBlob *>(pKeyCopy.Extract());
if(pcbPublicKey != NULL)
*pcbPublicKey = dwKeyLen;
return S_OK;
}
BYTE HexToByte (WCHAR wc) {
if (!iswxdigit(wc)) return (BYTE) 0xff;
if (iswdigit(wc)) return (BYTE) (wc - W('0'));
if (iswupper(wc)) return (BYTE) (wc - W('A') + 10);
return (BYTE) (wc - W('a') + 10);
}
// Read the hex string into a PublicKeyBlob structure.
// Caller owns the blob.
PublicKeyBlob *GetPublicKeyFromHex(LPCWSTR wszPublicKeyHexString) {
size_t cchHex = wcslen(wszPublicKeyHexString);
size_t cbHex = cchHex / 2;
if (cchHex % 2 != 0)
return NULL;
BYTE *pKey = new (nothrow) BYTE[cbHex];
if (!pKey)
return NULL;
for (size_t i = 0; i < cbHex; i++) {
pKey[i] = (BYTE) ((HexToByte(*wszPublicKeyHexString) << 4) | HexToByte(*(wszPublicKeyHexString + 1)));
wszPublicKeyHexString += 2;
}
return (PublicKeyBlob*) pKey;
}
// Create a temporary key container name likely to be unique to this process and
// thread. Any existing container with the same name is deleted.
BOOLEAN GetKeyContainerName(LPCWSTR *pwszKeyContainer, BOOLEAN *pbTempContainer)
{
*pbTempContainer = FALSE;
if (*pwszKeyContainer != NULL)
return TRUE;
GUID guid;
HRESULT hr = CoCreateGuid(&guid);
if (FAILED(hr)) {
SetStrongNameErrorInfo(hr);
return FALSE;
}
WCHAR wszGuid[64];
if (GuidToLPWSTR(guid, wszGuid, sizeof(wszGuid) / sizeof(WCHAR)) == 0) {
SetStrongNameErrorInfo(E_UNEXPECTED); // this operation should never fail
return FALSE;
}
// Name is of form '__MSCORSN__<guid>__' where <guid> is a GUID.
const size_t cchLengthOfKeyContainer = sizeof("__MSCORSN____") + (sizeof(wszGuid) / sizeof(WCHAR)) + 1 /* null */;
LPWSTR wszKeyContainer = new (nothrow) WCHAR[cchLengthOfKeyContainer];
if (wszKeyContainer == NULL) {
SetStrongNameErrorInfo(E_OUTOFMEMORY);
return FALSE;
}
_snwprintf_s(wszKeyContainer, cchLengthOfKeyContainer - 1 /* exclude null */, _TRUNCATE,
W("__MSCORSN__%s__"),
wszGuid);
// Delete any stale container with the same name.
LocateCSP(wszKeyContainer, SN_DELETE_CONTAINER);
SNLOG((W("Creating temporary key container name '%s'\n"), wszKeyContainer));
*pwszKeyContainer = wszKeyContainer;
*pbTempContainer = TRUE;
return TRUE;
}
// Free resources allocated by GetKeyContainerName and delete the named
// container.
VOID FreeKeyContainerName(LPCWSTR wszKeyContainer, BOOLEAN bTempContainer)
{
if (bTempContainer) {
// Free the name.
delete [] (WCHAR*)wszKeyContainer;
}
}
static DWORD GetSpecialKeyFlags(PublicKeyBlob* pKey)
{
if (SN_IS_THE_KEY(pKey))
return SN_OUTFLAG_MICROSOFT_SIGNATURE;
return 0;
}
#ifdef FEATURE_STRONGNAME_MIGRATION
HRESULT VerifyCounterSignature(
PublicKeyBlob *pSignaturePublicKey,
ULONG cbSignaturePublicKey,
PublicKeyBlob *pIdentityPublicKey,
BYTE *pCounterSignature,
ULONG cbCounterSignature)
{
LIMITED_METHOD_CONTRACT;
HRESULT hr = S_OK;
HandleStrongNameCspHolder hProv(NULL);
HandleKeyHolder hKey(NULL);
HandleHashHolder hHash(NULL);
hProv = LocateCSP(NULL, SN_IGNORE_CONTAINER, GET_UNALIGNED_VAL32(&pIdentityPublicKey->HashAlgID), GET_UNALIGNED_VAL32(&pIdentityPublicKey->SigAlgID));
if (!hProv)
{
hr = HRESULT_FROM_GetLastError();
SNLOG((W("Failed to acquire a CSP: %08x"), hr));
return hr;
}
if(SN_IS_NEUTRAL_KEY(pIdentityPublicKey))
{
pIdentityPublicKey = reinterpret_cast<PublicKeyBlob *>(const_cast<BYTE *>(g_rbTheKey));
}
BYTE *pbRealPublicKey = pIdentityPublicKey->PublicKey;
DWORD cbRealPublicKey = GET_UNALIGNED_VAL32(&pIdentityPublicKey->cbPublicKey);
if (!CryptImportKey(hProv, pbRealPublicKey, cbRealPublicKey, 0, 0, &hKey))
{
hr = HRESULT_FROM_GetLastError();
SNLOG((W("Failed to import key: %08x"), hr));
return hr;
}
// Create a hash object.
if (!CryptCreateHash(hProv, GET_UNALIGNED_VAL32(&pIdentityPublicKey->HashAlgID), 0, 0, &hHash))
{
hr = HRESULT_FROM_GetLastError();
SNLOG((W("Failed to create hash: %08x"), hr));
return hr;
}
if (!CryptHashData(hHash, (BYTE*)pSignaturePublicKey, cbSignaturePublicKey, 0))
{
hr = HRESULT_FROM_GetLastError();
SNLOG((W("Failed to compute hash: %08x"), hr));
return hr;
}
#if defined(_DEBUG) && !defined(DACCESS_COMPILE)
if (hHash != (HCRYPTHASH)INVALID_HANDLE_VALUE) {
DWORD cbHash;
DWORD dwRetLen = sizeof(cbHash);
if (CryptGetHashParam(hHash, HP_HASHSIZE, (BYTE*)&cbHash, &dwRetLen, 0))
{
NewArrayHolder<BYTE> pbHash(new (nothrow) BYTE[cbHash]);
if (pbHash != NULL)
{
if (CryptGetHashParam(hHash, HP_HASHVAL, pbHash, &cbHash, 0))
{
SNLOG((W("Computed Hash Value (%u bytes):\n"), cbHash));
HexDump(pbHash, cbHash);
}
else
{
SNLOG((W("CryptGetHashParam() failed with %08X\n"), GetLastError()));
}
}
}
else
{
SNLOG((W("CryptGetHashParam() failed with %08X\n"), GetLastError()));
}
}
#endif // _DEBUG
// Verify the hash against the signature.
//DbgCount(dwInFlags & SN_INFLAG_RUNTIME ? W("RuntimeVerify") : W("FusionVerify"));
if (pCounterSignature != NULL && cbCounterSignature != 0 &&
CryptVerifySignatureW(hHash, pCounterSignature, cbCounterSignature, hKey, NULL, 0))
{
SNLOG((W("Counter-signature verification succeeded\n")));
}
else
{
SNLOG((W("Counter-signature verification failed\n")));
hr = CORSEC_E_INVALID_COUNTERSIGNATURE;
}
return hr;
}
HRESULT ParseStringArgs(
CustomAttributeParser &ca, // The Custom Attribute blob.
CaArg* pArgs, // Array of argument descriptors.
ULONG cArgs) // Count of argument descriptors.
{
LIMITED_METHOD_CONTRACT;
HRESULT hr = S_OK;
// For each expected arg...
for (ULONG ix=0; ix<cArgs; ++ix)
{
CaArg* pArg = &pArgs[ix];
if(pArg->type.tag != SERIALIZATION_TYPE_STRING)
{
return E_UNEXPECTED; // The blob shouldn't have anything other than strings
}
IfFailGo(ca.GetString(&pArg->val.str.pStr, &pArg->val.str.cbStr));
}
ErrExit:
return hr;
}
HRESULT GetVerifiedSignatureKey(__in SN_LOAD_CTX *pLoadCtx, __out PublicKeyBlob **ppPublicKey, __out_opt DWORD *pcbPublicKey)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
HRESULT hr = S_OK;
mdAssembly tkAssembly;
ReleaseHolder<IMDInternalImport> pMetaDataImport;
IfFailRet(GetMetadataImport(pLoadCtx, &tkAssembly, &pMetaDataImport));
HRESULT attributeHr;
void *pAttribute;
ULONG cbAttribute;
hr = pMetaDataImport->GetCustomAttributeByName(tkAssembly, g_AssemblySignatureKeyAttribute, const_cast<const void**>(&pAttribute), &cbAttribute);
if (SUCCEEDED(hr) && hr != S_FALSE)
{
CustomAttributeParser parser(pAttribute, cbAttribute);
IfFailRet(parser.ValidateProlog());
CaType caTypeString;
caTypeString.Init(SERIALIZATION_TYPE_STRING);
CaArg args[2];
CaArg* argPublicKey = &args[0];
argPublicKey->Init(caTypeString);
CaArg* argCounterSignature = &args[1];
argCounterSignature->Init(caTypeString);
IfFailRet(ParseStringArgs(parser, args, lengthof(args)));
StrongNameBufferHolder<PublicKeyBlob> pSignaturePublicKey;
ULONG cbSignaturePublicKey;
if (argPublicKey->val.str.pStr == NULL || argPublicKey->val.str.cbStr == 0 ||
(!GetBytesFromHex(argPublicKey->val.str.pStr, argPublicKey->val.str.cbStr, (BYTE**)(pSignaturePublicKey.GetAddr()), &cbSignaturePublicKey)) ||
!StrongNameIsValidPublicKey((BYTE*)pSignaturePublicKey.GetValue(), cbSignaturePublicKey, false))
{
return CORSEC_E_INVALID_SIGNATUREKEY;
}
NewArrayHolder<BYTE> pCounterSignature;
ULONG cbCounterSignature;
if (argCounterSignature->val.str.pStr == NULL || argCounterSignature->val.str.cbStr == 0 ||
(!GetBytesFromHex(argCounterSignature->val.str.pStr, argCounterSignature->val.str.cbStr, &pCounterSignature, &cbCounterSignature)))
{
return CORSEC_E_INVALID_COUNTERSIGNATURE;
}
StrongNameBufferHolder<PublicKeyBlob> pIdentityPublicKey = NULL;
IfFailRet(FindPublicKey(pLoadCtx, NULL, 0, &pIdentityPublicKey));
IfFailRet(VerifyCounterSignature(pSignaturePublicKey, cbSignaturePublicKey, pIdentityPublicKey, pCounterSignature, cbCounterSignature));
*ppPublicKey = pSignaturePublicKey.Extract();
if (pcbPublicKey != NULL)
*pcbPublicKey = cbSignaturePublicKey;
}
else
{
*ppPublicKey = NULL;
if (pcbPublicKey != NULL)
*pcbPublicKey = 0;
}
return hr;
}
// Checks revocation list against the assembly's public keys.
// If the identity key has been revoked, then the signature key must be non-null and
// must be in the replacement keys list to be allowed.
bool AreKeysAllowedByRevocationList(BYTE* pbAssemblyIdentityKey, DWORD cbAssemblyIdentityKey, BYTE* pbAssemblySignatureKey, DWORD cbAssemblySignatureKey)
{
LIMITED_METHOD_CONTRACT;
bool fRevoked = false;
SN_REVOCATION_REC *pRevocationRec = g_pRevocationRecords;
while (pRevocationRec)
{
if (pRevocationRec->m_cbRevokedKey == cbAssemblyIdentityKey &&
memcmp(pRevocationRec->m_pbRevokedKey, pbAssemblyIdentityKey, cbAssemblyIdentityKey) == 0)
{
fRevoked = true; // Identity key can't be trusted.
if (pbAssemblySignatureKey != NULL)
{
SN_REPLACEMENT_KEY_REC *pReplacementKeyRec = pRevocationRec->m_pReplacementKeys;
while (pReplacementKeyRec)
{
if (pReplacementKeyRec->m_cbReplacementKey == cbAssemblySignatureKey &&
memcmp(pReplacementKeyRec->m_pbReplacementKey, pbAssemblySignatureKey, cbAssemblySignatureKey) == 0)
{
// Signature key was allowed as a replacement for the revoked identity key.
return true;
}
pReplacementKeyRec = pReplacementKeyRec->m_pNext;
}
}
// We didn't find the signature key in the list of allowed replacement keys for this record.
// However, we don't return here, because another record might have the same identity key
// and allow the signature key as a replacement.
}
pRevocationRec = pRevocationRec->m_pNext;
}
return !fRevoked;
}
#endif // FEATURE_STRONGNAME_MIGRATION
// The common code used to verify a signature (taking into account whether skip
// verification is enabled for the given assembly).
HRESULT VerifySignature(__in SN_LOAD_CTX *pLoadCtx, DWORD dwInFlags, PublicKeyBlob *pRealEcmaPublicKey,__out_opt DWORD *pdwOutFlags)
{
if (pdwOutFlags)
*pdwOutFlags = 0;
// Read the public key used to sign the assembly from the assembly metadata.
// Also get the assembly name, we might need this if we fail the
// verification and need to look up a verification disablement entry.
WCHAR wszSimpleAssemblyName[MAX_PATH_FNAME + 1];
SString strFullyQualifiedAssemblyName;
BOOL bSuccess = FALSE;
#if STRONGNAME_IN_VM
BOOL bAssemblyNameFormed = FALSE;
BOOL bVerificationBegun = FALSE;
#endif
HandleKeyHolder hKey(NULL);
HandleHashHolder hHash(NULL);
HandleStrongNameCspHolder hProv(NULL);
StrongNameBufferHolder<PublicKeyBlob> pAssemblyIdentityKey;
DWORD cbAssemblyIdentityKey;
HRESULT hr = FindPublicKey(pLoadCtx,
wszSimpleAssemblyName,
sizeof(wszSimpleAssemblyName) / sizeof(WCHAR),
&pAssemblyIdentityKey,
&cbAssemblyIdentityKey);
if (FAILED(hr))
return hr;
BOOL isEcmaKey = SN_IS_NEUTRAL_KEY(pAssemblyIdentityKey);
// If we're handed the ECMA key, we translate it to the real key at this point.
// Note: gcc gets confused with the complexity of StrongNameBufferHolder<> and
// won't auto-convert pAssemblyIdentityKey to type PublicKeyBlob*, so cast it explicitly.
PublicKeyBlob *pRealPublicKey = isEcmaKey ? pRealEcmaPublicKey : static_cast<PublicKeyBlob*>(pAssemblyIdentityKey);
// An assembly can specify a signature public key in an attribute.
// If one is present, we verify the signature using that public key.
#ifdef FEATURE_STRONGNAME_MIGRATION
StrongNameBufferHolder<PublicKeyBlob> pAssemblySignaturePublicKey;
DWORD cbAssemblySignaturePublicKey;
IfFailRet(GetVerifiedSignatureKey(pLoadCtx, &pAssemblySignaturePublicKey, &cbAssemblySignaturePublicKey));
if(hr != S_FALSE) // Attribute was found
{
pRealPublicKey = pAssemblySignaturePublicKey;
}
#endif // FEATURE_STRONGNAME_MIGRATION
DWORD dwSpecialKeys = GetSpecialKeyFlags(pRealPublicKey);
// If this isn't the first time we've been called for this assembly and we
// know it was fully signed and we're confident it couldn't have been
// tampered with in the meantime, we can just skip the verification.
if (!(dwInFlags & SN_INFLAG_FORCE_VER) &&
!(dwInFlags & SN_INFLAG_INSTALL) &&
(pLoadCtx->m_pCorHeader->Flags & VAL32(COMIMAGE_FLAGS_STRONGNAMESIGNED)) &&
((dwInFlags & SN_INFLAG_ADMIN_ACCESS) || g_fCacheVerify))
{
SNLOG((W("Skipping verification due to cached result\n")));
DbgCount(dwInFlags & SN_INFLAG_RUNTIME ? W("RuntimeSkipCache") : W("FusionSkipCache"));
return S_OK;
}
#ifdef FEATURE_STRONGNAME_DELAY_SIGNING_ALLOWED
// If we're not forcing verification, let's see if there's a skip
// verification entry for this assembly. If there is we can skip all the
// hard work and just lie about the strong name now. The exception is if the
// assembly is marked as fully signed, in which case we have to force a
// verification to see if they're telling the truth.
StrongNameBufferHolder<PublicKeyBlob> pTestKey = NULL;
SN_VER_REC *pVerRec = GetVerificationRecord(wszSimpleAssemblyName, pAssemblyIdentityKey);
if (!(dwInFlags & SN_INFLAG_FORCE_VER) && !(pLoadCtx->m_pCorHeader->Flags & VAL32(COMIMAGE_FLAGS_STRONGNAMESIGNED)))
{
if (pVerRec != NULL)
{
if (pVerRec->m_wszTestPublicKey)
{
// substitute the public key with the test public key.
pTestKey = GetPublicKeyFromHex(pVerRec->m_wszTestPublicKey);
if (pTestKey != NULL)
{
SNLOG((W("Using test public key for verification due to registry entry\n")));
DbgCount(dwInFlags & SN_INFLAG_RUNTIME ? W("RuntimeSkipDelay") : W("FusionSkipDelay"));
// If the assembly was not ECMA signed, then we need to update the key that it will be
// verified with as well.
if (!isEcmaKey)
{
// When test signing, there's no way to specify a hash algorithm.
// So instead of defaulting to SHA1, we pick the algorithm the assembly
// would've been signed with, if the test key wasn't present.
// Thus we use the same algorithm when verifying the signature.
SET_UNALIGNED_VAL32(&pTestKey->HashAlgID, GET_UNALIGNED_VAL32(&pRealPublicKey->HashAlgID));
pRealPublicKey = pTestKey;
}
}
}
else
{
SNLOG((W("Skipping verification due to registry entry\n")));
DbgCount(dwInFlags & SN_INFLAG_RUNTIME ? W("RuntimeSkipDelay") : W("FusionSkipDelay"));
if (pdwOutFlags)
{
*pdwOutFlags |= dwSpecialKeys;
}
return S_OK;
}
}
}
#endif // FEATURE_STRONGNAME_DELAY_SIGNING_ALLOWED
#ifdef FEATURE_STRONGNAME_MIGRATION
if(!isEcmaKey) // We should never revoke the ecma key, as it is tied strongly to the runtime
{
if(!AreKeysAllowedByRevocationList((BYTE*)pAssemblyIdentityKey.GetValue(), cbAssemblyIdentityKey, (BYTE*)pAssemblySignaturePublicKey.GetValue(), cbAssemblySignaturePublicKey))
{
if(pAssemblySignaturePublicKey == NULL)
{
SNLOG((W("Verification failed. Assembly public key has been revoked\n")));
}
else
{
SNLOG((W("Verification failed. Assembly identity key has been revoked, an the assembly signature key isn't in the replacement key list\n")));
}
hr = CORSEC_E_INVALID_STRONGNAME;
goto Error;
}
}
#endif // FEATURE_STRONGNAME_MIGRATION
#ifdef FEATURE_CORECLR
// TritonTODO: check with security team on this
if (pLoadCtx->m_pbSignature == NULL)
{
hr = CORSEC_E_MISSING_STRONGNAME;
goto Error;
}
#endif //FEATURE_CORECLR
#if STRONGNAME_IN_VM
bVerificationBegun = TRUE;
// SN verification start event
if (ETW_TRACING_CATEGORY_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_Context, TRACE_LEVEL_INFORMATION, CLR_SECURITY_KEYWORD))
{
// form the fully qualified assembly name using the load context
bAssemblyNameFormed = FormFullyQualifiedAssemblyName(pLoadCtx, strFullyQualifiedAssemblyName);
if(bAssemblyNameFormed)
{
ETW::SecurityLog::StrongNameVerificationStart(dwInFlags,(LPWSTR)strFullyQualifiedAssemblyName.GetUnicode());
}
}
#endif // STRONGNAME_IN_VM
ALG_ID uHashAlgId = GET_UNALIGNED_VAL32(&pRealPublicKey->HashAlgID);
ALG_ID uSignAlgId = GET_UNALIGNED_VAL32(&pRealPublicKey->SigAlgID);
// Default hashing and signing algorithm IDs if necessary.
if (uHashAlgId == 0)
uHashAlgId = CALG_SHA1;
if (uSignAlgId == 0)
uSignAlgId = CALG_RSA_SIGN;
// Find a CSP supporting the required algorithms.
hProv = LocateCSP(NULL, SN_IGNORE_CONTAINER, uHashAlgId, uSignAlgId);
if (!hProv)
{
hr = HRESULT_FROM_GetLastError();
SNLOG((W("Failed to acquire a CSP: %08x"), hr));
goto Error;
}
BYTE *pbRealPublicKey;
pbRealPublicKey = pRealPublicKey->PublicKey;
DWORD cbRealPublicKey;
cbRealPublicKey = GET_UNALIGNED_VAL32(&pRealPublicKey->cbPublicKey);
if (!CryptImportKey(hProv, pbRealPublicKey, cbRealPublicKey, 0, 0, &hKey))
{
hr = HRESULT_FROM_GetLastError();
SNLOG((W("Failed to import key: %08x"), hr));
goto Error;
}
// Create a hash object.
if (!CryptCreateHash(hProv, uHashAlgId, 0, 0, &hHash))
{
hr = HRESULT_FROM_GetLastError();
SNLOG((W("Failed to create hash: %08x"), hr));
goto Error;
}
// Compute a hash over the image.
if (!ComputeHash(pLoadCtx, hHash, CalcHash, NULL))
{
hr = HRESULT_FROM_GetLastError();
SNLOG((W("Failed to compute hash: %08x"), hr));
goto Error;
}
// Verify the hash against the signature.
DbgCount(dwInFlags & SN_INFLAG_RUNTIME ? W("RuntimeVerify") : W("FusionVerify"));
if (pLoadCtx->m_pbSignature != NULL && pLoadCtx->m_cbSignature != 0 &&
CryptVerifySignatureW(hHash, pLoadCtx->m_pbSignature, pLoadCtx->m_cbSignature, hKey, NULL, 0))
{
SNLOG((W("Verification succeeded (for real)\n")));
if (pdwOutFlags)
{
*pdwOutFlags |= dwSpecialKeys | SN_OUTFLAG_WAS_VERIFIED;
}
bSuccess = TRUE;
}
else
{
SNLOG((W("Verification failed\n")));
hr = CORSEC_E_INVALID_STRONGNAME;
}
Error:
#if STRONGNAME_IN_VM
// SN verification end event
if(bVerificationBegun &&
ETW_TRACING_CATEGORY_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_Context, TRACE_LEVEL_VERBOSE, CLR_SECURITY_KEYWORD))
{
// form the fully qualified assembly name using the load context if it has not yet been formed
if(!bAssemblyNameFormed)
{
strFullyQualifiedAssemblyName.Clear();
bAssemblyNameFormed = FormFullyQualifiedAssemblyName(pLoadCtx, strFullyQualifiedAssemblyName);
}
if(bAssemblyNameFormed)
{
ETW::SecurityLog::StrongNameVerificationStop(dwInFlags,(ULONG)hr, (LPWSTR)strFullyQualifiedAssemblyName.GetUnicode());
}
}
#endif // STRONGNAME_IN_VM
if (bSuccess)
return S_OK;
else
return hr;
}
// Compute a hash over the elements of an assembly manifest file that should
// remain static (skip checksum, Authenticode signatures and strong name
// signature blob).
// This function can also be used to get the blob of bytes that would be
// hashed without actually hashing.
BOOLEAN ComputeHash(SN_LOAD_CTX *pLoadCtx, HCRYPTHASH hHash, HashFunc func, void* cookie)
{
union {
IMAGE_NT_HEADERS32 m_32;
IMAGE_NT_HEADERS64 m_64;
} sHeaders;
IMAGE_SECTION_HEADER *pSections;
ULONG i;
BYTE *pbSig = pLoadCtx->m_pbSignature;
DWORD cbSig = pLoadCtx->m_cbSignature;
#define LIMIT_CHECK(_start, _length, _fileStart, _fileLength) \
do { if (((_start) < (_fileStart)) || \
(((_start)+(_length)) < (_start)) || \
(((_start)+(_length)) < (_fileStart)) || \
(((_start)+(_length)) > ((_fileStart)+(_fileLength))) ) \
{ SetLastError(CORSEC_E_INVALID_IMAGE_FORMAT); return FALSE; } } while (false)
#define FILE_LIMIT_CHECK(_start, _length) LIMIT_CHECK(_start, _length, pLoadCtx->m_pbBase, pLoadCtx->m_dwLength)
#define SN_HASH(_start, _length) do { if (!func(hHash, (_start), (_length), 0, cookie)) return FALSE; } while (false)
#define SN_CHECK_AND_HASH(_start, _length) do { FILE_LIMIT_CHECK(_start, _length); SN_HASH(_start, _length); } while (false)
// Make sure the file size doesn't wrap around.
if (pLoadCtx->m_pbBase + pLoadCtx->m_dwLength <= pLoadCtx->m_pbBase)
{
SetLastError(CORSEC_E_INVALID_IMAGE_FORMAT);
return FALSE;
}
// Make sure the signature is completely contained within the file.
FILE_LIMIT_CHECK(pbSig, cbSig);
// Hash the DOS header if it exists.
if ((BYTE*)pLoadCtx->m_pNtHeaders != pLoadCtx->m_pbBase)
SN_CHECK_AND_HASH(pLoadCtx->m_pbBase, (DWORD)((BYTE*)pLoadCtx->m_pNtHeaders - pLoadCtx->m_pbBase));
// Add image headers minus the checksum and security data directory.
if (pLoadCtx->m_pNtHeaders->OptionalHeader.Magic == VAL16(IMAGE_NT_OPTIONAL_HDR32_MAGIC)) {
sHeaders.m_32 = *((IMAGE_NT_HEADERS32*)pLoadCtx->m_pNtHeaders);
sHeaders.m_32.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY].VirtualAddress = 0;
sHeaders.m_32.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY].Size = 0;
sHeaders.m_32.OptionalHeader.CheckSum = 0;
SN_HASH((BYTE*)&sHeaders.m_32, sizeof(sHeaders.m_32));
} else if (pLoadCtx->m_pNtHeaders->OptionalHeader.Magic == VAL16(IMAGE_NT_OPTIONAL_HDR64_MAGIC)) {
sHeaders.m_64 = *((IMAGE_NT_HEADERS64*)pLoadCtx->m_pNtHeaders);
sHeaders.m_64.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY].VirtualAddress = 0;
sHeaders.m_64.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY].Size = 0;
sHeaders.m_64.OptionalHeader.CheckSum = 0;
SN_HASH((BYTE*)&sHeaders.m_64, sizeof(sHeaders.m_64));
} else {
SetLastError(CORSEC_E_INVALID_IMAGE_FORMAT);
return FALSE;
}
// Then the section headers.
pSections = IMAGE_FIRST_SECTION(pLoadCtx->m_pNtHeaders);
SN_CHECK_AND_HASH((BYTE*)pSections, VAL16(pLoadCtx->m_pNtHeaders->FileHeader.NumberOfSections) * sizeof(IMAGE_SECTION_HEADER));
// Finally, add data from each section.
for (i = 0; i < VAL16(pLoadCtx->m_pNtHeaders->FileHeader.NumberOfSections); i++) {
BYTE *pbData = pLoadCtx->m_pbBase + VAL32(pSections[i].PointerToRawData);
DWORD cbData = VAL32(pSections[i].SizeOfRawData);
// We need to exclude the strong name signature blob from the hash. The
// blob could intersect the section in a number of ways.
if ((pbSig + cbSig) <= pbData || pbSig >= (pbData + cbData))
// No intersection at all. Hash all data.
SN_CHECK_AND_HASH(pbData, cbData);
else if (pbSig == pbData && cbSig == cbData)
// Signature consumes entire block. Hash no data.
;
else if (pbSig == pbData)
// Signature at start. Hash end.
SN_CHECK_AND_HASH(pbData + cbSig, cbData - cbSig);
else if ((pbSig + cbSig) == (pbData + cbData))
// Signature at end. Hash start.
SN_CHECK_AND_HASH(pbData, cbData - cbSig);
else {
// Signature in the middle. Hash head and tail.
SN_CHECK_AND_HASH(pbData, (DWORD)(pbSig - pbData));
SN_CHECK_AND_HASH(pbSig + cbSig, cbData - (DWORD)(pbSig + cbSig - pbData));
}
}
#if defined(_DEBUG) && !defined(DACCESS_COMPILE)
if (hHash != (HCRYPTHASH)INVALID_HANDLE_VALUE) {
DWORD cbHash;
DWORD dwRetLen = sizeof(cbHash);
if (CryptGetHashParam(hHash, HP_HASHSIZE, (BYTE*)&cbHash, &dwRetLen, 0))
{
NewArrayHolder<BYTE> pbHash(new (nothrow) BYTE[cbHash]);
if (pbHash != NULL)
{
if (CryptGetHashParam(hHash, HP_HASHVAL, pbHash, &cbHash, 0))
{
SNLOG((W("Computed Hash Value (%u bytes):\n"), cbHash));
HexDump(pbHash, cbHash);
}
else
{
SNLOG((W("CryptGetHashParam() failed with %08X\n"), GetLastError()));
}
}
}
else
{
SNLOG((W("CryptGetHashParam() failed with %08X\n"), GetLastError()));
}
}
#endif // _DEBUG
return TRUE;
#undef SN_CHECK_AND_HASH
#undef SN_HASH
#undef FILE_LIMIT_CHECK
#undef LIMIT_CHECK
}
SNAPI_(DWORD) GetHashFromAssemblyFile(LPCSTR szFilePath, // [IN] location of file to be hashed
unsigned int *piHashAlg, // [IN/OUT] constant specifying the hash algorithm (set to 0 if you want the default)
BYTE *pbHash, // [OUT] hash buffer
DWORD cchHash, // [IN] max size of buffer
DWORD *pchHash) // [OUT] length of hash byte array
{
BOOL retVal = FALSE;
BEGIN_ENTRYPOINT_NOTHROW;
// Convert filename to wide characters and call the W version of this
// function.
MAKE_WIDEPTR_FROMANSI(wszFilePath, szFilePath);
retVal = GetHashFromAssemblyFileW(wszFilePath, piHashAlg, pbHash, cchHash, pchHash);
END_ENTRYPOINT_NOTHROW;
return retVal;
}
SNAPI_(DWORD) GetHashFromAssemblyFileW(LPCWSTR wszFilePath, // [IN] location of file to be hashed
unsigned int *piHashAlg, // [IN/OUT] constant specifying the hash algorithm (set to 0 if you want the default)
BYTE *pbHash, // [OUT] hash buffer
DWORD cchHash, // [IN] max size of buffer
DWORD *pchHash) // [OUT] length of hash byte array
{
HRESULT hr;
BEGIN_ENTRYPOINT_NOTHROW;
SN_LOAD_CTX sLoadCtx;
BYTE *pbMetaData = NULL;
DWORD cbMetaData;
sLoadCtx.m_fReadOnly = TRUE;
if (!LoadAssembly(&sLoadCtx, wszFilePath, 0, FALSE))
IfFailGo(HRESULT_FROM_GetLastError());
if (sLoadCtx.m_pedecoder->CheckCorHeader())
{
pbMetaData = (BYTE *)sLoadCtx.m_pedecoder->GetMetadata();
}
if (pbMetaData == NULL) {
UnloadAssembly(&sLoadCtx);
IfFailGo(E_INVALIDARG);
}
cbMetaData = VAL32(sLoadCtx.m_pCorHeader->MetaData.Size);
hr = GetHashFromBlob(pbMetaData, cbMetaData, piHashAlg, pbHash, cchHash, pchHash);
UnloadAssembly(&sLoadCtx);
ErrExit:
END_ENTRYPOINT_NOTHROW;
return hr;
}
SNAPI_(DWORD) GetHashFromFile(LPCSTR szFilePath, // [IN] location of file to be hashed
unsigned int *piHashAlg, // [IN/OUT] constant specifying the hash algorithm (set to 0 if you want the default)
BYTE *pbHash, // [OUT] hash buffer
DWORD cchHash, // [IN] max size of buffer
DWORD *pchHash) // [OUT] length of hash byte array
{
HRESULT hr = S_OK;
BEGIN_ENTRYPOINT_NOTHROW;
HANDLE hFile = CreateFileA(szFilePath,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,
NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
hr = HRESULT_FROM_GetLastError();
}
else
{
hr = GetHashFromHandle(hFile, piHashAlg, pbHash, cchHash, pchHash);
CloseHandle(hFile);
}
END_ENTRYPOINT_NOTHROW;
return hr;
}
SNAPI_(DWORD) GetHashFromFileW(LPCWSTR wszFilePath, // [IN] location of file to be hashed
unsigned int *piHashAlg, // [IN/OUT] constant specifying the hash algorithm (set to 0 if you want the default)
BYTE *pbHash, // [OUT] hash buffer
DWORD cchHash, // [IN] max size of buffer
DWORD *pchHash) // [OUT] length of hash byte array
{
HRESULT hr = S_OK;
BEGIN_ENTRYPOINT_NOTHROW;
HANDLE hFile = WszCreateFile(wszFilePath,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,
NULL);
if (hFile == INVALID_HANDLE_VALUE)
IfFailGo(HRESULT_FROM_GetLastError());
hr = GetHashFromHandle(hFile, piHashAlg, pbHash, cchHash, pchHash);
CloseHandle(hFile);
ErrExit:
END_ENTRYPOINT_NOTHROW;
return hr;
}
SNAPI_(DWORD) GetHashFromHandle(HANDLE hFile, // [IN] handle of file to be hashed
unsigned int *piHashAlg, // [IN/OUT] constant specifying the hash algorithm (set to 0 if you want the default)
BYTE *pbHash, // [OUT] hash buffer
DWORD cchHash, // [IN] max size of buffer
DWORD *pchHash) // [OUT] length of hash byte array
{
HRESULT hr;
BEGIN_ENTRYPOINT_NOTHROW;
PBYTE pbBuffer = NULL;
DWORD dwFileLen = SafeGetFileSize(hFile, 0);
if (dwFileLen == 0xffffffff)
IfFailGo(HRESULT_FROM_GetLastError());
if (SetFilePointer(hFile, 0, NULL, FILE_BEGIN) == 0xFFFFFFFF)
IfFailGo(HRESULT_FROM_GetLastError());
DWORD dwResultLen;
pbBuffer = new (nothrow) BYTE[dwFileLen];
IfNullGo(pbBuffer);
if (ReadFile(hFile, pbBuffer, dwFileLen, &dwResultLen, NULL))
hr = GetHashFromBlob(pbBuffer, dwResultLen, piHashAlg, pbHash, cchHash, pchHash);
else
hr = HRESULT_FROM_GetLastError();
delete[] pbBuffer;
ErrExit:
END_ENTRYPOINT_NOTHROW;
return hr;
}
SNAPI_(DWORD) GetHashFromBlob(BYTE *pbBlob, // [IN] pointer to memory block to hash
DWORD cchBlob, // [IN] length of blob
unsigned int *piHashAlg, // [IN/OUT] constant specifying the hash algorithm (set to 0 if you want the default)
BYTE *pbHash, // [OUT] hash buffer
DWORD cchHash, // [IN] max size of buffer
DWORD *pchHash) // [OUT] length of hash byte array
{
HRESULT hr = S_OK;
BEGIN_ENTRYPOINT_NOTHROW;
HandleStrongNameCspHolder hProv(NULL);
CapiHashHolder hHash(NULL);
if (!piHashAlg || !pbHash || !pchHash)
IfFailGo(E_INVALIDARG);
if (!(*piHashAlg))
*piHashAlg = CALG_SHA1;
*pchHash = cchHash;
hProv = LocateCSP(NULL, SN_IGNORE_CONTAINER, *piHashAlg);
if (!hProv ||
(!CryptCreateHash(hProv, *piHashAlg, 0, 0, &hHash)) ||
(!CryptHashData(hHash, pbBlob, cchBlob, 0)) ||
(!CryptGetHashParam(hHash, HP_HASHVAL, pbHash, pchHash, 0)))
hr = HRESULT_FROM_GetLastError();
ErrExit:
END_ENTRYPOINT_NOTHROW;
return hr;
}
#endif // #ifndef DACCESS_COMPILE
#else // !defined(FEATURE_CORECLR) || (defined(CROSSGEN_COMPILE) && !defined(PLATFORM_UNIX))
#define InitStrongName() S_OK
#endif // !defined(FEATURE_CORECLR) || (defined(CROSSGEN_COMPILE) && !defined(PLATFORM_UNIX))
// Free buffer allocated by routines below.
SNAPI_(VOID) StrongNameFreeBuffer(BYTE *pbMemory) // [in] address of memory to free
{
BEGIN_ENTRYPOINT_VOIDRET;
SNLOG((W("StrongNameFreeBuffer(%08X)\n"), pbMemory));
if (pbMemory != (BYTE*)SN_THE_KEY() && pbMemory != g_rbNeutralPublicKey)
delete [] pbMemory;
END_ENTRYPOINT_VOIDRET;
}
#ifndef DACCESS_COMPILE
// Retrieve per-thread context, lazily allocating it if necessary.
SN_THREAD_CTX *GetThreadContext()
{
SN_THREAD_CTX *pThreadCtx = (SN_THREAD_CTX*)ClrFlsGetValue(TlsIdx_StrongName);
if (pThreadCtx == NULL) {
pThreadCtx = new (nothrow) SN_THREAD_CTX;
if (pThreadCtx == NULL)
return NULL;
pThreadCtx->m_dwLastError = S_OK;
#if !defined(FEATURE_CORECLR) || (defined(CROSSGEN_COMPILE) && !defined(PLATFORM_UNIX))
for (ULONG i = 0; i < CachedCspCount; i++)
{
pThreadCtx->m_hProv[i] = NULL;
}
#endif // !FEATURE_CORECLR || (CROSSGEN_COMPILE && !PLATFORM_UNIX)
EX_TRY {
ClrFlsSetValue(TlsIdx_StrongName, pThreadCtx);
}
EX_CATCH {
delete pThreadCtx;
pThreadCtx = NULL;
}
EX_END_CATCH (SwallowAllExceptions);
}
return pThreadCtx;
}
// Set the per-thread last error code.
VOID SetStrongNameErrorInfo(DWORD dwStatus)
{
SN_THREAD_CTX *pThreadCtx = GetThreadContext();
if (pThreadCtx == NULL)
// We'll return E_OUTOFMEMORY when we attempt to get the error.
return;
pThreadCtx->m_dwLastError = dwStatus;
}
#endif // !DACCESS_COMPILE
// Return last error.
SNAPI_(DWORD) StrongNameErrorInfo(VOID)
{
HRESULT hr = E_FAIL;
BEGIN_ENTRYPOINT_NOTHROW;
#ifndef DACCESS_COMPILE
SN_THREAD_CTX *pThreadCtx = GetThreadContext();
if (pThreadCtx == NULL)
hr = E_OUTOFMEMORY;
else
hr = pThreadCtx->m_dwLastError;
#else
hr = E_FAIL;
#endif // #ifndef DACCESS_COMPILE
END_ENTRYPOINT_NOTHROW;
return hr;
}
// Create a strong name token from a public key blob.
SNAPI StrongNameTokenFromPublicKey(BYTE *pbPublicKeyBlob, // [in] public key blob
ULONG cbPublicKeyBlob,
BYTE **ppbStrongNameToken, // [out] strong name token
ULONG *pcbStrongNameToken)
{
BOOLEAN retVal = FALSE;
BEGIN_ENTRYPOINT_VOIDRET;
#ifndef DACCESS_COMPILE
#ifndef FEATURE_CORECLR
HCRYPTPROV hProv = NULL;
HCRYPTHASH hHash = NULL;
HCRYPTKEY hKey = NULL;
DWORD dwHashLen;
DWORD dwRetLen;
NewArrayHolder<BYTE> pHash(NULL);
#else // !FEATURE_CORECLR
SHA1Hash sha1;
BYTE *pHash = NULL;
#endif // !FEATURE_CORECLR
DWORD i;
DWORD cbKeyBlob;
PublicKeyBlob *pPublicKey = NULL;
DWORD dwHashLenMinusTokenSize = 0;
SNLOG((W("StrongNameTokenFromPublicKey(%08X, %08X, %08X, %08X)\n"), pbPublicKeyBlob, cbPublicKeyBlob, ppbStrongNameToken, pcbStrongNameToken));
#if STRONGNAME_IN_VM
FireEtwSecurityCatchCall_V1(GetClrInstanceId());
#endif // STRONGNAME_IN_VM
SN_COMMON_PROLOG();
if (pbPublicKeyBlob == NULL)
SN_ERROR(E_POINTER);
if (!StrongNameIsValidPublicKey(pbPublicKeyBlob, cbPublicKeyBlob, false))
SN_ERROR(CORSEC_E_INVALID_PUBLICKEY);
if (ppbStrongNameToken == NULL)
SN_ERROR(E_POINTER);
if (pcbStrongNameToken == NULL)
SN_ERROR(E_POINTER);
// Allocate a buffer for the output token.
*ppbStrongNameToken = new (nothrow) BYTE[SN_SIZEOF_TOKEN];
if (*ppbStrongNameToken == NULL) {
SetStrongNameErrorInfo(E_OUTOFMEMORY);
goto Exit;
}
*pcbStrongNameToken = SN_SIZEOF_TOKEN;
// We cache a couple of common cases.
if (SN_IS_NEUTRAL_KEY(pbPublicKeyBlob)) {
memcpy_s(*ppbStrongNameToken, *pcbStrongNameToken, g_rbNeutralPublicKeyToken, SN_SIZEOF_TOKEN);
retVal = TRUE;
goto Exit;
}
if (cbPublicKeyBlob == SN_SIZEOF_THE_KEY() &&
memcmp(pbPublicKeyBlob, SN_THE_KEY(), cbPublicKeyBlob) == 0) {
memcpy_s(*ppbStrongNameToken, *pcbStrongNameToken, SN_THE_KEYTOKEN(), SN_SIZEOF_TOKEN);
retVal = TRUE;
goto Exit;
}
#ifdef FEATURE_CORECLR
if (SN_IS_THE_SILVERLIGHT_PLATFORM_KEY(pbPublicKeyBlob))
{
memcpy_s(*ppbStrongNameToken, *pcbStrongNameToken, SN_THE_SILVERLIGHT_PLATFORM_KEYTOKEN(), SN_SIZEOF_TOKEN);
retVal = TRUE;
goto Exit;
}
if (SN_IS_THE_SILVERLIGHT_KEY(pbPublicKeyBlob))
{
memcpy_s(*ppbStrongNameToken, *pcbStrongNameToken, SN_THE_SILVERLIGHT_KEYTOKEN(), SN_SIZEOF_TOKEN);
retVal = TRUE;
goto Exit;
}
#ifdef FEATURE_WINDOWSPHONE
if (SN_IS_THE_MICROSOFT_PHONE_KEY(pbPublicKeyBlob))
{
memcpy_s(*ppbStrongNameToken, *pcbStrongNameToken, SN_THE_MICROSOFT_PHONE_KEYTOKEN(), SN_SIZEOF_TOKEN);
retVal = TRUE;
goto Exit;
}
if (SN_IS_THE_MICROSOFT_XNA_KEY(pbPublicKeyBlob))
{
memcpy_s(*ppbStrongNameToken, *pcbStrongNameToken, SN_THE_MICROSOFT_XNA_KEYTOKEN(), SN_SIZEOF_TOKEN);
retVal = TRUE;
goto Exit;
}
#endif //FEATURE_WINDOWSPHONE
#endif //FEATURE_CORECLR
// To compute the correct public key token, we need to make sure the public key blob
// was not padded with extra bytes that CAPI CryptImportKey would've ignored.
// Without this round trip, we would blindly compute the hash over the padded bytes
// which could make finding a public key token collision a significantly easier task
// since an attacker wouldn't need to work hard on generating valid key pairs before hashing.
if (cbPublicKeyBlob <= sizeof(PublicKeyBlob)) {
SetLastError(CORSEC_E_INVALID_PUBLICKEY);
goto Error;
}
// Check that the blob type is PUBLICKEYBLOB.
pPublicKey = (PublicKeyBlob*) pbPublicKeyBlob;
if (pPublicKey->PublicKey + GET_UNALIGNED_VAL32(&pPublicKey->cbPublicKey) < pPublicKey->PublicKey) {
SetLastError(CORSEC_E_INVALID_PUBLICKEY);
goto Error;
}
if (cbPublicKeyBlob < SN_SIZEOF_KEY(pPublicKey)) {
SetLastError(CORSEC_E_INVALID_PUBLICKEY);
goto Error;
}
if (*(BYTE*) pPublicKey->PublicKey /* PUBLICKEYSTRUC->bType */ != PUBLICKEYBLOB) {
SetLastError(CORSEC_E_INVALID_PUBLICKEY);
goto Error;
}
#ifndef FEATURE_CORECLR
// Look for a CSP to hash the public key.
hProv = LocateCSP(NULL, SN_HASH_SHA1_ONLY);
if (!hProv)
goto Error;
if (!CryptImportKey(hProv,
pPublicKey->PublicKey,
GET_UNALIGNED_VAL32(&pPublicKey->cbPublicKey),
0,
0,
&hKey))
goto Error;
cbKeyBlob = sizeof(DWORD);
if (!CryptExportKey(hKey, 0, PUBLICKEYBLOB, 0, NULL, &cbKeyBlob))
goto Error;
if ((offsetof(PublicKeyBlob, PublicKey) + cbKeyBlob) != cbPublicKeyBlob) {
SetLastError(CORSEC_E_INVALID_PUBLICKEY);
goto Error;
}
// Create a hash object.
if (!CryptCreateHash(hProv, CALG_SHA1, 0, 0, &hHash))
goto Error;
// Compute a hash over the public key.
if (!CryptHashData(hHash, pbPublicKeyBlob, cbPublicKeyBlob, 0))
goto Error;
// Get the length of the hash.
dwRetLen = sizeof(dwHashLen);
if (!CryptGetHashParam(hHash, HP_HASHSIZE, (BYTE*)&dwHashLen, &dwRetLen, 0))
goto Error;
// Allocate a temporary block to hold the hash.
pHash = new (nothrow) BYTE[dwHashLen];
if (pHash == NULL)
{
SetLastError(E_OUTOFMEMORY);
goto Error;
}
// Read the hash value.
if (!CryptGetHashParam(hHash, HP_HASHVAL, pHash, &dwHashLen, 0))
goto Error;
// We no longer need the hash object or the provider.
CryptDestroyHash(hHash);
CryptDestroyKey(hKey);
FreeCSP(hProv);
// Take the last few bytes of the hash value for our token. (These are the
// low order bytes from a network byte order point of view). Reverse the
// order of these bytes in the output buffer to get host byte order.
_ASSERTE(dwHashLen >= SN_SIZEOF_TOKEN);
if (!ClrSafeInt<DWORD>::subtraction(dwHashLen, SN_SIZEOF_TOKEN, dwHashLenMinusTokenSize))
{
SetLastError(COR_E_OVERFLOW);
goto Error;
}
#else // !FEATURE_CORECLR
// Compute a hash over the public key.
sha1.AddData(pbPublicKeyBlob, cbPublicKeyBlob);
pHash = sha1.GetHash();
static_assert(SHA1_HASH_SIZE >= SN_SIZEOF_TOKEN, "SN_SIZEOF_TOKEN must be smaller or equal to the SHA1_HASH_SIZE");
dwHashLenMinusTokenSize = SHA1_HASH_SIZE - SN_SIZEOF_TOKEN;
#endif // !FEATURE_CORECLR
// Take the last few bytes of the hash value for our token. (These are the
// low order bytes from a network byte order point of view). Reverse the
// order of these bytes in the output buffer to get host byte order.
for (i = 0; i < SN_SIZEOF_TOKEN; i++)
(*ppbStrongNameToken)[SN_SIZEOF_TOKEN - (i + 1)] = pHash[i + dwHashLenMinusTokenSize];
retVal = TRUE;
goto Exit;
Error:
SetStrongNameErrorInfo(HRESULT_FROM_GetLastError());
#ifndef FEATURE_CORECLR
if (hHash)
CryptDestroyHash(hHash);
if (hKey)
CryptDestroyKey(hKey);
if (hProv)
FreeCSP(hProv);
#endif // !FEATURE_CORECLR
if (*ppbStrongNameToken) {
delete [] *ppbStrongNameToken;
*ppbStrongNameToken = NULL;
}
Exit:
#else
DacNotImpl();
#endif // #ifndef DACCESS_COMPILE
END_ENTRYPOINT_VOIDRET;
return retVal;
}
| iamjasonp/coreclr | src/strongname/api/strongname.cpp | C++ | mit | 177,323 |
// WebcamJS v1.0.21
// Webcam library for capturing JPEG/PNG images in JavaScript
// Attempts getUserMedia, falls back to Flash
// Author: Joseph Huckaby: http://github.com/jhuckaby
// Based on JPEGCam: http://code.google.com/p/jpegcam/
// Copyright (c) 2012 - 2017 Joseph Huckaby
// Licensed under the MIT License
(function(window) {
var _userMedia;
// declare error types
// inheritance pattern here:
// https://stackoverflow.com/questions/783818/how-do-i-create-a-custom-error-in-javascript
function FlashError() {
var temp = Error.apply(this, arguments);
temp.name = this.name = "FlashError";
this.stack = temp.stack;
this.message = temp.message;
}
function WebcamError() {
var temp = Error.apply(this, arguments);
temp.name = this.name = "WebcamError";
this.stack = temp.stack;
this.message = temp.message;
}
IntermediateInheritor = function() {};
IntermediateInheritor.prototype = Error.prototype;
FlashError.prototype = new IntermediateInheritor();
WebcamError.prototype = new IntermediateInheritor();
var Webcam = {
version: '1.0.20',
// globals
protocol: location.protocol.match(/https/i) ? 'https' : 'http',
loaded: false, // true when webcam movie finishes loading
live: false, // true when webcam is initialized and ready to snap
userMedia: true, // true when getUserMedia is supported natively
iOS: /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream,
params: {
width: 0,
height: 0,
dest_width: 0, // size of captured image
dest_height: 0, // these default to width/height
image_format: 'jpeg', // image format (may be jpeg or png)
jpeg_quality: 90, // jpeg image quality from 0 (worst) to 100 (best)
enable_flash: true, // enable flash fallback,
force_flash: false, // force flash mode,
flip_horiz: false, // flip image horiz (mirror mode)
fps: 30, // camera frames per second
upload_name: 'webcam', // name of file in upload post data
constraints: null, // custom user media constraints,
swfURL: '', // URI to webcam.swf movie (defaults to the js location)
flashNotDetectedText: 'ERROR: No Adobe Flash Player detected. Webcam.js relies on Flash for browsers that do not support getUserMedia (like yours).',
noInterfaceFoundText: 'No supported webcam interface found.',
unfreeze_snap: true, // Whether to unfreeze the camera after snap (defaults to true)
iosPlaceholderText: 'Click here to open camera.',
user_callback: null, // callback function for snapshot (used if no user_callback parameter given to snap function)
user_canvas: null // user provided canvas for snapshot (used if no user_canvas parameter given to snap function)
},
errors: {
FlashError: FlashError,
WebcamError: WebcamError
},
hooks: {}, // callback hook functions
init: function() {
// initialize, check for getUserMedia support
var self = this;
// Setup getUserMedia, with polyfill for older browsers
// Adapted from: https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia
this.mediaDevices = (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) ?
navigator.mediaDevices : ((navigator.mozGetUserMedia || navigator.webkitGetUserMedia) ? {
getUserMedia: function(c) {
return new Promise(function(y, n) {
(navigator.mozGetUserMedia ||
navigator.webkitGetUserMedia).call(navigator, c, y, n);
});
}
} : null);
window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
this.userMedia = this.userMedia && !!this.mediaDevices && !!window.URL;
// Older versions of firefox (< 21) apparently claim support but user media does not actually work
if (navigator.userAgent.match(/Firefox\D+(\d+)/)) {
if (parseInt(RegExp.$1, 10) < 21) this.userMedia = null;
}
// Make sure media stream is closed when navigating away from page
if (this.userMedia) {
window.addEventListener( 'beforeunload', function(event) {
self.reset();
} );
}
},
exifOrientation: function(binFile) {
// extract orientation information from the image provided by iOS
// algorithm based on exif-js
var dataView = new DataView(binFile);
if ((dataView.getUint8(0) != 0xFF) || (dataView.getUint8(1) != 0xD8)) {
console.log('Not a valid JPEG file');
return 0;
}
var offset = 2;
var marker = null;
while (offset < binFile.byteLength) {
// find 0xFFE1 (225 marker)
if (dataView.getUint8(offset) != 0xFF) {
console.log('Not a valid marker at offset ' + offset + ', found: ' + dataView.getUint8(offset));
return 0;
}
marker = dataView.getUint8(offset + 1);
if (marker == 225) {
offset += 4;
var str = "";
for (n = 0; n < 4; n++) {
str += String.fromCharCode(dataView.getUint8(offset+n));
}
if (str != 'Exif') {
console.log('Not valid EXIF data found');
return 0;
}
offset += 6; // tiffOffset
var bigEnd = null;
// test for TIFF validity and endianness
if (dataView.getUint16(offset) == 0x4949) {
bigEnd = false;
} else if (dataView.getUint16(offset) == 0x4D4D) {
bigEnd = true;
} else {
console.log("Not valid TIFF data! (no 0x4949 or 0x4D4D)");
return 0;
}
if (dataView.getUint16(offset+2, !bigEnd) != 0x002A) {
console.log("Not valid TIFF data! (no 0x002A)");
return 0;
}
var firstIFDOffset = dataView.getUint32(offset+4, !bigEnd);
if (firstIFDOffset < 0x00000008) {
console.log("Not valid TIFF data! (First offset less than 8)", dataView.getUint32(offset+4, !bigEnd));
return 0;
}
// extract orientation data
var dataStart = offset + firstIFDOffset;
var entries = dataView.getUint16(dataStart, !bigEnd);
for (var i=0; i<entries; i++) {
var entryOffset = dataStart + i*12 + 2;
if (dataView.getUint16(entryOffset, !bigEnd) == 0x0112) {
var valueType = dataView.getUint16(entryOffset+2, !bigEnd);
var numValues = dataView.getUint32(entryOffset+4, !bigEnd);
if (valueType != 3 && numValues != 1) {
console.log('Invalid EXIF orientation value type ('+valueType+') or count ('+numValues+')');
return 0;
}
var value = dataView.getUint16(entryOffset + 8, !bigEnd);
if (value < 1 || value > 8) {
console.log('Invalid EXIF orientation value ('+value+')');
return 0;
}
return value;
}
}
} else {
offset += 2+dataView.getUint16(offset+2);
}
}
return 0;
},
fixOrientation: function(origObjURL, orientation, targetImg) {
// fix image orientation based on exif orientation data
// exif orientation information
// http://www.impulseadventure.com/photo/exif-orientation.html
// link source wikipedia (https://en.wikipedia.org/wiki/Exif#cite_note-20)
var img = new Image();
img.addEventListener('load', function(event) {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
// switch width height if orientation needed
if (orientation < 5) {
canvas.width = img.width;
canvas.height = img.height;
} else {
canvas.width = img.height;
canvas.height = img.width;
}
// transform (rotate) image - see link at beginning this method
switch (orientation) {
case 2: ctx.transform(-1, 0, 0, 1, img.width, 0); break;
case 3: ctx.transform(-1, 0, 0, -1, img.width, img.height); break;
case 4: ctx.transform(1, 0, 0, -1, 0, img.height); break;
case 5: ctx.transform(0, 1, 1, 0, 0, 0); break;
case 6: ctx.transform(0, 1, -1, 0, img.height , 0); break;
case 7: ctx.transform(0, -1, -1, 0, img.height, img.width); break;
case 8: ctx.transform(0, -1, 1, 0, 0, img.width); break;
}
ctx.drawImage(img, 0, 0);
// pass rotated image data to the target image container
targetImg.src = canvas.toDataURL();
}, false);
// start transformation by load event
img.src = origObjURL;
},
attach: function(elem) {
// create webcam preview and attach to DOM element
// pass in actual DOM reference, ID, or CSS selector
if (typeof(elem) == 'string') {
elem = document.getElementById(elem) || document.querySelector(elem);
}
if (!elem) {
return this.dispatch('error', new WebcamError("Could not locate DOM element to attach to."));
}
this.container = elem;
elem.innerHTML = ''; // start with empty element
// insert "peg" so we can insert our preview canvas adjacent to it later on
var peg = document.createElement('div');
elem.appendChild( peg );
this.peg = peg;
// set width/height if not already set
if (!this.params.width) this.params.width = elem.offsetWidth;
if (!this.params.height) this.params.height = elem.offsetHeight;
// make sure we have a nonzero width and height at this point
if (!this.params.width || !this.params.height) {
return this.dispatch('error', new WebcamError("No width and/or height for webcam. Please call set() first, or attach to a visible element."));
}
// set defaults for dest_width / dest_height if not set
if (!this.params.dest_width) this.params.dest_width = this.params.width;
if (!this.params.dest_height) this.params.dest_height = this.params.height;
this.userMedia = _userMedia === undefined ? this.userMedia : _userMedia;
// if force_flash is set, disable userMedia
if (this.params.force_flash) {
_userMedia = this.userMedia;
this.userMedia = null;
}
// check for default fps
if (typeof this.params.fps !== "number") this.params.fps = 30;
// adjust scale if dest_width or dest_height is different
var scaleX = this.params.width / this.params.dest_width;
var scaleY = this.params.height / this.params.dest_height;
if (this.userMedia) {
// setup webcam video container
var video = document.createElement('video');
video.setAttribute('autoplay', 'autoplay');
video.style.width = '' + this.params.dest_width + 'px';
video.style.height = '' + this.params.dest_height + 'px';
if ((scaleX != 1.0) || (scaleY != 1.0)) {
elem.style.overflow = 'hidden';
video.style.webkitTransformOrigin = '0px 0px';
video.style.mozTransformOrigin = '0px 0px';
video.style.msTransformOrigin = '0px 0px';
video.style.oTransformOrigin = '0px 0px';
video.style.transformOrigin = '0px 0px';
video.style.webkitTransform = 'scaleX('+scaleX+') scaleY('+scaleY+')';
video.style.mozTransform = 'scaleX('+scaleX+') scaleY('+scaleY+')';
video.style.msTransform = 'scaleX('+scaleX+') scaleY('+scaleY+')';
video.style.oTransform = 'scaleX('+scaleX+') scaleY('+scaleY+')';
video.style.transform = 'scaleX('+scaleX+') scaleY('+scaleY+')';
}
// add video element to dom
elem.appendChild( video );
this.video = video;
// ask user for access to their camera
var self = this;
this.mediaDevices.getUserMedia({
"audio": false,
"video": this.params.constraints || {
width: this.params.dest_width,
height: this.params.dest_height
}
})
.then( function(stream) {
// got access, attach stream to video
video.onloadedmetadata = function(e) {
self.stream = stream;
self.loaded = true;
self.live = true;
self.dispatch('load');
self.dispatch('live');
self.flip();
};
video.src = window.URL.createObjectURL( stream ) || stream;
})
.catch( function(err) {
// JH 2016-07-31 Instead of dispatching error, now falling back to Flash if userMedia fails (thx @john2014)
// JH 2016-08-07 But only if flash is actually installed -- if not, dispatch error here and now.
if (self.params.enable_flash && self.detectFlash()) {
setTimeout( function() { self.params.force_flash = 1; self.attach(elem); }, 1 );
}
else {
self.dispatch('error', err);
}
});
}
else if (this.iOS) {
// prepare HTML elements
var div = document.createElement('div');
div.id = this.container.id+'-ios_div';
div.className = 'webcamjs-ios-placeholder';
div.style.width = '' + this.params.width + 'px';
div.style.height = '' + this.params.height + 'px';
div.style.textAlign = 'center';
div.style.display = 'table-cell';
div.style.verticalAlign = 'middle';
div.style.backgroundRepeat = 'no-repeat';
div.style.backgroundSize = 'contain';
div.style.backgroundPosition = 'center';
var span = document.createElement('span');
span.className = 'webcamjs-ios-text';
span.innerHTML = this.params.iosPlaceholderText;
div.appendChild(span);
var img = document.createElement('img');
img.id = this.container.id+'-ios_img';
img.style.width = '' + this.params.dest_width + 'px';
img.style.height = '' + this.params.dest_height + 'px';
img.style.display = 'none';
div.appendChild(img);
var input = document.createElement('input');
input.id = this.container.id+'-ios_input';
input.setAttribute('type', 'file');
input.setAttribute('accept', 'image/*');
input.setAttribute('capture', 'camera');
var self = this;
var params = this.params;
// add input listener to load the selected image
input.addEventListener('change', function(event) {
if (event.target.files.length > 0 && event.target.files[0].type.indexOf('image/') == 0) {
var objURL = URL.createObjectURL(event.target.files[0]);
// load image with auto scale and crop
var image = new Image();
image.addEventListener('load', function(event) {
var canvas = document.createElement('canvas');
canvas.width = params.dest_width;
canvas.height = params.dest_height;
var ctx = canvas.getContext('2d');
// crop and scale image for final size
ratio = Math.min(image.width / params.dest_width, image.height / params.dest_height);
var sw = params.dest_width * ratio;
var sh = params.dest_height * ratio;
var sx = (image.width - sw) / 2;
var sy = (image.height - sh) / 2;
ctx.drawImage(image, sx, sy, sw, sh, 0, 0, params.dest_width, params.dest_height);
var dataURL = canvas.toDataURL();
img.src = dataURL;
div.style.backgroundImage = "url('"+dataURL+"')";
}, false);
// read EXIF data
var fileReader = new FileReader();
fileReader.addEventListener('load', function(e) {
var orientation = self.exifOrientation(e.target.result);
if (orientation > 1) {
// image need to rotate (see comments on fixOrientation method for more information)
// transform image and load to image object
self.fixOrientation(objURL, orientation, image);
} else {
// load image data to image object
image.src = objURL;
}
}, false);
// Convert image data to blob format
var http = new XMLHttpRequest();
http.open("GET", objURL, true);
http.responseType = "blob";
http.onload = function(e) {
if (this.status == 200 || this.status === 0) {
fileReader.readAsArrayBuffer(this.response);
}
};
http.send();
}
}, false);
input.style.display = 'none';
elem.appendChild(input);
// make div clickable for open camera interface
div.addEventListener('click', function(event) {
if (params.user_callback) {
// global user_callback defined - create the snapshot
self.snap(params.user_callback, params.user_canvas);
} else {
// no global callback definied for snapshot, load image and wait for external snap method call
input.style.display = 'block';
input.focus();
input.click();
input.style.display = 'none';
}
}, false);
elem.appendChild(div);
this.loaded = true;
this.live = true;
}
else if (this.params.enable_flash && this.detectFlash()) {
// flash fallback
window.Webcam = Webcam; // needed for flash-to-js interface
var div = document.createElement('div');
div.innerHTML = this.getSWFHTML();
elem.appendChild( div );
}
else {
this.dispatch('error', new WebcamError( this.params.noInterfaceFoundText ));
}
// setup final crop for live preview
if (this.params.crop_width && this.params.crop_height) {
var scaled_crop_width = Math.floor( this.params.crop_width * scaleX );
var scaled_crop_height = Math.floor( this.params.crop_height * scaleY );
elem.style.width = '' + scaled_crop_width + 'px';
elem.style.height = '' + scaled_crop_height + 'px';
elem.style.overflow = 'hidden';
elem.scrollLeft = Math.floor( (this.params.width / 2) - (scaled_crop_width / 2) );
elem.scrollTop = Math.floor( (this.params.height / 2) - (scaled_crop_height / 2) );
}
else {
// no crop, set size to desired
elem.style.width = '' + this.params.width + 'px';
elem.style.height = '' + this.params.height + 'px';
}
},
reset: function() {
// shutdown camera, reset to potentially attach again
if (this.preview_active) this.unfreeze();
// attempt to fix issue #64
this.unflip();
if (this.userMedia) {
if (this.stream) {
if (this.stream.getVideoTracks) {
// get video track to call stop on it
var tracks = this.stream.getVideoTracks();
if (tracks && tracks[0] && tracks[0].stop) tracks[0].stop();
}
else if (this.stream.stop) {
// deprecated, may be removed in future
this.stream.stop();
}
}
delete this.stream;
delete this.video;
}
if ((this.userMedia !== true) && this.loaded && !this.iOS) {
// call for turn off camera in flash
var movie = this.getMovie();
if (movie && movie._releaseCamera) movie._releaseCamera();
}
if (this.container) {
this.container.innerHTML = '';
delete this.container;
}
this.loaded = false;
this.live = false;
},
set: function() {
// set one or more params
// variable argument list: 1 param = hash, 2 params = key, value
if (arguments.length == 1) {
for (var key in arguments[0]) {
this.params[key] = arguments[0][key];
}
}
else {
this.params[ arguments[0] ] = arguments[1];
}
},
on: function(name, callback) {
// set callback hook
name = name.replace(/^on/i, '').toLowerCase();
if (!this.hooks[name]) this.hooks[name] = [];
this.hooks[name].push( callback );
},
off: function(name, callback) {
// remove callback hook
name = name.replace(/^on/i, '').toLowerCase();
if (this.hooks[name]) {
if (callback) {
// remove one selected callback from list
var idx = this.hooks[name].indexOf(callback);
if (idx > -1) this.hooks[name].splice(idx, 1);
}
else {
// no callback specified, so clear all
this.hooks[name] = [];
}
}
},
dispatch: function() {
// fire hook callback, passing optional value to it
var name = arguments[0].replace(/^on/i, '').toLowerCase();
var args = Array.prototype.slice.call(arguments, 1);
if (this.hooks[name] && this.hooks[name].length) {
for (var idx = 0, len = this.hooks[name].length; idx < len; idx++) {
var hook = this.hooks[name][idx];
if (typeof(hook) == 'function') {
// callback is function reference, call directly
hook.apply(this, args);
}
else if ((typeof(hook) == 'object') && (hook.length == 2)) {
// callback is PHP-style object instance method
hook[0][hook[1]].apply(hook[0], args);
}
else if (window[hook]) {
// callback is global function name
window[ hook ].apply(window, args);
}
} // loop
return true;
}
else if (name == 'error') {
if ((args[0] instanceof FlashError) || (args[0] instanceof WebcamError)) {
message = args[0].message;
} else {
message = "Could not access webcam: " + args[0].name + ": " +
args[0].message + " " + args[0].toString();
}
// default error handler if no custom one specified
alert("Webcam.js Error: " + message);
}
return false; // no hook defined
},
setSWFLocation: function(value) {
// for backward compatibility.
this.set('swfURL', value);
},
detectFlash: function() {
// return true if browser supports flash, false otherwise
// Code snippet borrowed from: https://github.com/swfobject/swfobject
var SHOCKWAVE_FLASH = "Shockwave Flash",
SHOCKWAVE_FLASH_AX = "ShockwaveFlash.ShockwaveFlash",
FLASH_MIME_TYPE = "application/x-shockwave-flash",
win = window,
nav = navigator,
hasFlash = false;
if (typeof nav.plugins !== "undefined" && typeof nav.plugins[SHOCKWAVE_FLASH] === "object") {
var desc = nav.plugins[SHOCKWAVE_FLASH].description;
if (desc && (typeof nav.mimeTypes !== "undefined" && nav.mimeTypes[FLASH_MIME_TYPE] && nav.mimeTypes[FLASH_MIME_TYPE].enabledPlugin)) {
hasFlash = true;
}
}
else if (typeof win.ActiveXObject !== "undefined") {
try {
var ax = new ActiveXObject(SHOCKWAVE_FLASH_AX);
if (ax) {
var ver = ax.GetVariable("$version");
if (ver) hasFlash = true;
}
}
catch (e) {;}
}
return hasFlash;
},
getSWFHTML: function() {
// Return HTML for embedding flash based webcam capture movie
var html = '',
swfURL = this.params.swfURL;
// make sure we aren't running locally (flash doesn't work)
if (location.protocol.match(/file/)) {
this.dispatch('error', new FlashError("Flash does not work from local disk. Please run from a web server."));
return '<h3 style="color:red">ERROR: the Webcam.js Flash fallback does not work from local disk. Please run it from a web server.</h3>';
}
// make sure we have flash
if (!this.detectFlash()) {
this.dispatch('error', new FlashError("Adobe Flash Player not found. Please install from get.adobe.com/flashplayer and try again."));
return '<h3 style="color:red">' + this.params.flashNotDetectedText + '</h3>';
}
// set default swfURL if not explicitly set
if (!swfURL) {
// find our script tag, and use that base URL
var base_url = '';
var scpts = document.getElementsByTagName('script');
for (var idx = 0, len = scpts.length; idx < len; idx++) {
var src = scpts[idx].getAttribute('src');
if (src && src.match(/\/webcam(\.min)?\.js/)) {
base_url = src.replace(/\/webcam(\.min)?\.js.*$/, '');
idx = len;
}
}
if (base_url) swfURL = base_url + '/webcam.swf';
else swfURL = 'webcam.swf';
}
// if this is the user's first visit, set flashvar so flash privacy settings panel is shown first
if (window.localStorage && !localStorage.getItem('visited')) {
this.params.new_user = 1;
localStorage.setItem('visited', 1);
}
// construct flashvars string
var flashvars = '';
for (var key in this.params) {
if (flashvars) flashvars += '&';
flashvars += key + '=' + escape(this.params[key]);
}
// construct object/embed tag
html += '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" type="application/x-shockwave-flash" codebase="'+this.protocol+'://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="'+this.params.width+'" height="'+this.params.height+'" id="webcam_movie_obj" align="middle"><param name="wmode" value="opaque" /><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="false" /><param name="movie" value="'+swfURL+'" /><param name="loop" value="false" /><param name="menu" value="false" /><param name="quality" value="best" /><param name="bgcolor" value="#ffffff" /><param name="flashvars" value="'+flashvars+'"/><embed id="webcam_movie_embed" src="'+swfURL+'" wmode="opaque" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="'+this.params.width+'" height="'+this.params.height+'" name="webcam_movie_embed" align="middle" allowScriptAccess="always" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="'+flashvars+'"></embed></object>';
return html;
},
getMovie: function() {
// get reference to movie object/embed in DOM
if (!this.loaded) return this.dispatch('error', new FlashError("Flash Movie is not loaded yet"));
var movie = document.getElementById('webcam_movie_obj');
if (!movie || !movie._snap) movie = document.getElementById('webcam_movie_embed');
if (!movie) this.dispatch('error', new FlashError("Cannot locate Flash movie in DOM"));
return movie;
},
freeze: function() {
// show preview, freeze camera
var self = this;
var params = this.params;
// kill preview if already active
if (this.preview_active) this.unfreeze();
// determine scale factor
var scaleX = this.params.width / this.params.dest_width;
var scaleY = this.params.height / this.params.dest_height;
// must unflip container as preview canvas will be pre-flipped
this.unflip();
// calc final size of image
var final_width = params.crop_width || params.dest_width;
var final_height = params.crop_height || params.dest_height;
// create canvas for holding preview
var preview_canvas = document.createElement('canvas');
preview_canvas.width = final_width;
preview_canvas.height = final_height;
var preview_context = preview_canvas.getContext('2d');
// save for later use
this.preview_canvas = preview_canvas;
this.preview_context = preview_context;
// scale for preview size
if ((scaleX != 1.0) || (scaleY != 1.0)) {
preview_canvas.style.webkitTransformOrigin = '0px 0px';
preview_canvas.style.mozTransformOrigin = '0px 0px';
preview_canvas.style.msTransformOrigin = '0px 0px';
preview_canvas.style.oTransformOrigin = '0px 0px';
preview_canvas.style.transformOrigin = '0px 0px';
preview_canvas.style.webkitTransform = 'scaleX('+scaleX+') scaleY('+scaleY+')';
preview_canvas.style.mozTransform = 'scaleX('+scaleX+') scaleY('+scaleY+')';
preview_canvas.style.msTransform = 'scaleX('+scaleX+') scaleY('+scaleY+')';
preview_canvas.style.oTransform = 'scaleX('+scaleX+') scaleY('+scaleY+')';
preview_canvas.style.transform = 'scaleX('+scaleX+') scaleY('+scaleY+')';
}
// take snapshot, but fire our own callback
this.snap( function() {
// add preview image to dom, adjust for crop
preview_canvas.style.position = 'relative';
preview_canvas.style.left = '' + self.container.scrollLeft + 'px';
preview_canvas.style.top = '' + self.container.scrollTop + 'px';
self.container.insertBefore( preview_canvas, self.peg );
self.container.style.overflow = 'hidden';
// set flag for user capture (use preview)
self.preview_active = true;
}, preview_canvas );
},
unfreeze: function() {
// cancel preview and resume live video feed
if (this.preview_active) {
// remove preview canvas
this.container.removeChild( this.preview_canvas );
delete this.preview_context;
delete this.preview_canvas;
// unflag
this.preview_active = false;
// re-flip if we unflipped before
this.flip();
}
},
flip: function() {
// flip container horiz (mirror mode) if desired
if (this.params.flip_horiz) {
var sty = this.container.style;
sty.webkitTransform = 'scaleX(-1)';
sty.mozTransform = 'scaleX(-1)';
sty.msTransform = 'scaleX(-1)';
sty.oTransform = 'scaleX(-1)';
sty.transform = 'scaleX(-1)';
sty.filter = 'FlipH';
sty.msFilter = 'FlipH';
}
},
unflip: function() {
// unflip container horiz (mirror mode) if desired
if (this.params.flip_horiz) {
var sty = this.container.style;
sty.webkitTransform = 'scaleX(1)';
sty.mozTransform = 'scaleX(1)';
sty.msTransform = 'scaleX(1)';
sty.oTransform = 'scaleX(1)';
sty.transform = 'scaleX(1)';
sty.filter = '';
sty.msFilter = '';
}
},
savePreview: function(user_callback, user_canvas) {
// save preview freeze and fire user callback
var params = this.params;
var canvas = this.preview_canvas;
var context = this.preview_context;
// render to user canvas if desired
if (user_canvas) {
var user_context = user_canvas.getContext('2d');
user_context.drawImage( canvas, 0, 0 );
}
// fire user callback if desired
user_callback(
user_canvas ? null : canvas.toDataURL('image/' + params.image_format, params.jpeg_quality / 100 ),
canvas,
context
);
// remove preview
if (this.params.unfreeze_snap) this.unfreeze();
},
snap: function(user_callback, user_canvas) {
// use global callback and canvas if not defined as parameter
if (!user_callback) user_callback = this.params.user_callback;
if (!user_canvas) user_canvas = this.params.user_canvas;
// take snapshot and return image data uri
var self = this;
var params = this.params;
if (!this.loaded) return this.dispatch('error', new WebcamError("Webcam is not loaded yet"));
// if (!this.live) return this.dispatch('error', new WebcamError("Webcam is not live yet"));
if (!user_callback) return this.dispatch('error', new WebcamError("Please provide a callback function or canvas to snap()"));
// if we have an active preview freeze, use that
if (this.preview_active) {
this.savePreview( user_callback, user_canvas );
return null;
}
// create offscreen canvas element to hold pixels
var canvas = document.createElement('canvas');
canvas.width = this.params.dest_width;
canvas.height = this.params.dest_height;
var context = canvas.getContext('2d');
// flip canvas horizontally if desired
if (this.params.flip_horiz) {
context.translate( params.dest_width, 0 );
context.scale( -1, 1 );
}
// create inline function, called after image load (flash) or immediately (native)
var func = function() {
// render image if needed (flash)
if (this.src && this.width && this.height) {
context.drawImage(this, 0, 0, params.dest_width, params.dest_height);
}
// crop if desired
if (params.crop_width && params.crop_height) {
var crop_canvas = document.createElement('canvas');
crop_canvas.width = params.crop_width;
crop_canvas.height = params.crop_height;
var crop_context = crop_canvas.getContext('2d');
crop_context.drawImage( canvas,
Math.floor( (params.dest_width / 2) - (params.crop_width / 2) ),
Math.floor( (params.dest_height / 2) - (params.crop_height / 2) ),
params.crop_width,
params.crop_height,
0,
0,
params.crop_width,
params.crop_height
);
// swap canvases
context = crop_context;
canvas = crop_canvas;
}
// render to user canvas if desired
if (user_canvas) {
var user_context = user_canvas.getContext('2d');
user_context.drawImage( canvas, 0, 0 );
}
// fire user callback if desired
user_callback(
user_canvas ? null : canvas.toDataURL('image/' + params.image_format, params.jpeg_quality / 100 ),
canvas,
context
);
};
// grab image frame from userMedia or flash movie
if (this.userMedia) {
// native implementation
context.drawImage(this.video, 0, 0, this.params.dest_width, this.params.dest_height);
// fire callback right away
func();
}
else if (this.iOS) {
var div = document.getElementById(this.container.id+'-ios_div');
var img = document.getElementById(this.container.id+'-ios_img');
var input = document.getElementById(this.container.id+'-ios_input');
// function for handle snapshot event (call user_callback and reset the interface)
iFunc = function(event) {
func.call(img);
img.removeEventListener('load', iFunc);
div.style.backgroundImage = 'none';
img.removeAttribute('src');
input.value = null;
};
if (!input.value) {
// No image selected yet, activate input field
img.addEventListener('load', iFunc);
input.style.display = 'block';
input.focus();
input.click();
input.style.display = 'none';
} else {
// Image already selected
iFunc(null);
}
}
else {
// flash fallback
var raw_data = this.getMovie()._snap();
// render to image, fire callback when complete
var img = new Image();
img.onload = func;
img.src = 'data:image/'+this.params.image_format+';base64,' + raw_data;
}
return null;
},
configure: function(panel) {
// open flash configuration panel -- specify tab name:
// "camera", "privacy", "default", "localStorage", "microphone", "settingsManager"
if (!panel) panel = "camera";
this.getMovie()._configure(panel);
},
flashNotify: function(type, msg) {
// receive notification from flash about event
switch (type) {
case 'flashLoadComplete':
// movie loaded successfully
this.loaded = true;
this.dispatch('load');
break;
case 'cameraLive':
// camera is live and ready to snap
this.live = true;
this.dispatch('live');
break;
case 'error':
// Flash error
this.dispatch('error', new FlashError(msg));
break;
default:
// catch-all event, just in case
// console.log("webcam flash_notify: " + type + ": " + msg);
break;
}
},
b64ToUint6: function(nChr) {
// convert base64 encoded character to 6-bit integer
// from: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Base64_encoding_and_decoding
return nChr > 64 && nChr < 91 ? nChr - 65
: nChr > 96 && nChr < 123 ? nChr - 71
: nChr > 47 && nChr < 58 ? nChr + 4
: nChr === 43 ? 62 : nChr === 47 ? 63 : 0;
},
base64DecToArr: function(sBase64, nBlocksSize) {
// convert base64 encoded string to Uintarray
// from: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Base64_encoding_and_decoding
var sB64Enc = sBase64.replace(/[^A-Za-z0-9\+\/]/g, ""), nInLen = sB64Enc.length,
nOutLen = nBlocksSize ? Math.ceil((nInLen * 3 + 1 >> 2) / nBlocksSize) * nBlocksSize : nInLen * 3 + 1 >> 2,
taBytes = new Uint8Array(nOutLen);
for (var nMod3, nMod4, nUint24 = 0, nOutIdx = 0, nInIdx = 0; nInIdx < nInLen; nInIdx++) {
nMod4 = nInIdx & 3;
nUint24 |= this.b64ToUint6(sB64Enc.charCodeAt(nInIdx)) << 18 - 6 * nMod4;
if (nMod4 === 3 || nInLen - nInIdx === 1) {
for (nMod3 = 0; nMod3 < 3 && nOutIdx < nOutLen; nMod3++, nOutIdx++) {
taBytes[nOutIdx] = nUint24 >>> (16 >>> nMod3 & 24) & 255;
}
nUint24 = 0;
}
}
return taBytes;
},
upload: function(image_data_uri, target_url, callback) {
// submit image data to server using binary AJAX
var form_elem_name = this.params.upload_name || 'webcam';
// detect image format from within image_data_uri
var image_fmt = '';
if (image_data_uri.match(/^data\:image\/(\w+)/))
image_fmt = RegExp.$1;
else
throw "Cannot locate image format in Data URI";
// extract raw base64 data from Data URI
var raw_image_data = image_data_uri.replace(/^data\:image\/\w+\;base64\,/, '');
// contruct use AJAX object
var http = new XMLHttpRequest();
http.open("POST", target_url, true);
// setup progress events
if (http.upload && http.upload.addEventListener) {
http.upload.addEventListener( 'progress', function(e) {
if (e.lengthComputable) {
var progress = e.loaded / e.total;
Webcam.dispatch('uploadProgress', progress, e);
}
}, false );
}
// completion handler
var self = this;
http.onload = function() {
if (callback) callback.apply( self, [http.status, http.responseText, http.statusText] );
Webcam.dispatch('uploadComplete', http.status, http.responseText, http.statusText);
};
// create a blob and decode our base64 to binary
var blob = new Blob( [ this.base64DecToArr(raw_image_data) ], {type: 'image/'+image_fmt} );
// stuff into a form, so servers can easily receive it as a standard file upload
var form = new FormData();
form.append( form_elem_name, blob, form_elem_name+"."+image_fmt.replace(/e/, '') );
// send data to server
http.send(form);
}
};
Webcam.init();
if (typeof define === 'function' && define.amd) {
define( function() { return Webcam; } );
}
else if (typeof module === 'object' && module.exports) {
module.exports = Webcam;
}
else {
window.Webcam = Webcam;
}
}(window));
| extend1994/cdnjs | ajax/libs/webcamjs/1.0.21/webcam.js | JavaScript | mit | 35,897 |
/**
* angular-route-segment v1.0.0
* https://github.com/artch/angular-route-segment
* @author Artem Chivchalov
* @license MIT License http://opensource.org/licenses/MIT
*/
'use strict';
(function(angular) {
angular.module( 'route-segment', [] ).provider( '$routeSegment',
['$routeProvider', function($routeProvider) {
var $routeSegmentProvider = this;
var options = $routeSegmentProvider.options = {
/**
* When true, it will resolve `templateUrl` automatically via $http service and put its
* contents into `template`.
* @type {boolean}
*/
autoLoadTemplates: false,
/**
* When true, all attempts to call `within` method on non-existing segments will throw an error (you would
* usually want this behavior in production). When false, it will transparently create new empty segment
* (can be useful in isolated tests).
* @type {boolean}
*/
strictMode: false
};
var segments = this.segments = {},
rootPointer = pointer(segments, null);
function camelCase(name) {
return name.replace(/([\:\-\_]+(.))/g, function(_, separator, letter, offset) {
return offset ? letter.toUpperCase() : letter;
});
}
function pointer(segment, parent) {
if(!segment)
throw new Error('Invalid pointer segment');
var lastAddedName;
return {
/**
* Adds new segment at current pointer level.
*
* @param string} name Name of a segment.
* @param {Object} params Segment's parameters hash. The following params are supported:
* - `template` provides HTML for the given segment view;
* - `templateUrl` is a template should be fetched from network via this URL;
* - `controller` is attached to the given segment view when compiled and linked,
* this can be any controller definition AngularJS supports;
* - `dependencies` is an array of route param names which are forcing the view
* to recreate when changed;
* - `watcher` is a $watch-function for recreating the view when its returning value
* is changed;
* - `resolve` is a hash of functions or injectable names which should be resolved
* prior to instantiating the template and the controller;
* - `untilResolved` is the alternate set of params (e.g. `template` and `controller`)
* which should be used before resolving is completed;
* - `resolveFailed` is the alternate set of params which should be used
* if resolving failed;
*
* @returns {Object} The same level pointer.
*/
segment: function(name, params) {
segment[camelCase(name)] = {params: params};
lastAddedName = name;
return this;
},
/**
* Traverses into an existing segment, so that subsequent `segment` calls
* will add new segments as its descendants.
*
* @param {string} childName An existing segment's name. If undefined, then the last added segment is selected.
* @returns {Object} The pointer to the child segment.
*/
within: function(childName) {
var child;
childName = childName || lastAddedName;
if(child = segment[camelCase(childName)]) {
if(child.children == undefined)
child.children = {};
}
else {
if(options.strictMode)
throw new Error('Cannot get into unknown `'+childName+'` segment');
else {
child = segment[camelCase(childName)] = {params: {}, children: {}};
}
}
return pointer(child.children, this);
},
/**
* Traverses up in the tree.
* @returns {Object} The pointer which are parent to the current one;
*/
up: function() {
return parent;
},
/**
* Traverses to the root. *
* @returns The root pointer.
*/
root: function() {
return rootPointer;
}
}
}
/**
* The shorthand for $routeProvider.when() method with specified route name.
* @param {string} route Route URL, e.g. '/foo/bar'
* @param {string} name Fully qualified route name, e.g. 'foo.bar'
*/
$routeSegmentProvider.when = function(route, name) {
$routeProvider.when(route, {segment: name});
return this;
};
// Extending the provider with the methods of rootPointer
// to start configuration.
angular.extend($routeSegmentProvider, rootPointer);
// the service factory
this.$get = ['$rootScope', '$q', '$http', '$templateCache', '$route', '$routeParams', '$injector',
function($rootScope, $q, $http, $templateCache, $route, $routeParams, $injector) {
var $routeSegment = {
/**
* Fully qualified name of current active route
* @type {string}
*/
name: '',
/**
* Array of segments splitted by each level separately. Each item contains the following properties:
* - `name` is the name of a segment;
* - `params` is the config params hash of a segment;
* - `locals` is a hash which contains resolve results if any;
* - `reload` is a function to reload a segment (restart resolving, reinstantiate a controller, etc)
*
* @type {Array.<Object>}
*/
chain: [],
/**
* Helper method for checking whether current route starts with the given string
* @param {string} val
* @returns {boolean}
*/
startsWith: function (val) {
var regexp = new RegExp('^'+val);
return regexp.test($routeSegment.name);
},
/**
* Helper method for checking whether current route contains the given string
* @param {string} val
* @returns {Boolean}
*/
contains: function (val) {
for(var i=0; i<this.chain.length; i++)
if(this.chain[i].name == val)
return true;
return false;
}
};
var lastParams = angular.copy($routeParams);
// When a route changes, all interested parties should be notified about new segment chain
$rootScope.$on('$routeChangeSuccess', function(event, args) {
var route = args.$route || args.$$route;
if(route && route.segment) {
var segmentName = route.segment;
var segmentNameChain = segmentName.split(".");
var updates = [];
for(var i=0; i < segmentNameChain.length; i++) {
var newSegment = getSegmentInChain( i, segmentNameChain );
if(!$routeSegment.chain[i] || $routeSegment.chain[i].name != newSegment.name ||
isDependenciesChanged(newSegment)) {
updates.push(updateSegment(i, newSegment));
}
}
$q.all(updates).then(function() {
$routeSegment.name = segmentName;
// Removing redundant segment in case if new segment chain is shorter than old one
if($routeSegment.chain.length > segmentNameChain.length) {
for(var i=segmentNameChain.length; i < $routeSegment.chain.length; i++)
updateSegment(i, null);
$routeSegment.chain.splice(-1, $routeSegment.chain.length - segmentNameChain.length);
}
});
lastParams = angular.copy($routeParams);
}
});
function isDependenciesChanged(segment) {
var result = false;
if(segment.params.dependencies)
angular.forEach(segment.params.dependencies, function(name) {
if(!angular.equals(lastParams[name], $routeParams[name]))
result = true;
});
return result;
}
function updateSegment(index, segment) {
if($routeSegment.chain[index] && $routeSegment.chain[index].clearWatcher) {
$routeSegment.chain[index].clearWatcher();
}
if(!segment) {
$rootScope.$broadcast( 'routeSegmentChange', { index: index, segment: null } );
return;
}
if(segment.params.untilResolved) {
return resolveAndBroadcast(index, segment.name, segment.params.untilResolved)
.then(function() {
resolveAndBroadcast(index, segment.name, segment.params);
})
}
else
return resolveAndBroadcast(index, segment.name, segment.params);
}
function resolveAndBroadcast(index, name, params) {
var locals = angular.extend({}, params.resolve);
angular.forEach(locals, function(value, key) {
locals[key] = angular.isString(value) ? $injector.get(value) : $injector.invoke(value);
});
if(params.template)
locals.$template = params.template;
if(options.autoLoadTemplates && params.templateUrl)
locals.$template =
$http.get(params.templateUrl, {cache: $templateCache})
.then(function(response) {
return response.data;
});
return $q.all(locals).then(
function(resolvedLocals) {
$routeSegment.chain[index] = {
name: name,
params: params,
locals: resolvedLocals,
reload: function() {
updateSegment(index, this);
}
};
if(params.watcher) {
var getWatcherValue = function() {
if(!angular.isFunction(params.watcher))
throw new Error('Watcher is not a function in segment `'+name+'`');
return $injector.invoke(
params.watcher,
{},
{segment: $routeSegment.chain[index]});
}
var lastWatcherValue = getWatcherValue();
$routeSegment.chain[index].clearWatcher = $rootScope.$watch(
getWatcherValue,
function(value) {
if(value == lastWatcherValue) // should not being run when $digest-ing at first time
return;
lastWatcherValue = value;
$routeSegment.chain[index].reload();
})
}
$rootScope.$broadcast( 'routeSegmentChange', {
index: index,
segment: $routeSegment.chain[index] } );
},
function(error) {
if(params.resolveFailed) {
var newResolve = {error: function() { return $q.when(error); }};
resolveAndBroadcast(index, name, angular.extend({resolve: newResolve}, params.resolveFailed));
}
else
throw new Error('Resolving failed with a reason `'+error+'`, but no `resolveFailed` ' +
'provided for segment `'+name+'`');
})
}
function getSegmentInChain(segmentIdx, segmentNameChain) {
if(!segmentNameChain)
return null;
if(segmentIdx >= segmentNameChain.length)
return null;
var curSegment = segments, nextName;
for(var i=0;i<=segmentIdx;i++) {
nextName = segmentNameChain[i];
if(curSegment[ camelCase(nextName) ] != undefined)
curSegment = curSegment[ camelCase(nextName) ];
if(i < segmentIdx)
curSegment = curSegment.children;
}
return {
name: nextName,
params: curSegment.params
};
}
return $routeSegment;
}];
}])
})(angular);;'use strict';
/**
* The directive app:view is more powerful replacement of built-in ng:view. It allows views to be nested, where each
* following view in the chain corresponds to the next route segment (see $routeSegment service).
*
* Sample:
* <div>
* <h4>Section</h4>
* <div app:view>Nothing selected</div>
* </div>
*
* Initial contents of an element with app:view will display if corresponding route segment doesn't exist.
*
* View resolving are depends on route segment params:
* - `template` define contents of the view
* - `controller` is attached to view contents when compiled and linked
*/
(function(angular) {
angular.module( 'view-segment', [ 'route-segment' ] ).directive( 'appViewSegment',
['$route', '$compile', '$controller', '$routeParams', '$routeSegment', '$q', '$injector',
function($route, $compile, $controller, $routeParams, $routeSegment, $q, $injector) {
return {
restrict : 'ECA',
compile : function(tElement) {
var oldContent = tElement.clone();
return function($scope, element, attrs) {
var lastScope, onloadExp = attrs.onload || '', animate,
viewSegmentIndex = parseInt(attrs.appViewSegment);
try {
// Trying to inject $animator which may be absent in 1.0.x branch
var $animator = $injector.get('$animator')
animate = $animator($scope, attrs);
}
catch(e) {
}
update($routeSegment.chain[viewSegmentIndex]);
// Watching for the specified route segment and updating contents
$scope.$on('routeSegmentChange', function(event, args) {
if(args.index == viewSegmentIndex)
update(args.segment);
});
function destroyLastScope() {
if (lastScope) {
lastScope.$destroy();
lastScope = null;
}
}
function clearContent() {
if(animate)
animate.leave(element.contents(), element);
else
element.html('');
destroyLastScope();
}
function update(segment) {
if(!segment) {
element.html(oldContent.html());
destroyLastScope();
$compile(element.contents())($scope);
return;
}
var locals = angular.extend({}, segment.locals),
template = locals && locals.$template;
if (template) {
clearContent();
if(animate)
animate.enter( angular.element('<div></div>').html(template).contents(), element );
else
element.html(template);
destroyLastScope();
var link = $compile(element.contents()), controller;
lastScope = $scope.$new();
if (segment.params.controller) {
locals.$scope = lastScope;
controller = $controller(segment.params.controller, locals);
element.children().data('$ngControllerController', controller);
}
link(lastScope);
lastScope.$emit('$viewContentLoaded');
lastScope.$eval(onloadExp);
} else {
clearContent();
}
}
}
}
}
}]);
})(angular); | bootcdn/cdnjs | ajax/libs/angular-route-segment/1.0.1/angular-route-segment.js | JavaScript | mit | 19,037 |
/* The MIT License */
.dropzone,
.dropzone *,
.dropzone-previews,
.dropzone-previews * {
box-sizing: border-box;
}
.dropzone {
position: relative;
border: 1px solid rgba(0,0,0,0.08);
background: rgba(0,0,0,0.02);
padding: 1em;
}
.dropzone.dz-clickable {
cursor: pointer;
}
.dropzone.dz-clickable .dz-message,
.dropzone.dz-clickable .dz-message span {
cursor: pointer;
}
.dropzone.dz-clickable * {
cursor: default;
}
.dropzone .dz-message {
opacity: 1;
}
.dropzone.dz-drag-hover {
border-color: rgba(0,0,0,0.15);
background: rgba(0,0,0,0.04);
}
.dropzone.dz-started .dz-message {
display: none;
}
.dropzone .dz-preview,
.dropzone-previews .dz-preview {
background: rgba(255,255,255,0.8);
position: relative;
display: inline-block;
margin: 17px;
vertical-align: top;
border: 1px solid #acacac;
padding: 6px 6px 6px 6px;
}
.dropzone .dz-preview.dz-file-preview [data-dz-thumbnail],
.dropzone-previews .dz-preview.dz-file-preview [data-dz-thumbnail] {
display: none;
}
.dropzone .dz-preview .dz-details,
.dropzone-previews .dz-preview .dz-details {
width: 100px;
height: 100px;
position: relative;
background: #ebebeb;
padding: 5px;
margin-bottom: 22px;
}
.dropzone .dz-preview .dz-details .dz-filename,
.dropzone-previews .dz-preview .dz-details .dz-filename {
overflow: hidden;
height: 100%;
}
.dropzone .dz-preview .dz-details img,
.dropzone-previews .dz-preview .dz-details img {
absolute: top left;
width: 100px;
height: 100px;
}
.dropzone .dz-preview .dz-details .dz-size,
.dropzone-previews .dz-preview .dz-details .dz-size {
absolute: bottom -28px left 3px;
height: 28px;
line-height: 28px;
}
.dropzone .dz-preview.dz-error .dz-error-mark,
.dropzone-previews .dz-preview.dz-error .dz-error-mark {
display: block;
}
.dropzone .dz-preview.dz-success .dz-success-mark,
.dropzone-previews .dz-preview.dz-success .dz-success-mark {
display: block;
}
.dropzone .dz-preview:hover .dz-details img,
.dropzone-previews .dz-preview:hover .dz-details img {
display: none;
}
.dropzone .dz-preview .dz-success-mark,
.dropzone-previews .dz-preview .dz-success-mark,
.dropzone .dz-preview .dz-error-mark,
.dropzone-previews .dz-preview .dz-error-mark {
display: none;
position: absolute;
width: 40px;
height: 40px;
font-size: 30px;
text-align: center;
right: -10px;
top: -10px;
}
.dropzone .dz-preview .dz-success-mark,
.dropzone-previews .dz-preview .dz-success-mark {
color: #8cc657;
}
.dropzone .dz-preview .dz-error-mark,
.dropzone-previews .dz-preview .dz-error-mark {
color: #ee162d;
}
.dropzone .dz-preview .dz-progress,
.dropzone-previews .dz-preview .dz-progress {
position: absolute;
top: 100px;
left: 6px;
right: 6px;
height: 6px;
background: #d7d7d7;
display: none;
}
.dropzone .dz-preview .dz-progress .dz-upload,
.dropzone-previews .dz-preview .dz-progress .dz-upload {
display: block;
position: absolute;
top: 0;
bottom: 0;
left: 0;
width: 0%;
background-color: #8cc657;
}
.dropzone .dz-preview.dz-processing .dz-progress,
.dropzone-previews .dz-preview.dz-processing .dz-progress {
display: block;
}
.dropzone .dz-preview .dz-error-message,
.dropzone-previews .dz-preview .dz-error-message {
display: none;
absolute: top -5px left -20px;
background: rgba(245,245,245,0.8);
padding: 8px 10px;
color: #800;
min-width: 140px;
max-width: 500px;
z-index: 500;
}
.dropzone .dz-preview:hover.dz-error .dz-error-message,
.dropzone-previews .dz-preview:hover.dz-error .dz-error-message {
display: block;
}
.dropzone {
border: 1px solid rgba(0,0,0,0.03);
min-height: 360px;
-webkit-border-radius: 3px;
border-radius: 3px;
background: rgba(0,0,0,0.03);
padding: 23px;
}
.dropzone .dz-default.dz-message {
opacity: 1;
-ms-filter: none;
filter: none;
-webkit-transition: opacity 0.3s ease-in-out;
-moz-transition: opacity 0.3s ease-in-out;
-o-transition: opacity 0.3s ease-in-out;
-ms-transition: opacity 0.3s ease-in-out;
transition: opacity 0.3s ease-in-out;
background-image: url("../images/spritemap.png");
background-repeat: no-repeat;
background-position: 0 0;
position: absolute;
width: 428px;
height: 123px;
margin-left: -214px;
margin-top: -61.5px;
top: 50%;
left: 50%;
}
@media all and (-webkit-min-device-pixel-ratio:1.5),(min--moz-device-pixel-ratio:1.5),(-o-min-device-pixel-ratio:1.5/1),(min-device-pixel-ratio:1.5),(min-resolution:138dpi),(min-resolution:1.5dppx) {
.dropzone .dz-default.dz-message {
background-image: url("../images/spritemap@2x.png");
-webkit-background-size: 428px 406px;
-moz-background-size: 428px 406px;
background-size: 428px 406px;
}
}
.dropzone .dz-default.dz-message span {
display: none;
}
.dropzone.dz-square .dz-default.dz-message {
background-position: 0 -123px;
width: 268px;
margin-left: -134px;
height: 174px;
margin-top: -87px;
}
.dropzone.dz-drag-hover .dz-message {
opacity: 0.15;
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=15)";
filter: alpha(opacity=15);
}
.dropzone.dz-started .dz-message {
display: block;
opacity: 0;
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
filter: alpha(opacity=0);
}
.dropzone .dz-preview,
.dropzone-previews .dz-preview {
-webkit-box-shadow: 1px 1px 4px rgba(0,0,0,0.16);
box-shadow: 1px 1px 4px rgba(0,0,0,0.16);
font-size: 14px;
}
.dropzone .dz-preview.dz-image-preview:hover .dz-details img,
.dropzone-previews .dz-preview.dz-image-preview:hover .dz-details img {
display: block;
opacity: 0.1;
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=10)";
filter: alpha(opacity=10);
}
.dropzone .dz-preview.dz-success .dz-success-mark,
.dropzone-previews .dz-preview.dz-success .dz-success-mark {
opacity: 1;
-ms-filter: none;
filter: none;
}
.dropzone .dz-preview.dz-error .dz-error-mark,
.dropzone-previews .dz-preview.dz-error .dz-error-mark {
opacity: 1;
-ms-filter: none;
filter: none;
}
.dropzone .dz-preview.dz-error .dz-progress .dz-upload,
.dropzone-previews .dz-preview.dz-error .dz-progress .dz-upload {
background: #ee1e2d;
}
.dropzone .dz-preview .dz-error-mark,
.dropzone-previews .dz-preview .dz-error-mark,
.dropzone .dz-preview .dz-success-mark,
.dropzone-previews .dz-preview .dz-success-mark {
display: block;
opacity: 0;
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
filter: alpha(opacity=0);
-webkit-transition: opacity 0.4s ease-in-out;
-moz-transition: opacity 0.4s ease-in-out;
-o-transition: opacity 0.4s ease-in-out;
-ms-transition: opacity 0.4s ease-in-out;
transition: opacity 0.4s ease-in-out;
background-image: url("../images/spritemap.png");
background-repeat: no-repeat;
}
@media all and (-webkit-min-device-pixel-ratio:1.5),(min--moz-device-pixel-ratio:1.5),(-o-min-device-pixel-ratio:1.5/1),(min-device-pixel-ratio:1.5),(min-resolution:138dpi),(min-resolution:1.5dppx) {
.dropzone .dz-preview .dz-error-mark,
.dropzone-previews .dz-preview .dz-error-mark,
.dropzone .dz-preview .dz-success-mark,
.dropzone-previews .dz-preview .dz-success-mark {
background-image: url("../images/spritemap@2x.png");
-webkit-background-size: 428px 406px;
-moz-background-size: 428px 406px;
background-size: 428px 406px;
}
}
.dropzone .dz-preview .dz-error-mark span,
.dropzone-previews .dz-preview .dz-error-mark span,
.dropzone .dz-preview .dz-success-mark span,
.dropzone-previews .dz-preview .dz-success-mark span {
display: none;
}
.dropzone .dz-preview .dz-error-mark,
.dropzone-previews .dz-preview .dz-error-mark {
background-position: -268px -123px;
}
.dropzone .dz-preview .dz-success-mark,
.dropzone-previews .dz-preview .dz-success-mark {
background-position: -268px -163px;
}
.dropzone .dz-preview .dz-progress .dz-upload,
.dropzone-previews .dz-preview .dz-progress .dz-upload {
-webkit-animation: loading 0.4s linear infinite;
-moz-animation: loading 0.4s linear infinite;
-o-animation: loading 0.4s linear infinite;
-ms-animation: loading 0.4s linear infinite;
animation: loading 0.4s linear infinite;
-webkit-transition: width 0.3s ease-in-out;
-moz-transition: width 0.3s ease-in-out;
-o-transition: width 0.3s ease-in-out;
-ms-transition: width 0.3s ease-in-out;
transition: width 0.3s ease-in-out;
-webkit-border-radius: 2px;
border-radius: 2px;
position: absolute;
top: 0;
left: 0;
width: 0%;
height: 100%;
background-image: url("../images/spritemap.png");
background-repeat: repeat-x;
background-position: 0px -400px;
}
@media all and (-webkit-min-device-pixel-ratio:1.5),(min--moz-device-pixel-ratio:1.5),(-o-min-device-pixel-ratio:1.5/1),(min-device-pixel-ratio:1.5),(min-resolution:138dpi),(min-resolution:1.5dppx) {
.dropzone .dz-preview .dz-progress .dz-upload,
.dropzone-previews .dz-preview .dz-progress .dz-upload {
background-image: url("../images/spritemap@2x.png");
-webkit-background-size: 428px 406px;
-moz-background-size: 428px 406px;
background-size: 428px 406px;
}
}
.dropzone .dz-preview.dz-success .dz-progress,
.dropzone-previews .dz-preview.dz-success .dz-progress {
display: block;
opacity: 0;
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
filter: alpha(opacity=0);
-webkit-transition: opacity 0.4s ease-in-out;
-moz-transition: opacity 0.4s ease-in-out;
-o-transition: opacity 0.4s ease-in-out;
-ms-transition: opacity 0.4s ease-in-out;
transition: opacity 0.4s ease-in-out;
}
.dropzone .dz-preview .dz-error-message,
.dropzone-previews .dz-preview .dz-error-message {
display: block;
opacity: 0;
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
filter: alpha(opacity=0);
-webkit-transition: opacity 0.3s ease-in-out;
-moz-transition: opacity 0.3s ease-in-out;
-o-transition: opacity 0.3s ease-in-out;
-ms-transition: opacity 0.3s ease-in-out;
transition: opacity 0.3s ease-in-out;
}
.dropzone .dz-preview:hover.dz-error .dz-error-message,
.dropzone-previews .dz-preview:hover.dz-error .dz-error-message {
opacity: 1;
-ms-filter: none;
filter: none;
}
.dropzone a.dz-remove,
.dropzone-previews a.dz-remove {
background-image: -webkit-linear-gradient(top, #fafafa, #eee);
background-image: -moz-linear-gradient(top, #fafafa, #eee);
background-image: -o-linear-gradient(top, #fafafa, #eee);
background-image: -ms-linear-gradient(top, #fafafa, #eee);
background-image: linear-gradient(to bottom, #fafafa, #eee);
-webkit-border-radius: 2px;
border-radius: 2px;
border: 1px solid #eee;
text-decoration: none;
display: block;
padding: 4px 5px;
text-align: center;
color: #aaa;
margin-top: 26px;
}
.dropzone a.dz-remove:hover,
.dropzone-previews a.dz-remove:hover {
color: #666;
}
@-moz-keyframes loading {
from {
background-position: 0 -400px;
}
to {
background-position: -7px -400px;
}
}
@-webkit-keyframes loading {
from {
background-position: 0 -400px;
}
to {
background-position: -7px -400px;
}
}
@-o-keyframes loading {
from {
background-position: 0 -400px;
}
to {
background-position: -7px -400px;
}
}
@keyframes loading {
from {
background-position: 0 -400px;
}
to {
background-position: -7px -400px;
}
}
| anilanar/jsdelivr | files/dropzone/3.12.0/css/dropzone.css | CSS | mit | 11,258 |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function() {
var mode = CodeMirror.getMode({indentUnit: 2}, "css");
function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }
// Error, because "foobarhello" is neither a known type or property, but
// property was expected (after "and"), and it should be in parenthese.
MT("atMediaUnknownType",
"[def @media] [attribute screen] [keyword and] [error foobarhello] { }");
// Soft error, because "foobarhello" is not a known property or type.
MT("atMediaUnknownProperty",
"[def @media] [attribute screen] [keyword and] ([error foobarhello]) { }");
// Make sure nesting works with media queries
MT("atMediaMaxWidthNested",
"[def @media] [attribute screen] [keyword and] ([property max-width]: [number 25px]) { [tag foo] { } }");
MT("tagSelector",
"[tag foo] { }");
MT("classSelector",
"[qualifier .foo-bar_hello] { }");
MT("idSelector",
"[builtin #foo] { [error #foo] }");
MT("tagSelectorUnclosed",
"[tag foo] { [property margin]: [number 0] } [tag bar] { }");
MT("tagStringNoQuotes",
"[tag foo] { [property font-family]: [variable hello] [variable world]; }");
MT("tagStringDouble",
"[tag foo] { [property font-family]: [string \"hello world\"]; }");
MT("tagStringSingle",
"[tag foo] { [property font-family]: [string 'hello world']; }");
MT("tagColorKeyword",
"[tag foo] {",
" [property color]: [keyword black];",
" [property color]: [keyword navy];",
" [property color]: [keyword yellow];",
"}");
MT("tagColorHex3",
"[tag foo] { [property background]: [atom #fff]; }");
MT("tagColorHex6",
"[tag foo] { [property background]: [atom #ffffff]; }");
MT("tagColorHex4",
"[tag foo] { [property background]: [atom&error #ffff]; }");
MT("tagColorHexInvalid",
"[tag foo] { [property background]: [atom&error #ffg]; }");
MT("tagNegativeNumber",
"[tag foo] { [property margin]: [number -5px]; }");
MT("tagPositiveNumber",
"[tag foo] { [property padding]: [number 5px]; }");
MT("tagVendor",
"[tag foo] { [meta -foo-][property box-sizing]: [meta -foo-][atom border-box]; }");
MT("tagBogusProperty",
"[tag foo] { [property&error barhelloworld]: [number 0]; }");
MT("tagTwoProperties",
"[tag foo] { [property margin]: [number 0]; [property padding]: [number 0]; }");
MT("tagTwoPropertiesURL",
"[tag foo] { [property background]: [atom url]([string //example.com/foo.png]); [property padding]: [number 0]; }");
MT("commentSGML",
"[comment <!--comment-->]");
MT("commentSGML2",
"[comment <!--comment]",
"[comment -->] [tag div] {}");
MT("indent_tagSelector",
"[tag strong], [tag em] {",
" [property background]: [atom rgba](",
" [number 255], [number 255], [number 0], [number .2]",
" );",
"}");
MT("indent_atMedia",
"[def @media] {",
" [tag foo] {",
" [property color]:",
" [keyword yellow];",
" }",
"}");
MT("indent_comma",
"[tag foo] {",
" [property font-family]: [variable verdana],",
" [atom sans-serif];",
"}");
MT("indent_parentheses",
"[tag foo]:[variable-3 before] {",
" [property background]: [atom url](",
"[string blahblah]",
"[string etc]",
"[string ]) [keyword !important];",
"}");
MT("font_face",
"[def @font-face] {",
" [property font-family]: [string 'myfont'];",
" [error nonsense]: [string 'abc'];",
" [property src]: [atom url]([string http://blah]),",
" [atom url]([string http://foo]);",
"}");
MT("empty_url",
"[def @import] [tag url]() [tag screen];");
MT("parens",
"[qualifier .foo] {",
" [property background-image]: [variable fade]([atom #000], [number 20%]);",
" [property border-image]: [variable linear-gradient](",
" [atom to] [atom bottom],",
" [variable fade]([atom #000], [number 20%]) [number 0%],",
" [variable fade]([atom #000], [number 20%]) [number 100%]",
" );",
"}");
})();
| vuthea/CoffeeShopPro | application/views/admin-kh4it/assets/codemirror/mode/css/test.js | JavaScript | mit | 4,227 |
<?php
namespace Stripe;
/**
* Class EphemeralKey
*
* @property string $id
* @property string $object
* @property int $created
* @property int $expires
* @property bool $livemode
* @property string $secret
* @property array $associated_objects
*
* @package Stripe
*/
class EphemeralKey extends ApiResource
{
/**
* This is a special case because the ephemeral key endpoint has an
* underscore in it. The parent `className` function strips underscores.
*
* @return string The name of the class.
*/
public static function className()
{
return 'ephemeral_key';
}
/**
* @param array|null $params
* @param array|string|null $opts
*
* @return EphemeralKey The created key.
*/
public static function create($params = null, $opts = null)
{
if (!$opts['stripe_version']) {
throw new \InvalidArgumentException('stripe_version must be specified to create an ephemeral key');
}
return self::_create($params, $opts);
}
/**
* @param array|null $params
* @param array|string|null $opts
*
* @return EphemeralKey The deleted key.
*/
public function delete($params = null, $opts = null)
{
return $this->_delete($params, $opts);
}
}
| talent-webmobiledeveloper/codeigniter3_twiliosms | application/libraries/stripe/lib/EphemeralKey.php | PHP | mit | 1,306 |
class BlogSweeper < ActionController::Caching::Sweeper
observe Blog, User, Article, Page, Comment, Trackback, Note, Tag
def pending_sweeps
@pending_sweeps ||= Set.new
end
def run_pending_page_sweeps
pending_sweeps.each do |each|
self.send(each)
end
end
def after_comments_create
expire_for(controller.send(:instance_variable_get, :@comment))
end
alias_method :after_comments_update, :after_comments_create
alias_method :after_articles_comment, :after_comments_create
def after_comments_destroy
expire_for(controller.send(:instance_variable_get, :@comment), true)
end
alias_method :after_articles_nuke_comment, :after_comments_destroy
def after_articles_trackback
expire_for(controller.send(:instance_variable_get, :@trackback))
end
def after_articles_nuke_trackback
expire_for(controller.send(:instance_variable_get, :@trackback), true)
end
def after_save(record)
expire_for(record) unless (record.is_a?(Article) and record.state == :draft)
end
def after_destroy(record)
expire_for(record, true)
end
# TODO: Simplify this. Almost every sweep amounts to a sweep_all.
def expire_for(record, destroying = false)
case record
when Page
pending_sweeps << :sweep_pages
when Content
if record.invalidates_cache?(destroying)
pending_sweeps << :sweep_articles << :sweep_pages
end
when Tag
pending_sweeps << :sweep_articles << :sweep_pages
when Blog, User, Comment, Trackback
pending_sweeps << :sweep_all << :sweep_theme
end
unless controller
run_pending_page_sweeps
end
end
def sweep_all
PageCache.sweep_all
end
def sweep_theme
PageCache.sweep_theme_cache
end
def sweep_articles
PageCache.sweep_all
end
def sweep_pages
PageCache.zap_pages(%w{pages}) unless Blog.default.nil?
end
def logger
@logger ||= ::Rails.logger || Logger.new(STDERR)
end
private
def callback(timing)
super
if timing == :after
run_pending_page_sweeps
end
end
end
| babaa/foodblog | app/models/blog_sweeper.rb | Ruby | mit | 2,069 |
/* This module allows to load external modules on the fly as plugins. */
var PluginsModule = {
settings_panel: [ {name:"plugins", title:"Plugins", icon:null } ],
loaded_plugins: [],
init: function()
{
},
onShowSettingsPanel: function(name,widgets)
{
if(name != "plugins") return;
widgets.addList("Installed", this.loaded_plugins, { height: 400 } );
widgets.addStringButton("Plugin URL","js/modules/", { callback_button: function(value) {
trace("Loading: " + value);
PluginsModule.loadPlugin(value);
}});
},
loadPlugin: function(url, on_complete )
{
var last_plugin = null;
if(LiteGUI.modules.length)
last_plugin = LiteGUI.modules[ LiteGUI.modules.length - 1];
$.getScript(url, function(){
trace("Running...");
inner();
}).fail( function(response) {
if(response.status == 200)
{
try
{
eval(response.responseText);
inner();
}
catch (err)
{
trace("Error parsing code");
LiteGUI.alert("Problem, plugin has errors. Check log for more info.");
trace(err);
}
}
else if(response.status == 404)
{
trace("Error loading plugin");
LiteGUI.alert("Problem, plugin not found.");
}
else
{
trace("Error loading plugin");
LiteGUI.alert("Problem, plugin cannot be loaded. [Error: " + response.status + "]");
}
if(on_complete) on_complete(false);
});
function inner()
{
var loaded_plugin = LiteGUI.modules[ LiteGUI.modules.length - 1];
if(loaded_plugin != last_plugin)
{
PluginsModule.loaded_plugins.push( { name: loaded_plugin.name || url , url: url });
trace("Plugin loaded OK");
AppSettings.updateDialogContent();
AppSettings.changeSection("plugins");
if(on_complete) on_complete(true);
}
else
{
trace("Error loading plugin");
LiteGUI.alert("Plugin File loaded but it doesnt looks like a plugin");
if(on_complete) on_complete(false);
}
}
},
}
LiteGUI.registerModule( PluginsModule ); | zerin108/webglstudio.js | editor/js/modules/plugins.js | JavaScript | mit | 2,056 |
/**
* jqPlot
* Pure JavaScript plotting plugin using jQuery
*
* Version: 1.0.2
* Revision: 1108
*
* Copyright (c) 2009-2011 Chris Leonello
* jqPlot is currently available for use in all personal or commercial projects
* under both the MIT (http://www.opensource.org/licenses/mit-license.php) and GPL
* version 2.0 (http://www.gnu.org/licenses/gpl-2.0.html) licenses. This means that you can
* choose the license that best suits your project and use it accordingly.
*
* Although not required, the author would appreciate an email letting him
* know of any substantial use of jqPlot. You can reach the author at:
* chris at jqplot dot com or see http://www.jqplot.com/info.php .
*
* If you are feeling kind and generous, consider supporting the project by
* making a donation at: http://www.jqplot.com/donate.php .
*
* sprintf functions contained in jqplot.sprintf.js by Ash Searle:
*
* version 2007.04.27
* author Ash Searle
* http://hexmen.com/blog/2007/03/printf-sprintf/
* http://hexmen.com/js/sprintf.js
* The author (Ash Searle) has placed this code in the public domain:
* "This code is unrestricted: you are free to use it however you like."
*
*/
(function($) {
// Need to ensure pyramid axis and grid renderers are loaded.
// You should load these with script tags in the html head, that is more efficient
// as the browser will cache the request.
// Note, have to block with synchronous request in order to execute bar renderer code.
if ($.jqplot.PyramidAxisRenderer === undefined) {
$.ajax({
url: $.jqplot.pluginLocation + 'jqplot.pyramidAxisRenderer.js',
dataType: "script",
async: false
});
}
if ($.jqplot.PyramidGridRenderer === undefined) {
$.ajax({
url: $.jqplot.pluginLocation + 'jqplot.pyramidGridRenderer.js',
dataType: "script",
async: false
});
}
$.jqplot.PyramidRenderer = function(){
$.jqplot.LineRenderer.call(this);
};
$.jqplot.PyramidRenderer.prototype = new $.jqplot.LineRenderer();
$.jqplot.PyramidRenderer.prototype.constructor = $.jqplot.PyramidRenderer;
// called with scope of a series
$.jqplot.PyramidRenderer.prototype.init = function(options, plot) {
options = options || {};
this._type = 'pyramid';
// Group: Properties
//
// prop: barPadding
this.barPadding = 10;
this.barWidth = null;
// prop: fill
// True to fill the bars.
this.fill = true;
// prop: highlightMouseOver
// True to highlight slice when moused over.
// This must be false to enable highlightMouseDown to highlight when clicking on a slice.
this.highlightMouseOver = true;
// prop: highlightMouseDown
// True to highlight when a mouse button is pressed over a slice.
// This will be disabled if highlightMouseOver is true.
this.highlightMouseDown = false;
// prop: highlightColors
// an array of colors to use when highlighting a slice.
this.highlightColors = [];
// prop highlightThreshold
// Expand the highlightable region in the x direction.
// E.g. a value of 3 will highlight a bar when the mouse is
// within 3 pixels of the bar in the x direction.
this.highlightThreshold = 2;
// prop: synchronizeHighlight
// Index of another series to highlight when this series is highlighted.
// null or false to not synchronize.
this.synchronizeHighlight = false;
// prop: offsetBars
// False will center bars on their y value.
// True will push bars up by 1/2 bar width to fill between their y values.
// If true, there needs to be 1 more tick than there are bars.
this.offsetBars = false;
// if user has passed in highlightMouseDown option and not set highlightMouseOver, disable highlightMouseOver
if (options.highlightMouseDown && options.highlightMouseOver == null) {
options.highlightMouseOver = false;
}
this.side = 'right';
$.extend(true, this, options);
// if (this.fill === false) {
// this.shadow = false;
// }
if (this.side === 'left') {
this._highlightThreshold = [[-this.highlightThreshold, 0], [-this.highlightThreshold, 0], [0,0], [0,0]];
}
else {
this._highlightThreshold = [[0,0], [0,0], [this.highlightThreshold, 0], [this.highlightThreshold, 0]];
}
this.renderer.options = options;
// index of the currenty highlighted point, if any
this._highlightedPoint = null;
// Array of actual data colors used for each data point.
this._dataColors = [];
this._barPoints = [];
this.fillAxis = 'y';
this._primaryAxis = '_yaxis';
this._xnudge = 0;
// set the shape renderer options
var opts = {lineJoin:'miter', lineCap:'butt', fill:this.fill, fillRect:this.fill, isarc:false, strokeStyle:this.color, fillStyle:this.color, closePath:this.fill, lineWidth: this.lineWidth};
this.renderer.shapeRenderer.init(opts);
// set the shadow renderer options
var shadow_offset = options.shadowOffset;
// set the shadow renderer options
if (shadow_offset == null) {
// scale the shadowOffset to the width of the line.
if (this.lineWidth > 2.5) {
shadow_offset = 1.25 * (1 + (Math.atan((this.lineWidth/2.5))/0.785398163 - 1)*0.6);
// var shadow_offset = this.shadowOffset;
}
// for skinny lines, don't make such a big shadow.
else {
shadow_offset = 1.25 * Math.atan((this.lineWidth/2.5))/0.785398163;
}
}
var sopts = {lineJoin:'miter', lineCap:'butt', fill:this.fill, fillRect:this.fill, isarc:false, angle:this.shadowAngle, offset:shadow_offset, alpha:this.shadowAlpha, depth:this.shadowDepth, closePath:this.fill, lineWidth: this.lineWidth};
this.renderer.shadowRenderer.init(sopts);
plot.postDrawHooks.addOnce(postPlotDraw);
plot.eventListenerHooks.addOnce('jqplotMouseMove', handleMove);
// if this is the left side of pyramid, set y values to negative.
if (this.side === 'left') {
for (var i=0, l=this.data.length; i<l; i++) {
this.data[i][1] = -Math.abs(this.data[i][1]);
}
}
};
// setGridData
// converts the user data values to grid coordinates and stores them
// in the gridData array.
// Called with scope of a series.
$.jqplot.PyramidRenderer.prototype.setGridData = function(plot) {
// recalculate the grid data
var xp = this._xaxis.series_u2p;
var yp = this._yaxis.series_u2p;
var data = this._plotData;
var pdata = this._prevPlotData;
this.gridData = [];
this._prevGridData = [];
var l = data.length;
var adjust = false;
var i;
// if any data values are < 0, consider this a negative series
for (i = 0; i < l; i++) {
if (data[i][1] < 0) {
this.side = 'left';
}
}
if (this._yaxis.name === 'yMidAxis' && this.side === 'right') {
this._xnudge = this._xaxis.max/2000.0;
adjust = true;
}
for (i = 0; i < l; i++) {
// if not a line series or if no nulls in data, push the converted point onto the array.
if (data[i][0] != null && data[i][1] != null) {
this.gridData.push([xp(data[i][1]), yp(data[i][0])]);
}
// else if there is a null, preserve it.
else if (data[i][0] == null) {
this.gridData.push([xp(data[i][1]), null]);
}
else if (data[i][1] == null) {
this.gridData.push(null, [yp(data[i][0])]);
}
// finally, adjust x grid data if have to
if (data[i][1] === 0 && adjust) {
this.gridData[i][0] = xp(this._xnudge);
}
}
};
// makeGridData
// converts any arbitrary data values to grid coordinates and
// returns them. This method exists so that plugins can use a series'
// linerenderer to generate grid data points without overwriting the
// grid data associated with that series.
// Called with scope of a series.
$.jqplot.PyramidRenderer.prototype.makeGridData = function(data, plot) {
// recalculate the grid data
var xp = this._xaxis.series_u2p;
var yp = this._yaxis.series_u2p;
var gd = [];
var l = data.length;
var adjust = false;
var i;
// if any data values are < 0, consider this a negative series
for (i = 0; i < l; i++) {
if (data[i][1] < 0) {
this.side = 'left';
}
}
if (this._yaxis.name === 'yMidAxis' && this.side === 'right') {
this._xnudge = this._xaxis.max/2000.0;
adjust = true;
}
for (i = 0; i < l; i++) {
// if not a line series or if no nulls in data, push the converted point onto the array.
if (data[i][0] != null && data[i][1] != null) {
gd.push([xp(data[i][1]), yp(data[i][0])]);
}
// else if there is a null, preserve it.
else if (data[i][0] == null) {
gd.push([xp(data[i][1]), null]);
}
else if (data[i][1] == null) {
gd.push([null, yp(data[i][0])]);
}
// finally, adjust x grid data if have to
if (data[i][1] === 0 && adjust) {
gd[i][0] = xp(this._xnudge);
}
}
return gd;
};
$.jqplot.PyramidRenderer.prototype.setBarWidth = function() {
// need to know how many data values we have on the approprate axis and figure it out.
var i;
var nvals = 0;
var nseries = 0;
var paxis = this[this._primaryAxis];
var s, series, pos;
nvals = paxis.max - paxis.min;
var nticks = paxis.numberTicks;
var nbins = (nticks-1)/2;
// so, now we have total number of axis values.
var temp = (this.barPadding === 0) ? 1.0 : 0;
if (paxis.name == 'xaxis' || paxis.name == 'x2axis') {
this.barWidth = (paxis._offsets.max - paxis._offsets.min) / nvals - this.barPadding + temp;
}
else {
if (this.fill) {
this.barWidth = (paxis._offsets.min - paxis._offsets.max) / nvals - this.barPadding + temp;
}
else {
this.barWidth = (paxis._offsets.min - paxis._offsets.max) / nvals;
}
}
};
$.jqplot.PyramidRenderer.prototype.draw = function(ctx, gridData, options) {
var i;
// Ughhh, have to make a copy of options b/c it may be modified later.
var opts = $.extend({}, options);
var shadow = (opts.shadow != undefined) ? opts.shadow : this.shadow;
var showLine = (opts.showLine != undefined) ? opts.showLine : this.showLine;
var fill = (opts.fill != undefined) ? opts.fill : this.fill;
var xp = this._xaxis.series_u2p;
var yp = this._yaxis.series_u2p;
var pointx, pointy;
// clear out data colors.
this._dataColors = [];
this._barPoints = [];
if (this.renderer.options.barWidth == null) {
this.renderer.setBarWidth.call(this);
}
// var temp = this._plotSeriesInfo = this.renderer.calcSeriesNumbers.call(this);
// var nvals = temp[0];
// var nseries = temp[1];
// var pos = temp[2];
var points = [],
w,
h;
// this._barNudge = 0;
if (showLine) {
var negativeColors = new $.jqplot.ColorGenerator(this.negativeSeriesColors);
var positiveColors = new $.jqplot.ColorGenerator(this.seriesColors);
var negativeColor = negativeColors.get(this.index);
if (! this.useNegativeColors) {
negativeColor = opts.fillStyle;
}
var positiveColor = opts.fillStyle;
var base;
var xstart = this._xaxis.series_u2p(this._xnudge);
var ystart = this._yaxis.series_u2p(this._yaxis.min);
var yend = this._yaxis.series_u2p(this._yaxis.max);
var bw = this.barWidth;
var bw2 = bw/2.0;
var points = [];
var yadj = this.offsetBars ? bw2 : 0;
for (var i=0, l=gridData.length; i<l; i++) {
if (this.data[i][0] == null) {
continue;
}
base = gridData[i][1];
// not stacked and first series in stack
if (this._plotData[i][1] < 0) {
if (this.varyBarColor && !this._stack) {
if (this.useNegativeColors) {
opts.fillStyle = negativeColors.next();
}
else {
opts.fillStyle = positiveColors.next();
}
}
}
else {
if (this.varyBarColor && !this._stack) {
opts.fillStyle = positiveColors.next();
}
else {
opts.fillStyle = positiveColor;
}
}
if (this.fill) {
if (this._plotData[i][1] >= 0) {
// xstart = this._xaxis.series_u2p(this._xnudge);
w = gridData[i][0] - xstart;
h = this.barWidth;
points = [xstart, base - bw2 - yadj, w, h];
}
else {
// xstart = this._xaxis.series_u2p(0);
w = xstart - gridData[i][0];
h = this.barWidth;
points = [gridData[i][0], base - bw2 - yadj, w, h];
}
this._barPoints.push([[points[0], points[1] + h], [points[0], points[1]], [points[0] + w, points[1]], [points[0] + w, points[1] + h]]);
if (shadow) {
this.renderer.shadowRenderer.draw(ctx, points);
}
var clr = opts.fillStyle || this.color;
this._dataColors.push(clr);
this.renderer.shapeRenderer.draw(ctx, points, opts);
}
else {
if (i === 0) {
points =[[xstart, ystart], [gridData[i][0], ystart], [gridData[i][0], gridData[i][1] - bw2 - yadj]];
}
else if (i < l-1) {
points = points.concat([[gridData[i-1][0], gridData[i-1][1] - bw2 - yadj], [gridData[i][0], gridData[i][1] + bw2 - yadj], [gridData[i][0], gridData[i][1] - bw2 - yadj]]);
}
// finally, draw the line
else {
points = points.concat([[gridData[i-1][0], gridData[i-1][1] - bw2 - yadj], [gridData[i][0], gridData[i][1] + bw2 - yadj], [gridData[i][0], yend], [xstart, yend]]);
if (shadow) {
this.renderer.shadowRenderer.draw(ctx, points);
}
var clr = opts.fillStyle || this.color;
this._dataColors.push(clr);
this.renderer.shapeRenderer.draw(ctx, points, opts);
}
}
}
}
if (this.highlightColors.length == 0) {
this.highlightColors = $.jqplot.computeHighlightColors(this._dataColors);
}
else if (typeof(this.highlightColors) == 'string') {
this.highlightColors = [];
for (var i=0; i<this._dataColors.length; i++) {
this.highlightColors.push(this.highlightColors);
}
}
};
// setup default renderers for axes and legend so user doesn't have to
// called with scope of plot
function preInit(target, data, options) {
options = options || {};
options.axesDefaults = options.axesDefaults || {};
options.grid = options.grid || {};
options.legend = options.legend || {};
options.seriesDefaults = options.seriesDefaults || {};
// only set these if there is a pie series
var setopts = false;
if (options.seriesDefaults.renderer === $.jqplot.PyramidRenderer) {
setopts = true;
}
else if (options.series) {
for (var i=0; i < options.series.length; i++) {
if (options.series[i].renderer === $.jqplot.PyramidRenderer) {
setopts = true;
}
}
}
if (setopts) {
options.axesDefaults.renderer = $.jqplot.PyramidAxisRenderer;
options.grid.renderer = $.jqplot.PyramidGridRenderer;
options.seriesDefaults.pointLabels = {show: false};
}
}
// called within context of plot
// create a canvas which we can draw on.
// insert it before the eventCanvas, so eventCanvas will still capture events.
function postPlotDraw() {
// Memory Leaks patch
if (this.plugins.pyramidRenderer && this.plugins.pyramidRenderer.highlightCanvas) {
this.plugins.pyramidRenderer.highlightCanvas.resetCanvas();
this.plugins.pyramidRenderer.highlightCanvas = null;
}
this.plugins.pyramidRenderer = {highlightedSeriesIndex:null};
this.plugins.pyramidRenderer.highlightCanvas = new $.jqplot.GenericCanvas();
this.eventCanvas._elem.before(this.plugins.pyramidRenderer.highlightCanvas.createElement(this._gridPadding, 'jqplot-pyramidRenderer-highlight-canvas', this._plotDimensions, this));
this.plugins.pyramidRenderer.highlightCanvas.setContext();
this.eventCanvas._elem.bind('mouseleave', {plot:this}, function (ev) { unhighlight(ev.data.plot); });
}
function highlight (plot, sidx, pidx, points) {
var s = plot.series[sidx];
var canvas = plot.plugins.pyramidRenderer.highlightCanvas;
canvas._ctx.clearRect(0,0,canvas._ctx.canvas.width, canvas._ctx.canvas.height);
s._highlightedPoint = pidx;
plot.plugins.pyramidRenderer.highlightedSeriesIndex = sidx;
var opts = {fillStyle: s.highlightColors[pidx], fillRect: false};
s.renderer.shapeRenderer.draw(canvas._ctx, points, opts);
if (s.synchronizeHighlight !== false && plot.series.length >= s.synchronizeHighlight && s.synchronizeHighlight !== sidx) {
s = plot.series[s.synchronizeHighlight];
opts = {fillStyle: s.highlightColors[pidx], fillRect: false};
s.renderer.shapeRenderer.draw(canvas._ctx, s._barPoints[pidx], opts);
}
canvas = null;
}
function unhighlight (plot) {
var canvas = plot.plugins.pyramidRenderer.highlightCanvas;
canvas._ctx.clearRect(0,0, canvas._ctx.canvas.width, canvas._ctx.canvas.height);
for (var i=0; i<plot.series.length; i++) {
plot.series[i]._highlightedPoint = null;
}
plot.plugins.pyramidRenderer.highlightedSeriesIndex = null;
plot.target.trigger('jqplotDataUnhighlight');
canvas = null;
}
function handleMove(ev, gridpos, datapos, neighbor, plot) {
if (neighbor) {
var ins = [neighbor.seriesIndex, neighbor.pointIndex, neighbor.data];
var evt1 = jQuery.Event('jqplotDataMouseOver');
evt1.pageX = ev.pageX;
evt1.pageY = ev.pageY;
plot.target.trigger(evt1, ins);
if (plot.series[ins[0]].highlightMouseOver && !(ins[0] == plot.plugins.pyramidRenderer.highlightedSeriesIndex && ins[1] == plot.series[ins[0]]._highlightedPoint)) {
var evt = jQuery.Event('jqplotDataHighlight');
evt.which = ev.which;
evt.pageX = ev.pageX;
evt.pageY = ev.pageY;
plot.target.trigger(evt, ins);
highlight (plot, neighbor.seriesIndex, neighbor.pointIndex, neighbor.points);
}
}
else if (neighbor == null) {
unhighlight (plot);
}
}
// Have to add hook here, becuase it needs called before series is inited.
$.jqplot.preInitHooks.push(preInit);
})(jQuery); | nolsherry/cdnjs | ajax/libs/jqPlot/1.0.2/plugins/jqplot.pyramidRenderer.js | JavaScript | mit | 21,112 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="shortcut icon" type="image/ico" href="http://www.datatables.net/favicon.ico">
<meta name="viewport" content="initial-scale=1.0, maximum-scale=2.0">
<title>AutoFill example - KeyTable integration</title>
<link rel="stylesheet" type="text/css" href="../../../../media/css/jquery.dataTables.css">
<link rel="stylesheet" type="text/css" href="../../css/autoFill.dataTables.css">
<link rel="stylesheet" type="text/css" href="../../../KeyTable/css/keyTable.dataTables.css">
<link rel="stylesheet" type="text/css" href="../../../../examples/resources/syntax/shCore.css">
<link rel="stylesheet" type="text/css" href="../../../../examples/resources/demo.css">
<style type="text/css" class="init">
</style>
<script type="text/javascript" language="javascript" src="//code.jquery.com/jquery-1.12.0.min.js">
</script>
<script type="text/javascript" language="javascript" src="../../../../media/js/jquery.dataTables.js">
</script>
<script type="text/javascript" language="javascript" src="../../js/dataTables.autoFill.js">
</script>
<script type="text/javascript" language="javascript" src="../../../KeyTable/js/dataTables.keyTable.js">
</script>
<script type="text/javascript" language="javascript" src="../../../../examples/resources/syntax/shCore.js">
</script>
<script type="text/javascript" language="javascript" src="../../../../examples/resources/demo.js">
</script>
<script type="text/javascript" language="javascript" class="init">
$(document).ready(function() {
$('#example').DataTable( {
keys: true,
autoFill: true
} );
} );
</script>
</head>
<body class="dt-example">
<div class="container">
<section>
<h1>AutoFill example <span>KeyTable integration</span></h1>
<div class="info">
<p>If you are looking to emulate the UI of spreadsheet programs such as Excel with DataTables, the combination of <a href=
"https://datatables.net/extensions/keytable">KeyTable</a> and AutoFill will take you a long way there!</p>
<p>AutoFill will automatically detect when KeyTable is used on the same table and later its focus option (<a href=
"//datatables.net/reference/option/autoFill.focus"><code class="option" title="AutoFill initialisation option">autoFill.focus</code></a>) so the focused cell will
show the auto fill handle. Thus all that needs to be done is to initialise both AutoFill and KeyTable with <a href=
"//datatables.net/reference/option/autoFill"><code class="option" title="AutoFill initialisation option">autoFill</code></a> and <a href=
"//datatables.net/reference/option/keys"><code class="option" title="KeyTable initialisation option">keys</code></a> respectively).</p>
</div>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
<tbody>
<tr>
<td>Tiger Nixon</td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>61</td>
<td>2011/04/25</td>
<td>$320,800</td>
</tr>
<tr>
<td>Garrett Winters</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>63</td>
<td>2011/07/25</td>
<td>$170,750</td>
</tr>
<tr>
<td>Ashton Cox</td>
<td>Junior Technical Author</td>
<td>San Francisco</td>
<td>66</td>
<td>2009/01/12</td>
<td>$86,000</td>
</tr>
<tr>
<td>Cedric Kelly</td>
<td>Senior Javascript Developer</td>
<td>Edinburgh</td>
<td>22</td>
<td>2012/03/29</td>
<td>$433,060</td>
</tr>
<tr>
<td>Airi Satou</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>33</td>
<td>2008/11/28</td>
<td>$162,700</td>
</tr>
<tr>
<td>Brielle Williamson</td>
<td>Integration Specialist</td>
<td>New York</td>
<td>61</td>
<td>2012/12/02</td>
<td>$372,000</td>
</tr>
<tr>
<td>Herrod Chandler</td>
<td>Sales Assistant</td>
<td>San Francisco</td>
<td>59</td>
<td>2012/08/06</td>
<td>$137,500</td>
</tr>
<tr>
<td>Rhona Davidson</td>
<td>Integration Specialist</td>
<td>Tokyo</td>
<td>55</td>
<td>2010/10/14</td>
<td>$327,900</td>
</tr>
<tr>
<td>Colleen Hurst</td>
<td>Javascript Developer</td>
<td>San Francisco</td>
<td>39</td>
<td>2009/09/15</td>
<td>$205,500</td>
</tr>
<tr>
<td>Sonya Frost</td>
<td>Software Engineer</td>
<td>Edinburgh</td>
<td>23</td>
<td>2008/12/13</td>
<td>$103,600</td>
</tr>
<tr>
<td>Jena Gaines</td>
<td>Office Manager</td>
<td>London</td>
<td>30</td>
<td>2008/12/19</td>
<td>$90,560</td>
</tr>
<tr>
<td>Quinn Flynn</td>
<td>Support Lead</td>
<td>Edinburgh</td>
<td>22</td>
<td>2013/03/03</td>
<td>$342,000</td>
</tr>
<tr>
<td>Charde Marshall</td>
<td>Regional Director</td>
<td>San Francisco</td>
<td>36</td>
<td>2008/10/16</td>
<td>$470,600</td>
</tr>
<tr>
<td>Haley Kennedy</td>
<td>Senior Marketing Designer</td>
<td>London</td>
<td>43</td>
<td>2012/12/18</td>
<td>$313,500</td>
</tr>
<tr>
<td>Tatyana Fitzpatrick</td>
<td>Regional Director</td>
<td>London</td>
<td>19</td>
<td>2010/03/17</td>
<td>$385,750</td>
</tr>
<tr>
<td>Michael Silva</td>
<td>Marketing Designer</td>
<td>London</td>
<td>66</td>
<td>2012/11/27</td>
<td>$198,500</td>
</tr>
<tr>
<td>Paul Byrd</td>
<td>Chief Financial Officer (CFO)</td>
<td>New York</td>
<td>64</td>
<td>2010/06/09</td>
<td>$725,000</td>
</tr>
<tr>
<td>Gloria Little</td>
<td>Systems Administrator</td>
<td>New York</td>
<td>59</td>
<td>2009/04/10</td>
<td>$237,500</td>
</tr>
<tr>
<td>Bradley Greer</td>
<td>Software Engineer</td>
<td>London</td>
<td>41</td>
<td>2012/10/13</td>
<td>$132,000</td>
</tr>
<tr>
<td>Dai Rios</td>
<td>Personnel Lead</td>
<td>Edinburgh</td>
<td>35</td>
<td>2012/09/26</td>
<td>$217,500</td>
</tr>
<tr>
<td>Jenette Caldwell</td>
<td>Development Lead</td>
<td>New York</td>
<td>30</td>
<td>2011/09/03</td>
<td>$345,000</td>
</tr>
<tr>
<td>Yuri Berry</td>
<td>Chief Marketing Officer (CMO)</td>
<td>New York</td>
<td>40</td>
<td>2009/06/25</td>
<td>$675,000</td>
</tr>
<tr>
<td>Caesar Vance</td>
<td>Pre-Sales Support</td>
<td>New York</td>
<td>21</td>
<td>2011/12/12</td>
<td>$106,450</td>
</tr>
<tr>
<td>Doris Wilder</td>
<td>Sales Assistant</td>
<td>Sidney</td>
<td>23</td>
<td>2010/09/20</td>
<td>$85,600</td>
</tr>
<tr>
<td>Angelica Ramos</td>
<td>Chief Executive Officer (CEO)</td>
<td>London</td>
<td>47</td>
<td>2009/10/09</td>
<td>$1,200,000</td>
</tr>
<tr>
<td>Gavin Joyce</td>
<td>Developer</td>
<td>Edinburgh</td>
<td>42</td>
<td>2010/12/22</td>
<td>$92,575</td>
</tr>
<tr>
<td>Jennifer Chang</td>
<td>Regional Director</td>
<td>Singapore</td>
<td>28</td>
<td>2010/11/14</td>
<td>$357,650</td>
</tr>
<tr>
<td>Brenden Wagner</td>
<td>Software Engineer</td>
<td>San Francisco</td>
<td>28</td>
<td>2011/06/07</td>
<td>$206,850</td>
</tr>
<tr>
<td>Fiona Green</td>
<td>Chief Operating Officer (COO)</td>
<td>San Francisco</td>
<td>48</td>
<td>2010/03/11</td>
<td>$850,000</td>
</tr>
<tr>
<td>Shou Itou</td>
<td>Regional Marketing</td>
<td>Tokyo</td>
<td>20</td>
<td>2011/08/14</td>
<td>$163,000</td>
</tr>
<tr>
<td>Michelle House</td>
<td>Integration Specialist</td>
<td>Sidney</td>
<td>37</td>
<td>2011/06/02</td>
<td>$95,400</td>
</tr>
<tr>
<td>Suki Burks</td>
<td>Developer</td>
<td>London</td>
<td>53</td>
<td>2009/10/22</td>
<td>$114,500</td>
</tr>
<tr>
<td>Prescott Bartlett</td>
<td>Technical Author</td>
<td>London</td>
<td>27</td>
<td>2011/05/07</td>
<td>$145,000</td>
</tr>
<tr>
<td>Gavin Cortez</td>
<td>Team Leader</td>
<td>San Francisco</td>
<td>22</td>
<td>2008/10/26</td>
<td>$235,500</td>
</tr>
<tr>
<td>Martena Mccray</td>
<td>Post-Sales support</td>
<td>Edinburgh</td>
<td>46</td>
<td>2011/03/09</td>
<td>$324,050</td>
</tr>
<tr>
<td>Unity Butler</td>
<td>Marketing Designer</td>
<td>San Francisco</td>
<td>47</td>
<td>2009/12/09</td>
<td>$85,675</td>
</tr>
<tr>
<td>Howard Hatfield</td>
<td>Office Manager</td>
<td>San Francisco</td>
<td>51</td>
<td>2008/12/16</td>
<td>$164,500</td>
</tr>
<tr>
<td>Hope Fuentes</td>
<td>Secretary</td>
<td>San Francisco</td>
<td>41</td>
<td>2010/02/12</td>
<td>$109,850</td>
</tr>
<tr>
<td>Vivian Harrell</td>
<td>Financial Controller</td>
<td>San Francisco</td>
<td>62</td>
<td>2009/02/14</td>
<td>$452,500</td>
</tr>
<tr>
<td>Timothy Mooney</td>
<td>Office Manager</td>
<td>London</td>
<td>37</td>
<td>2008/12/11</td>
<td>$136,200</td>
</tr>
<tr>
<td>Jackson Bradshaw</td>
<td>Director</td>
<td>New York</td>
<td>65</td>
<td>2008/09/26</td>
<td>$645,750</td>
</tr>
<tr>
<td>Olivia Liang</td>
<td>Support Engineer</td>
<td>Singapore</td>
<td>64</td>
<td>2011/02/03</td>
<td>$234,500</td>
</tr>
<tr>
<td>Bruno Nash</td>
<td>Software Engineer</td>
<td>London</td>
<td>38</td>
<td>2011/05/03</td>
<td>$163,500</td>
</tr>
<tr>
<td>Sakura Yamamoto</td>
<td>Support Engineer</td>
<td>Tokyo</td>
<td>37</td>
<td>2009/08/19</td>
<td>$139,575</td>
</tr>
<tr>
<td>Thor Walton</td>
<td>Developer</td>
<td>New York</td>
<td>61</td>
<td>2013/08/11</td>
<td>$98,540</td>
</tr>
<tr>
<td>Finn Camacho</td>
<td>Support Engineer</td>
<td>San Francisco</td>
<td>47</td>
<td>2009/07/07</td>
<td>$87,500</td>
</tr>
<tr>
<td>Serge Baldwin</td>
<td>Data Coordinator</td>
<td>Singapore</td>
<td>64</td>
<td>2012/04/09</td>
<td>$138,575</td>
</tr>
<tr>
<td>Zenaida Frank</td>
<td>Software Engineer</td>
<td>New York</td>
<td>63</td>
<td>2010/01/04</td>
<td>$125,250</td>
</tr>
<tr>
<td>Zorita Serrano</td>
<td>Software Engineer</td>
<td>San Francisco</td>
<td>56</td>
<td>2012/06/01</td>
<td>$115,000</td>
</tr>
<tr>
<td>Jennifer Acosta</td>
<td>Junior Javascript Developer</td>
<td>Edinburgh</td>
<td>43</td>
<td>2013/02/01</td>
<td>$75,650</td>
</tr>
<tr>
<td>Cara Stevens</td>
<td>Sales Assistant</td>
<td>New York</td>
<td>46</td>
<td>2011/12/06</td>
<td>$145,600</td>
</tr>
<tr>
<td>Hermione Butler</td>
<td>Regional Director</td>
<td>London</td>
<td>47</td>
<td>2011/03/21</td>
<td>$356,250</td>
</tr>
<tr>
<td>Lael Greer</td>
<td>Systems Administrator</td>
<td>London</td>
<td>21</td>
<td>2009/02/27</td>
<td>$103,500</td>
</tr>
<tr>
<td>Jonas Alexander</td>
<td>Developer</td>
<td>San Francisco</td>
<td>30</td>
<td>2010/07/14</td>
<td>$86,500</td>
</tr>
<tr>
<td>Shad Decker</td>
<td>Regional Director</td>
<td>Edinburgh</td>
<td>51</td>
<td>2008/11/13</td>
<td>$183,000</td>
</tr>
<tr>
<td>Michael Bruce</td>
<td>Javascript Developer</td>
<td>Singapore</td>
<td>29</td>
<td>2011/06/27</td>
<td>$183,000</td>
</tr>
<tr>
<td>Donna Snider</td>
<td>Customer Support</td>
<td>New York</td>
<td>27</td>
<td>2011/01/25</td>
<td>$112,000</td>
</tr>
</tbody>
</table>
<ul class="tabs">
<li class="active">Javascript</li>
<li>HTML</li>
<li>CSS</li>
<li>Ajax</li>
<li>Server-side script</li>
</ul>
<div class="tabs">
<div class="js">
<p>The Javascript shown below is used to initialise the table shown in this example:</p><code class="multiline language-js">$(document).ready(function() {
$('#example').DataTable( {
keys: true,
autoFill: true
} );
} );</code>
<p>In addition to the above code, the following Javascript library files are loaded for use in this example:</p>
<ul>
<li>
<a href="//code.jquery.com/jquery-1.12.0.min.js">//code.jquery.com/jquery-1.12.0.min.js</a>
</li>
<li>
<a href="../../../../media/js/jquery.dataTables.js">../../../../media/js/jquery.dataTables.js</a>
</li>
<li>
<a href="../../js/dataTables.autoFill.js">../../js/dataTables.autoFill.js</a>
</li>
<li>
<a href="../../../KeyTable/js/dataTables.keyTable.js">../../../KeyTable/js/dataTables.keyTable.js</a>
</li>
</ul>
</div>
<div class="table">
<p>The HTML shown below is the raw HTML table element, before it has been enhanced by DataTables:</p>
</div>
<div class="css">
<div>
<p>This example uses a little bit of additional CSS beyond what is loaded from the library files (below), in order to correctly display the table. The
additional CSS used is shown below:</p><code class="multiline language-css"></code>
</div>
<p>The following CSS library files are loaded for use in this example to provide the styling of the table:</p>
<ul>
<li>
<a href="../../../../media/css/jquery.dataTables.css">../../../../media/css/jquery.dataTables.css</a>
</li>
<li>
<a href="../../css/autoFill.dataTables.css">../../css/autoFill.dataTables.css</a>
</li>
<li>
<a href="../../../KeyTable/css/keyTable.dataTables.css">../../../KeyTable/css/keyTable.dataTables.css</a>
</li>
</ul>
</div>
<div class="ajax">
<p>This table loads data by Ajax. The latest data that has been loaded is shown below. This data will update automatically as any additional data is
loaded.</p>
</div>
<div class="php">
<p>The script used to perform the server-side processing for this table is shown below. Please note that this is just an example script using PHP. Server-side
processing scripts can be written in any language, using <a href="//datatables.net/manual/server-side">the protocol described in the DataTables
documentation</a>.</p>
</div>
</div>
</section>
</div>
<section>
<div class="footer">
<div class="gradient"></div>
<div class="liner">
<h2>Other examples</h2>
<div class="toc">
<div class="toc-group">
<h3><a href="./index.html">Initialisation</a></h3>
<ul class="toc active">
<li>
<a href="./simple.html">Basic initialisation</a>
</li>
<li>
<a href="./fills.html">Fill types</a>
</li>
<li class="active">
<a href="./keyTable.html">KeyTable integration</a>
</li>
<li>
<a href="./events.html">Events</a>
</li>
<li>
<a href="./alwaysAsk.html">Always confirm action</a>
</li>
<li>
<a href="./columns.html">Column selector</a>
</li>
<li>
<a href="./focus.html">Click focus</a>
</li>
<li>
<a href="./scrolling.html">Scrolling DataTable</a>
</li>
<li>
<a href="./plugins.html">Fill plug-ins</a>
</li>
</ul>
</div>
<div class="toc-group">
<h3><a href="../styling/index.html">Styling</a></h3>
<ul class="toc">
<li>
<a href="../styling/bootstrap.html">Bootstrap styling</a>
</li>
<li>
<a href="../styling/foundation.html">Foundation styling</a>
</li>
<li>
<a href="../styling/jqueryui.html">jQuery UI styling</a>
</li>
</ul>
</div>
</div>
<div class="epilogue">
<p>Please refer to the <a href="http://www.datatables.net">DataTables documentation</a> for full information about its API properties and methods.<br>
Additionally, there are a wide range of <a href="http://www.datatables.net/extensions">extensions</a> and <a href=
"http://www.datatables.net/plug-ins">plug-ins</a> which extend the capabilities of DataTables.</p>
<p class="copyright">DataTables designed and created by <a href="http://www.sprymedia.co.uk">SpryMedia Ltd</a> © 2007-2016<br>
DataTables is licensed under the <a href="http://www.datatables.net/mit">MIT license</a>.</p>
</div>
</div>
</div>
</section>
</body>
</html> | SongkranGit/rmsf | assets/adminlte2/plugins/datatables/extensions/AutoFill/examples/initialisation/keyTable.html | HTML | mit | 17,962 |
<?php
namespace DoctrineExtensions\Versionable;
use Doctrine\Common\EventSubscriber,
Doctrine\ORM\Events,
Doctrine\ORM\Event\OnFlushEventArgs,
Doctrine\ORM\EntityManager,
DoctrineExtensions\Versionable\Entity\ResourceVersion;
class VersionListener implements EventSubscriber
{
public function getSubscribedEvents()
{
return array(Events::onFlush);
}
/**
* @param OnFlushEventArgs $args
*/
public function onFlush(OnFlushEventArgs $args)
{
/* @var $em Doctrine\ORM\EntityManager */
$em = $args->getEntityManager();
/* @var $uow Doctrine\ORM\UnitOfWork */
$uow = $em->getUnitOfWork();
/* @var $resourceClass Doctrine\ORM\Mapping\ClassMetadata */
$resourceClass = $em->getClassMetadata('DoctrineExtensions\Versionable\Entity\ResourceVersion');
foreach ($uow->getScheduledEntityUpdates() AS $entity) {
if ($entity instanceof Versionable) {
$entityClass = $em->getClassMetadata(get_class($entity));
if (!$entityClass->isVersioned) {
throw Exception::versionedEntityRequired();
}
$entityId = $entityClass->getIdentifierValues($entity);
if (count($entityId) == 1 && current($entityId)) {
$entityId = current($entityId);
} else {
throw Exception::singleIdentifierRequired();
}
$oldValues = array_map(function($changeSetField) {
return $changeSetField[0];
}, $uow->getEntityChangeSet($entity));
$entityVersion = $entityClass->reflFields[$entityClass->versionField]->getValue($entity);
unset($oldValues[$entityClass->versionField]);
unset($oldValues[$entityClass->getSingleIdentifierFieldName()]);
$resourceVersion = new ResourceVersion($entityClass->name, $entityId, $oldValues, $entityVersion);
$em->persist( $resourceVersion );
$uow->computeChangeSet($resourceClass, $resourceVersion);
}
}
}
} | vgrdominik2/cupon | vendor/beberlei/DoctrineExtensions/lib/DoctrineExtensions/Versionable/VersionListener.php | PHP | mit | 2,184 |
<?php
namespace Faker;
/**
* @property string $name
* @property string $firstName
* @property string $firstNameMale
* @property string $firstNameFemale
* @property string $lastName
* @property string $title
* @property string $titleMale
* @property string $titleFemale
*
* @property string $citySuffix
* @property string $streetSuffix
* @property string $buildingNumber
* @property string $city
* @property string $streetName
* @property string $streetAddress
* @property string $postcode
* @property string $address
* @property string $country
* @property float $latitude
* @property float $longitude
*
* @property string $ean13
* @property string $ean8
* @property string $isbn13
* @property string $isbn10
*
* @property string $phoneNumber
*
* @property string $company
* @property string $companySuffix
*
* @property string $creditCardType
* @property string $creditCardNumber
* @method string creditCardNumber($type = null, $formatted = false, $separator = '-')
* @property \DateTime $creditCardExpirationDate
* @property string $creditCardExpirationDateString
* @property string $creditCardDetails
* @property string $bankAccountNumber
* @method string iban($countryCode = null, $prefix = '', $length = null)
* @property string $swiftBicNumber
* @property string $vat
*
* @property string $word
* @property string|array $words
* @method string|array words($nb = 3, $asText = false)
* @property string $sentence
* @method string sentence($nbWords = 6, $variableNbWords = true)
* @property string|array $sentences
* @method string|array sentences($nb = 3, $asText = false)
* @property string $paragraph
* @method string paragraph($nbSentences = 3, $variableNbSentences = true)
* @property string|array $paragraphs
* @method string|array paragraphs($nb = 3, $asText = false)
* @property string $text
* @method string text($maxNbChars = 200)
*
* @method string realText($maxNbChars = 200, $indexSize = 2)
*
* @property string $email
* @property string $safeEmail
* @property string $freeEmail
* @property string $companyEmail
* @property string $freeEmailDomain
* @property string $safeEmailDomain
* @property string $userName
* @property string $password
* @method string password($minLength = 6, $maxLength = 20)
* @property string $domainName
* @property string $domainWord
* @property string $tld
* @property string $url
* @property string $slug
* @method string slug($nbWords = 6, $variableNbWords = true)
* @property string $ipv4
* @property string $ipv6
* @property string $localIpv4
* @property string $macAddress
*
* @property int $unixTime
* @property \DateTime $dateTime
* @property \DateTime $dateTimeAD
* @property string $iso8601
* @property \DateTime $dateTimeThisCentury
* @property \DateTime $dateTimeThisDecade
* @property \DateTime $dateTimeThisYear
* @property \DateTime $dateTimeThisMonth
* @property string $amPm
* @property int $dayOfMonth
* @property int $dayOfWeek
* @property int $month
* @property string $monthName
* @property int $year
* @property int $century
* @property string $timezone
* @method string date($format = 'Y-m-d', $max = 'now')
* @method string time($format = 'H:i:s', $max = 'now')
* @method \DateTime dateTimeBetween($startDate = '-30 years', $endDate = 'now')
*
* @property string $md5
* @property string $sha1
* @property string $sha256
* @property string $locale
* @property string $countryCode
* @property string $countryISOAlpha3
* @property string $languageCode
* @property string $currencyCode
* @method boolean boolean($chanceOfGettingTrue = 50)
*
* @property int $randomDigit
* @property int $randomDigitNotNull
* @property string $randomLetter
* @property string $randomAscii
* @method int randomNumber($nbDigits = null, $strict = false)
* @method int|string|null randomKey(array $array = array())
* @method int numberBetween($min = 0, $max = 2147483647)
* @method float randomFloat($nbMaxDecimals = null, $min = 0, $max = null)
* @method mixed randomElement(array $array = array('a', 'b', 'c'))
* @method array randomElements(array $array = array('a', 'b', 'c'), $count = 1)
* @method array|string shuffle($arg = '')
* @method array shuffleArray(array $array = array())
* @method string shuffleString($string = '', $encoding = 'UTF-8')
* @method string numerify($string = '###')
* @method string lexify($string = '????')
* @method string bothify($string = '## ??')
* @method string asciify($string = '****')
* @method string regexify($regex = '')
* @method string toLower($string = '')
* @method string toUpper($string = '')
* @method Generator optional($weight = 0.5, $default = null)
* @method Generator unique($reset = false, $maxRetries = 10000)
*
* @method integer biasedNumberBetween($min = 0, $max = 100, $function = 'sqrt')
*
* @property string $macProcessor
* @property string $linuxProcessor
* @property string $userAgent
* @property string $chrome
* @property string $firefox
* @property string $safari
* @property string $opera
* @property string $internetExplorer
* @property string $windowsPlatformToken
* @property string $macPlatformToken
* @property string $linuxPlatformToken
*
* @property string $uuid
*
* @property string $mimeType
* @property string $fileExtension
* @method string file($sourceDirectory = '/tmp', $targetDirectory = '/tmp', $fullPath = true)
*
* @method string imageUrl($width = 640, $height = 480, $category = null, $randomize = true)
* @method string image($dir = null, $width = 640, $height = 480, $category = null, $fullPath = true)
*
* @property string $hexColor
* @property string $safeHexColor
* @property string $rgbColor
* @property array $rgbColorAsArray
* @property string $rgbCssColor
* @property string $safeColorName
* @property string $colorName
*/
class Generator
{
protected $providers = array();
protected $formatters = array();
public function addProvider($provider)
{
array_unshift($this->providers, $provider);
}
public function getProviders()
{
return $this->providers;
}
public function seed($seed = null)
{
if ($seed === null) {
mt_srand();
} else {
mt_srand((int) $seed);
}
}
public function format($formatter, $arguments = array())
{
return call_user_func_array($this->getFormatter($formatter), $arguments);
}
/**
* @return Callable
*/
public function getFormatter($formatter)
{
if (isset($this->formatters[$formatter])) {
return $this->formatters[$formatter];
}
foreach ($this->providers as $provider) {
if (method_exists($provider, $formatter)) {
$this->formatters[$formatter] = array($provider, $formatter);
return $this->formatters[$formatter];
}
}
throw new \InvalidArgumentException(sprintf('Unknown formatter "%s"', $formatter));
}
/**
* Replaces tokens ('{{ tokenName }}') with the result from the token method call
*
* @param string $string String that needs to bet parsed
* @return string
*/
public function parse($string)
{
return preg_replace_callback('/\{\{\s?(\w+)\s?\}\}/u', array($this, 'callFormatWithMatches'), $string);
}
protected function callFormatWithMatches($matches)
{
return $this->format($matches[1]);
}
public function __get($attribute)
{
return $this->format($attribute);
}
public function __call($method, $attributes)
{
return $this->format($method, $attributes);
}
}
| kevinrodbe/Faker | src/Faker/Generator.php | PHP | mit | 7,725 |
// Combinations of templates and structure inheritance.
//
// Created by Alex Ott.
template <typename DerivedT>
struct grammar {
public:
typedef grammar<DerivedT> self_t;
typedef DerivedT const& embed_t;
grammar() {}
~grammar() { }
void use_parser() const { }
void test1() { }
};
struct PDFbool_parser : public grammar<PDFbool_parser> {
PDFbool_parser() {}
template <typename scannerT> struct definition {
typedef typename scannerT::iterator_t iterator_t;
int top;
definition(const PDFbool_parser& /*self*/) {
return ;
}
const int start() const {
return top;
}
};
};
int main(void) {
PDFbool_parser PDFbool_p = PDFbool_parser();
PDFbool_p.//-1-
;
// #1# ("definition" "embed_t" "self_t" "test1" "use_parser")
}
// ----------------------------------------------------------------------
template <class Derived> struct Base {
public:
void interface()
{
// ...
static_cast<Derived*>(this)->implementation();
// ...
}
static void static_func()
{
// ...
Derived::static_sub_func();
// ...
}
};
struct Derived : Base<Derived> {
void implementation() { }
static void static_sub_func() { }
};
int foo () {
Derived d;
d.//-2-
;
// #2# ("implementation" "interface" "static_func" "static_sub_func")
}
| littletwolee/emacs-configure | .emacs.d/cedet/semantic/tests/teststruct.cpp | C++ | mit | 1,313 |
<?php
namespace Concrete\Core\Config;
class DatabaseSaver implements SaverInterface
{
/**
* Save config item
*
* @param string $item
* @param string $value
* @param string $environment
* @param string $group
* @param string|null $namespace
* @return bool
*/
public function save($item, $value, $environment, $group, $namespace = null)
{
if (is_array($value)) {
foreach ($value as $key => $val) {
$key = ($item ? $item . '.' : '') . $key;
$this->save($key, $val, $environment, $group, $namespace);
}
return;
}
$query = \Database::createQueryBuilder();
$query->update('Config', 'c')
->set('configValue', $query->expr()->literal($value))
->where($query->expr()->comparison('configGroup', '=', $query->expr()->literal($group)));
if ($item) {
$query->andWhere($query->expr()->comparison('configItem', '=', $query->expr()->literal($item)));
}
$query->andWhere($query->expr()->comparison('configNamespace', '=', $query->expr()->literal($namespace ?: '')));
if (!$query->execute()) {
try {
$query = "INSERT INTO Config (configItem, configValue, configGroup, configNamespace) VALUES (?, ?, ?, ?)";
\Database::executeQuery(
$query,
array(
$item,
$value,
$group,
$namespace ?: ''
));
} catch (\Exception $e) {
// This happens when the update succeeded, but didn't actually change anything on the row.
}
}
}
}
| lisophorm/c5changelogtest | concrete/src/Config/DatabaseSaver.php | PHP | mit | 1,808 |
/**
* @author Mat Groves http://matgroves.com/ @Doormat23
*/
/**
* Utility methods for Sprite/Texture tinting.
*
* @class CanvasTinter
* @static
*/
PIXI.CanvasTinter = function()
{
};
/**
* Basically this method just needs a sprite and a color and tints the sprite with the given color.
*
* @method getTintedTexture
* @static
* @param sprite {Sprite} the sprite to tint
* @param color {Number} the color to use to tint the sprite with
* @return {HTMLCanvasElement} The tinted canvas
*/
PIXI.CanvasTinter.getTintedTexture = function(sprite, color)
{
var texture = sprite.texture;
color = PIXI.CanvasTinter.roundColor(color);
var stringColor = "#" + ("00000" + ( color | 0).toString(16)).substr(-6);
texture.tintCache = texture.tintCache || {};
if(texture.tintCache[stringColor]) return texture.tintCache[stringColor];
// clone texture..
var canvas = PIXI.CanvasTinter.canvas || document.createElement("canvas");
//PIXI.CanvasTinter.tintWithPerPixel(texture, stringColor, canvas);
PIXI.CanvasTinter.tintMethod(texture, color, canvas);
if(PIXI.CanvasTinter.convertTintToImage)
{
// is this better?
var tintImage = new Image();
tintImage.src = canvas.toDataURL();
texture.tintCache[stringColor] = tintImage;
}
else
{
texture.tintCache[stringColor] = canvas;
// if we are not converting the texture to an image then we need to lose the reference to the canvas
PIXI.CanvasTinter.canvas = null;
}
return canvas;
};
/**
* Tint a texture using the "multiply" operation.
*
* @method tintWithMultiply
* @static
* @param texture {Texture} the texture to tint
* @param color {Number} the color to use to tint the sprite with
* @param canvas {HTMLCanvasElement} the current canvas
*/
PIXI.CanvasTinter.tintWithMultiply = function(texture, color, canvas)
{
var context = canvas.getContext( "2d" );
var crop = texture.crop;
canvas.width = crop.width;
canvas.height = crop.height;
context.fillStyle = "#" + ("00000" + ( color | 0).toString(16)).substr(-6);
context.fillRect(0, 0, crop.width, crop.height);
context.globalCompositeOperation = "multiply";
context.drawImage(texture.baseTexture.source,
crop.x,
crop.y,
crop.width,
crop.height,
0,
0,
crop.width,
crop.height);
context.globalCompositeOperation = "destination-atop";
context.drawImage(texture.baseTexture.source,
crop.x,
crop.y,
crop.width,
crop.height,
0,
0,
crop.width,
crop.height);
};
/**
* Tint a texture using the "overlay" operation.
*
* @method tintWithOverlay
* @static
* @param texture {Texture} the texture to tint
* @param color {Number} the color to use to tint the sprite with
* @param canvas {HTMLCanvasElement} the current canvas
*/
PIXI.CanvasTinter.tintWithOverlay = function(texture, color, canvas)
{
var context = canvas.getContext( "2d" );
var crop = texture.crop;
canvas.width = crop.width;
canvas.height = crop.height;
context.globalCompositeOperation = "copy";
context.fillStyle = "#" + ("00000" + ( color | 0).toString(16)).substr(-6);
context.fillRect(0, 0, crop.width, crop.height);
context.globalCompositeOperation = "destination-atop";
context.drawImage(texture.baseTexture.source,
crop.x,
crop.y,
crop.width,
crop.height,
0,
0,
crop.width,
crop.height);
//context.globalCompositeOperation = "copy";
};
/**
* Tint a texture pixel per pixel.
*
* @method tintPerPixel
* @static
* @param texture {Texture} the texture to tint
* @param color {Number} the color to use to tint the sprite with
* @param canvas {HTMLCanvasElement} the current canvas
*/
PIXI.CanvasTinter.tintWithPerPixel = function(texture, color, canvas)
{
var context = canvas.getContext( "2d" );
var crop = texture.crop;
canvas.width = crop.width;
canvas.height = crop.height;
context.globalCompositeOperation = "copy";
context.drawImage(texture.baseTexture.source,
crop.x,
crop.y,
crop.width,
crop.height,
0,
0,
crop.width,
crop.height);
var rgbValues = PIXI.hex2rgb(color);
var r = rgbValues[0], g = rgbValues[1], b = rgbValues[2];
var pixelData = context.getImageData(0, 0, crop.width, crop.height);
var pixels = pixelData.data;
for (var i = 0; i < pixels.length; i += 4)
{
pixels[i+0] *= r;
pixels[i+1] *= g;
pixels[i+2] *= b;
}
context.putImageData(pixelData, 0, 0);
};
/**
* Rounds the specified color according to the PIXI.CanvasTinter.cacheStepsPerColorChannel.
*
* @method roundColor
* @static
* @param color {number} the color to round, should be a hex color
*/
PIXI.CanvasTinter.roundColor = function(color)
{
var step = PIXI.CanvasTinter.cacheStepsPerColorChannel;
var rgbValues = PIXI.hex2rgb(color);
rgbValues[0] = Math.min(255, (rgbValues[0] / step) * step);
rgbValues[1] = Math.min(255, (rgbValues[1] / step) * step);
rgbValues[2] = Math.min(255, (rgbValues[2] / step) * step);
return PIXI.rgb2hex(rgbValues);
};
/**
* Number of steps which will be used as a cap when rounding colors.
*
* @property cacheStepsPerColorChannel
* @type Number
* @static
*/
PIXI.CanvasTinter.cacheStepsPerColorChannel = 8;
/**
* Tint cache boolean flag.
*
* @property convertTintToImage
* @type Boolean
* @static
*/
PIXI.CanvasTinter.convertTintToImage = false;
/**
* Whether or not the Canvas BlendModes are supported, consequently the ability to tint using the multiply method.
*
* @property canUseMultiply
* @type Boolean
* @static
*/
PIXI.CanvasTinter.canUseMultiply = PIXI.canUseNewCanvasBlendModes();
/**
* The tinting method that will be used.
*
* @method tintMethod
* @static
*/
PIXI.CanvasTinter.tintMethod = PIXI.CanvasTinter.canUseMultiply ? PIXI.CanvasTinter.tintWithMultiply : PIXI.CanvasTinter.tintWithPerPixel;
| Maanraket/chessdungeon.js | bower_components/pixi/src/pixi/renderers/canvas/utils/CanvasTinter.js | JavaScript | mit | 6,770 |
/*
* /MathJax/jax/output/HTML-CSS/jax.js
*
* Copyright (c) 2009-2015 The MathJax Consortium
*
* 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.
*/
(function(h,b,d){var g,i=b.Browser.isMobile;var e=function(){var k=[].slice.call(arguments,0);k[0][0]=["HTML-CSS",k[0][0]];return MathJax.Message.Set.apply(MathJax.Message,k)};var f=MathJax.Object.Subclass({timeout:(i?15:8)*1000,comparisonFont:["sans-serif","monospace","script","Times","Courier","Arial","Helvetica"],testSize:["40px","50px","60px","30px","20px"],FedoraSTIXcheck:{family:"STIXSizeOneSym",testString:"abcABC",noStyleChar:true},Init:function(){this.div=MathJax.HTML.addElement(document.body,"div",{style:{position:"absolute",width:0,height:0,overflow:"hidden",padding:0,border:0,margin:0}},[["div",{id:"MathJax_Font_Test",style:{position:"absolute",visibility:"hidden",top:0,left:0,width:"auto",padding:0,border:0,margin:0,whiteSpace:"nowrap",textAlign:"left",textIndent:0,textTransform:"none",lineHeight:"normal",letterSpacing:"normal",wordSpacing:"normal",fontSize:this.testSize[0],fontWeight:"normal",fontStyle:"normal",fontSizeAdjust:"none"}},[""]]]).firstChild;this.text=this.div.firstChild},findFont:function(p,l){var o=null;if(l&&this.testCollection(l)){o=l}else{for(var n=0,k=p.length;n<k;n++){if(p[n]===l){continue}if(this.testCollection(p[n])){o=p[n];break}}}if(o==="STIX"&&this.testFont(this.FedoraSTIXcheck)){o=null}return o},testCollection:function(l){var k={testString:"() {} []"};k.family={TeX:"MathJax_Size1",STIX:"STIXSizeOneSym"}[l]||l.replace(/-(Math)?/,"")+"MathJax_Size1";if(l==="STIX"){k.noStyleChar=true}return this.testFont(k)},testFont:function(n){if(n.isWebFont&&d.FontFaceBug){this.div.style.fontWeight=this.div.style.fontStyle="normal"}else{this.div.style.fontWeight=(n.weight||"normal");this.div.style.fontStyle=(n.style||"normal")}var p=n.familyFixed||n.family;if(!p.match(/^(STIX|MathJax)|'/)){p=p.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/ Jax/,"Jax")+"','"+p+"','"+p+"-";if(n.weight){p+="Bold"}if(n.style){p+="Italic"}if(!n.weight&&!n.style){p+="Regular"}n.familyFixed=p="'"+p+"'"}var l=this.getComparisonWidths(n.testString,n.noStyleChar);var q=null;if(l){this.div.style.fontFamily=p+","+this.comparisonFont[0];if(this.div.offsetWidth==l[0]){this.div.style.fontFamily=p+","+this.comparisonFont[l[2]];if(this.div.offsetWidth==l[1]){q=false}}if(q===null&&(this.div.offsetWidth!=l[3]||this.div.offsetHeight!=l[4])){if(!n.noStyleChar&&d.FONTDATA&&d.FONTDATA.hasStyleChar){for(var o=0,k=this.testSize.length;o<k;o++){if(this.testStyleChar(n,this.testSize[o])){q=true;k=0}}}else{q=true}}}if(d.safariTextNodeBug){this.div.innerHTML=""}else{this.text.nodeValue=""}return q},styleChar:"\uEFFD",versionChar:"\uEFFE",compChar:"\uEFFF",testStyleChar:function(m,p){var s=3+(m.weight?2:0)+(m.style?4:0);var l="",o=0;var r=this.div.style.fontSize;this.div.style.fontSize=p;if(d.msieItalicWidthBug&&m.style==="italic"){this.text.nodeValue=l=this.compChar;o=this.div.offsetWidth}if(d.safariTextNodeBug){this.div.innerHTML=this.compChar+l}else{this.text.nodeValue=this.compChar+l}var k=this.div.offsetWidth-o;if(d.safariTextNodeBug){this.div.innerHTML=this.styleChar+l}else{this.text.nodeValue=this.styleChar+l}var q=Math.floor((this.div.offsetWidth-o)/k+0.5);if(q===s){if(d.safariTextNodeBug){this.div.innerHTML=this.versionChar+l}else{this.text.nodeValue=this.versionChar+l}m.version=Math.floor((this.div.offsetWidth-o)/k+1.5)/2}this.div.style.fontSize=r;return(q===s)},getComparisonWidths:function(p,n){if(d.FONTDATA&&d.FONTDATA.hasStyleChar&&!n){p+=this.styleChar+" "+this.compChar}if(d.safariTextNodeBug){this.div.innerHTML=p}else{this.text.nodeValue=p}this.div.style.fontFamily=this.comparisonFont[0];var l=this.div.offsetWidth;this.div.style.fontFamily=d.webFontDefault;var r=this.div.offsetWidth,o=this.div.offsetHeight;for(var q=1,k=this.comparisonFont.length;q<k;q++){this.div.style.fontFamily=this.comparisonFont[q];if(this.div.offsetWidth!=l){return[l,this.div.offsetWidth,q,r,o]}}return null},loadWebFont:function(l){b.Startup.signal.Post("HTML-CSS Jax - Web-Font "+d.fontInUse+"/"+l.directory);var o=e(["LoadWebFont","Loading web-font %1",d.fontInUse+"/"+l.directory]);var k=MathJax.Callback({});var m=MathJax.Callback(["loadComplete",this,l,o,k]);h.timer.start(h,[this.checkWebFont,l,m],0,this.timeout);return k},loadComplete:function(m,p,l,k){MathJax.Message.Clear(p);if(k===h.STATUS.OK){this.webFontLoaded=true;l();return}this.loadError(m);if(b.Browser.isFirefox&&d.allowWebFonts){var o=document.location.protocol+"//"+document.location.hostname;if(document.location.port!=""){o+=":"+document.location.port}o+="/";if(h.fileURL(d.webfontDir).substr(0,o.length)!==o){this.firefoxFontError(m)}}if(!this.webFontLoaded){d.loadWebFontError(m,l)}else{l()}},loadError:function(k){e(["CantLoadWebFont","Can't load web font %1",d.fontInUse+"/"+k.directory],null,2000);b.Startup.signal.Post(["HTML-CSS Jax - web font error",d.fontInUse+"/"+k.directory,k])},firefoxFontError:function(k){e(["FirefoxCantLoadWebFont","Firefox can't load web fonts from a remote host"],null,3000);b.Startup.signal.Post("HTML-CSS Jax - Firefox web fonts on remote host error")},checkWebFont:function(k,l,m){if(k.time(m)){return}if(d.Font.testFont(l)){m(k.STATUS.OK)}else{setTimeout(k,k.delay)}},fontFace:function(o){var p=d.allowWebFonts;var r=d.FONTDATA.FONTS[o];if(d.msieFontCSSBug&&!r.family.match(/-Web$/)){r.family+="-Web"}var k=d.webfontDir+"/"+p;var n=h.fileURL(k);var m=o.replace(/-b/,"-B").replace(/-i/,"-I").replace(/-Bold-/,"-Bold");if(!m.match(/-/)){m+="-Regular"}if(p==="svg"){m+=".svg#"+m}else{m+="."+p}var l=h.fileRev(k+"/"+m.replace(/#.*/,""));var q={"font-family":r.family,src:"url('"+n+"/"+m+l+"')"};if(p==="otf"){m=m.replace(/otf$/,"woff");l=h.fileRev(k+"/"+m);q.src+=" format('opentype')";n=h.fileURL(d.webfontDir+"/woff");q.src="url('"+n+"/"+m+l+"') format('woff'), "+q.src}else{if(p!=="eot"){q.src+=" format('"+p+"')"}}if(!(d.FontFaceBug&&r.isWebFont)){if(o.match(/-bold/)){q["font-weight"]="bold"}if(o.match(/-italic/)){q["font-style"]="italic"}}return q}});var j,a,c;d.Augment({config:{styles:{".MathJax":{display:"inline","font-style":"normal","font-weight":"normal","line-height":"normal","font-size":"100%","font-size-adjust":"none","text-indent":0,"text-align":"left","text-transform":"none","letter-spacing":"normal","word-spacing":"normal","word-wrap":"normal","white-space":"nowrap","float":"none",direction:"ltr","max-width":"none","max-height":"none","min-width":0,"min-height":0,border:0,padding:0,margin:0},".MathJax_Display":{position:"relative",display:"block!important","text-indent":0,"max-width":"none","max-height":"none","min-width":0,"min-height":0,width:"100%"},".MathJax img, .MathJax nobr, .MathJax a":{border:0,padding:0,margin:0,"max-width":"none","max-height":"none","min-width":0,"min-height":0,"vertical-align":0,"line-height":"normal","text-decoration":"none"},"img.MathJax_strut":{border:"0!important",padding:"0!important",margin:"0!important","vertical-align":"0!important"},".MathJax span":{display:"inline",position:"static",border:0,padding:0,margin:0,"vertical-align":0,"line-height":"normal","text-decoration":"none"},".MathJax nobr":{"white-space":"nowrap!important"},".MathJax img":{display:"inline!important","float":"none!important"},".MathJax *":{transition:"none","-webkit-transition":"none","-moz-transition":"none","-ms-transition":"none","-o-transition":"none"},".MathJax_Processing":{visibility:"hidden",position:"fixed",width:0,height:0,overflow:"hidden"},".MathJax_Processed":{display:"none!important"},".MathJax_ExBox":{display:"block!important",overflow:"hidden",width:"1px",height:"60ex","min-height":0,"max-height":"none"},".MathJax .MathJax_EmBox":{display:"block!important",overflow:"hidden",width:"1px",height:"60em","min-height":0,"max-height":"none"},".MathJax .MathJax_HitBox":{cursor:"text",background:"white",opacity:0,filter:"alpha(opacity=0)"},".MathJax .MathJax_HitBox *":{filter:"none",opacity:1,background:"transparent"},"#MathJax_Tooltip":{position:"absolute",left:0,top:0,width:"auto",height:"auto",display:"none"},"#MathJax_Tooltip *":{filter:"none",opacity:1,background:"transparent"},"@font-face":{"font-family":"MathJax_Blank",src:"url('about:blank')"}}},settings:b.config.menuSettings,Font:null,webFontDefault:"MathJax_Blank",allowWebFonts:"otf",maxStretchyParts:1000,fontName:{TeXLocal:"TeX",TeXWeb:["","TeX"],TeXImage:["",""],STIXLocal:["STIX","STIX-Web"],STIXWeb:"STIX-Web",AsanaMathWeb:"Asana-Math",GyrePagellaWeb:"Gyre-Pagella",GyreTermesWeb:"Gyre-Termes",LatinModernWeb:"Latin-Modern",NeoEulerWeb:"Neo-Euler"},fontInUse:"generic",FONTDATA:{TeX_factor:1,baselineskip:1.2,lineH:0.8,lineD:0.2,ffLineH:0.8,FONTS:{},VARIANT:{normal:{fonts:[]},"-generic-variant":{},"-largeOp":{},"-smallOp":{}},RANGES:[],DELIMITERS:{},RULECHAR:45,REMAP:{}},Config:function(){if(!this.require){this.require=[]}this.Font=f();this.SUPER(arguments).Config.call(this);var m=this.settings,l=this.config,k=m.font;if(this.adjustAvailableFonts){this.adjustAvailableFonts(l.availableFonts)}if(m.scale){l.scale=m.scale}if(k&&k!=="Auto"&&this.fontName[k]){l.availableFonts=[];delete l.fonts;if(this.fontName[k] instanceof Array){l.preferredFont=this.fontName[k][0];l.webFont=this.fontName[k][1]}else{l.preferredFont=l.webFont=this.fontName[k]}if(l.preferredFont){l.availableFonts[0]=l.preferredFont}}if(l.fonts){l.availableFonts=l.fonts;l.preferredFont=l.webFont=l.fonts[0];if(l.webFont==="STIX"){l.webFont+="-Web"}}k=this.Font.findFont(l.availableFonts,l.preferredFont);if(!k&&this.allowWebFonts){k=l.webFont;if(k){this.webFonts=true}}if(!k&&this.config.imageFont){k=l.imageFont;this.imgFonts=true}if(k){this.fontInUse=k;this.fontDir+="/"+k;this.webfontDir+="/"+k;this.require.push(this.fontDir+"/fontdata.js");if(this.imgFonts){this.require.push(this.directory+"/imageFonts.js");b.Startup.signal.Post("HTML-CSS Jax - using image fonts")}}else{e(["CantFindFontUsing","Can't find a valid font using %1","["+this.config.availableFonts.join(", ")+"]"],null,3000);b.Startup.signal.Post("HTML-CSS Jax - no valid font")}this.require.push(MathJax.OutputJax.extensionDir+"/MathEvents.js")},Startup:function(){j=MathJax.Extension.MathEvents.Event;a=MathJax.Extension.MathEvents.Touch;c=MathJax.Extension.MathEvents.Hover;this.ContextMenu=j.ContextMenu;this.Mousedown=j.AltContextMenu;this.Mouseover=c.Mouseover;this.Mouseout=c.Mouseout;this.Mousemove=c.Mousemove;this.hiddenDiv=this.Element("div",{style:{visibility:"hidden",overflow:"hidden",position:"absolute",top:0,height:"1px",width:"auto",padding:0,border:0,margin:0,textAlign:"left",textIndent:0,textTransform:"none",lineHeight:"normal",letterSpacing:"normal",wordSpacing:"normal"}});if(!document.body.firstChild){document.body.appendChild(this.hiddenDiv)}else{document.body.insertBefore(this.hiddenDiv,document.body.firstChild)}this.hiddenDiv=this.addElement(this.hiddenDiv,"div",{id:"MathJax_Hidden"});var l=this.addElement(this.hiddenDiv,"div",{style:{width:"5in"}});this.pxPerInch=l.offsetWidth/5;this.hiddenDiv.removeChild(l);this.startMarker=this.createStrut(this.Element("span"),10,true);this.endMarker=this.addText(this.Element("span"),"x").parentNode;this.HDspan=this.Element("span");if(this.operaHeightBug){this.createStrut(this.HDspan,0)}if(this.msieInlineBlockAlignBug){this.HDimg=this.addElement(this.HDspan,"img",{style:{height:"0px",width:"1px"}});try{this.HDimg.src="about:blank"}catch(k){}}else{this.HDimg=this.createStrut(this.HDspan,0)}this.EmExSpan=this.Element("span",{style:{position:"absolute","font-size-adjust":"none"}},[["span",{className:"MathJax_ExBox"}],["span",{className:"MathJax"},[["span",{className:"MathJax_EmBox"}]]]]);this.linebreakSpan=this.Element("span",null,[["hr",{style:{width:"100%",size:1,padding:0,border:0,margin:0}}]]);return h.Styles(this.config.styles,["InitializeHTML",this])},removeSTIXfonts:function(n){for(var l=0,k=n.length;l<k;l++){if(n[l]==="STIX"){n.splice(l,1);k--;l--}}if(this.config.preferredFont==="STIX"){this.config.preferredFont=n[0]}},PreloadWebFonts:function(){if(!d.allowWebFonts||!d.config.preloadWebFonts){return}for(var l=0,k=d.config.preloadWebFonts.length;l<k;l++){var n=d.FONTDATA.FONTS[d.config.preloadWebFonts[l]];if(!n.available){d.Font.testFont(n)}}},InitializeHTML:function(){this.PreloadWebFonts();this.getDefaultExEm();if(this.defaultEm){return}var k=MathJax.Callback();h.timer.start(h,function(l){if(l.time(k)){b.signal.Post(["HTML-CSS Jax - no default em size"]);return}d.getDefaultExEm();if(d.defaultEm){k()}else{setTimeout(l,l.delay)}},this.defaultEmDelay,this.defaultEmTimeout);return k},defaultEmDelay:100,defaultEmTimeout:1000,getDefaultExEm:function(){document.body.appendChild(this.EmExSpan);document.body.appendChild(this.linebreakSpan);this.defaultEx=this.EmExSpan.firstChild.offsetHeight/60;this.defaultEm=this.EmExSpan.lastChild.firstChild.offsetHeight/60;this.defaultWidth=this.linebreakSpan.firstChild.offsetWidth;document.body.removeChild(this.linebreakSpan);document.body.removeChild(this.EmExSpan)},preTranslate:function(q){var p=q.jax[this.id],B,x=p.length,w,E,u,A,s,C,l,D,k,F,t,r=false,y,o=this.config.linebreaks.automatic,v=this.config.linebreaks.width;if(o){r=(v.match(/^\s*(\d+(\.\d*)?%\s*)?container\s*$/)!=null);if(r){v=v.replace(/\s*container\s*/,"")}else{t=this.defaultWidth}if(v===""){v="100%"}}else{t=100000}for(B=0;B<x;B++){E=p[B];if(!E.parentNode){continue}u=E.previousSibling;if(u&&String(u.className).match(/^MathJax(_Display)?( MathJax_Processing)?$/)){u.parentNode.removeChild(u)}l=E.MathJax.elementJax;if(!l){continue}l.HTMLCSS={display:(l.root.Get("display")==="block")};A=s=this.Element("span",{className:"MathJax",id:l.inputID+"-Frame",isMathJax:true,jaxID:this.id,oncontextmenu:j.Menu,onmousedown:j.Mousedown,onmouseover:j.Mouseover,onmouseout:j.Mouseout,onmousemove:j.Mousemove,onclick:j.Click,ondblclick:j.DblClick});if(b.Browser.noContextMenu){A.ontouchstart=a.start;A.ontouchend=a.end}if(l.HTMLCSS.display){s=this.Element("div",{className:"MathJax_Display"});s.appendChild(A)}else{if(this.msieDisappearingBug){A.style.display="inline-block"}}s.className+=" MathJax_Processing";E.parentNode.insertBefore(s,E);E.parentNode.insertBefore(this.EmExSpan.cloneNode(true),E);s.parentNode.insertBefore(this.linebreakSpan.cloneNode(true),s)}var z=[];for(B=0;B<x;B++){E=p[B];if(!E.parentNode){continue}C=E.previousSibling;s=C.previousSibling;l=E.MathJax.elementJax;if(!l){continue}D=C.firstChild.offsetHeight/60;k=C.lastChild.firstChild.offsetHeight/60;y=s.previousSibling.firstChild.offsetWidth;if(r){t=y}if(D===0||D==="NaN"){z.push(s);l.HTMLCSS.isHidden=true;D=this.defaultEx;k=this.defaultEm;y=this.defaultWidth;if(r){t=y}}F=(this.config.matchFontHeight?D/this.TeX.x_height/k:1);F=Math.floor(Math.max(this.config.minScaleAdjust/100,F)*this.config.scale);l.HTMLCSS.scale=F/100;l.HTMLCSS.fontSize=F+"%";l.HTMLCSS.em=l.HTMLCSS.outerEm=k;this.em=k*F/100;l.HTMLCSS.ex=D;l.HTMLCSS.cwidth=y/this.em;l.HTMLCSS.lineWidth=(o?this.length2em(v,1,t/this.em):1000000)}for(B=0,w=z.length;B<w;B++){this.hiddenDiv.appendChild(z[B]);this.addElement(this.hiddenDiv,"br")}for(B=0;B<x;B++){E=p[B];if(!E.parentNode){continue}C=p[B].previousSibling;l=p[B].MathJax.elementJax;if(!l){continue}A=C.previousSibling;if(!l.HTMLCSS.isHidden){A=A.previousSibling}A.parentNode.removeChild(A);C.parentNode.removeChild(C)}q.HTMLCSSeqn=q.HTMLCSSlast=0;q.HTMLCSSi=-1;q.HTMLCSSchunk=this.config.EqnChunk;q.HTMLCSSdelay=false},PHASE:{I:1,II:2,III:3},Translate:function(l,p){if(!l.parentNode){return}if(p.HTMLCSSdelay){p.HTMLCSSdelay=false;b.RestartAfter(MathJax.Callback.Delay(this.config.EqnChunkDelay))}var k=l.MathJax.elementJax,o=k.root,m=document.getElementById(k.inputID+"-Frame"),q=(k.HTMLCSS.display?(m||{}).parentNode:m);if(!q){return}this.getMetrics(k);if(this.scale!==1){m.style.fontSize=k.HTMLCSS.fontSize}this.initImg(m);this.initHTML(o,m);this.savePreview(l);try{o.setTeXclass();k.HTMLCSS.span=m;k.HTMLCSS.div=q;o.toHTML(m,q,this.PHASE.I)}catch(n){if(n.restart){while(m.firstChild){m.removeChild(m.firstChild)}}this.restorePreview(l);throw n}this.restorePreview(l);q.className=q.className.split(/ /)[0]+" MathJax_Processed";b.signal.Post(["New Math Pending",k.inputID]);p.HTMLCSSeqn+=(p.i-p.HTMLCSSi);p.HTMLCSSi=p.i;if(p.HTMLCSSeqn>=p.HTMLCSSlast+p.HTMLCSSchunk){this.postTranslate(p,true);p.HTMLCSSchunk=Math.floor(p.HTMLCSSchunk*this.config.EqnChunkFactor);p.HTMLCSSdelay=true}return false},savePreview:function(k){var l=k.MathJax.preview;if(l){k.MathJax.tmpPreview=document.createElement("span");l.parentNode.replaceChild(k.MathJax.tmpPreview,l)}},restorePreview:function(k){var l=k.MathJax.tmpPreview;if(l){l.parentNode.replaceChild(k.MathJax.preview,l);delete k.MathJax.tmpPreview}},getMetrics:function(k){var l=k.HTMLCSS;this.em=g.mbase.prototype.em=l.em*l.scale;this.outerEm=l.em;this.scale=l.scale;this.cwidth=l.cwidth;this.linebreakWidth=l.lineWidth},postTranslate:function(l,s){var p=l.jax[this.id],t,n,q,o;for(q=l.HTMLCSSlast,o=l.HTMLCSSeqn;q<o;q++){t=p[q];if(t&&t.MathJax.elementJax){var k=t.MathJax.elementJax.HTMLCSS.div;k.className=k.className.split(/ /)[0];if(t.MathJax.preview){t.MathJax.preview.innerHTML=""}}}for(q=l.HTMLCSSlast,o=l.HTMLCSSeqn;q<o;q++){t=p[q];if(t&&t.MathJax.elementJax){n=t.MathJax.elementJax;this.getMetrics(n);n.root.toHTML(n.HTMLCSS.span,n.HTMLCSS.div,this.PHASE.II)}}for(q=l.HTMLCSSlast,o=l.HTMLCSSeqn;q<o;q++){t=p[q];if(t&&t.MathJax.elementJax){n=t.MathJax.elementJax;this.getMetrics(n);n.root.toHTML(n.HTMLCSS.span,n.HTMLCSS.div,this.PHASE.III);if(n.HTMLCSS.isHidden){t.parentNode.insertBefore(n.HTMLCSS.div,t)}delete n.HTMLCSS.span;delete n.HTMLCSS.div;t.MathJax.state=n.STATE.PROCESSED;b.signal.Post(["New Math",t.MathJax.elementJax.inputID])}}if(this.forceReflow){var r=(document.styleSheets||[])[0]||{};r.disabled=true;r.disabled=false}l.HTMLCSSlast=l.HTMLCSSeqn},getJaxFromMath:function(k){if(k.parentNode.className==="MathJax_Display"){k=k.parentNode}do{k=k.nextSibling}while(k&&k.nodeName.toLowerCase()!=="script");return b.getJaxFor(k)},getHoverSpan:function(k,l){return k.root.HTMLspanElement()},getHoverBBox:function(k,n,o){var p=n.bbox,m=k.HTMLCSS.outerEm;var l={w:p.w*m,h:p.h*m,d:p.d*m};if(p.width){l.width=p.width}return l},Zoom:function(l,w,v,k,t){w.className="MathJax";w.style.fontSize=l.HTMLCSS.fontSize;var z=w.appendChild(this.EmExSpan.cloneNode(true));var o=z.lastChild.firstChild.offsetHeight/60;this.em=g.mbase.prototype.em=o;this.outerEm=o/l.HTMLCSS.scale;z.parentNode.removeChild(z);this.scale=l.HTMLCSS.scale;this.linebreakWidth=l.HTMLCSS.lineWidth;this.cwidth=l.HTMLCSS.cwidth;this.zoomScale=parseInt(b.config.menuSettings.zscale)/100;this.idPostfix="-zoom";l.root.toHTML(w,w);this.idPostfix="";this.zoomScale=1;var x=l.root.HTMLspanElement().bbox,n=x.width;if(n){if(x.tw){k=x.tw*o}if(x.w*o<k){k=x.w*o}w.style.width=Math.floor(k-1.5*d.em)+"px";w.style.display="inline-block";var m=(l.root.id||"MathJax-Span-"+l.root.spanID)+"-zoom";var p=document.getElementById(m).firstChild;while(p&&p.style.width!==n){p=p.nextSibling}if(p){var s=p.offsetWidth;p.style.width="100%";if(s>k){w.style.width=(s+100)+"px"}}}p=w.firstChild.firstChild.style;if(x.H!=null&&x.H>x.h){p.marginTop=d.Em(x.H-Math.max(x.h,d.FONTDATA.lineH))}if(x.D!=null&&x.D>x.d){p.marginBottom=d.Em(x.D-Math.max(x.d,d.FONTDATA.lineD))}if(x.lw<0){p.paddingLeft=d.Em(-x.lw)}if(x.rw>x.w){p.marginRight=d.Em(x.rw-x.w)}w.style.position="absolute";if(!n){v.style.position="absolute"}var u=w.offsetWidth,r=w.offsetHeight,y=v.offsetHeight,q=v.offsetWidth;w.style.position=v.style.position="";return{Y:-j.getBBox(w).h,mW:q,mH:y,zW:u,zH:r}},initImg:function(k){},initHTML:function(l,k){},initFont:function(k){var m=d.FONTDATA.FONTS,l=d.config.availableFonts;if(l&&l.length&&d.Font.testFont(m[k])){m[k].available=true;if(m[k].familyFixed){m[k].family=m[k].familyFixed;delete m[k].familyFixed}return null}if(!this.allowWebFonts){return null}m[k].isWebFont=true;if(d.FontFaceBug){m[k].family=k;if(d.msieFontCSSBug){m[k].family+="-Web"}}return h.Styles({"@font-face":this.Font.fontFace(k)})},Remove:function(k){var l=document.getElementById(k.inputID+"-Frame");if(l){if(k.HTMLCSS.display){l=l.parentNode}l.parentNode.removeChild(l)}delete k.HTMLCSS},getHD:function(l,m){if(l.bbox&&this.config.noReflows&&!m){return{h:l.bbox.h,d:l.bbox.d}}var k=l.style.position;l.style.position="absolute";this.HDimg.style.height="0px";l.appendChild(this.HDspan);var n={h:l.offsetHeight};this.HDimg.style.height=n.h+"px";n.d=l.offsetHeight-n.h;n.h-=n.d;n.h/=this.em;n.d/=this.em;l.removeChild(this.HDspan);l.style.position=k;return n},getW:function(o){var l,n,m=(o.bbox||{}).w,p=o;if(o.bbox&&this.config.noReflows&&o.bbox.exactW!==false){if(!o.bbox.exactW){if(o.style.paddingLeft){m+=this.unEm(o.style.paddingLeft)*(o.scale||1)}if(o.style.paddingRight){m+=this.unEm(o.style.paddingRight)*(o.scale||1)}}return m}if(o.bbox&&o.bbox.exactW){return m}if((o.bbox&&m>=0&&!this.initialSkipBug&&!this.msieItalicWidthBug)||this.negativeBBoxes||!o.firstChild){l=o.offsetWidth;n=o.parentNode.offsetHeight}else{if(o.bbox&&m<0&&this.msieNegativeBBoxBug){l=-o.offsetWidth,n=o.parentNode.offsetHeight}else{var k=o.style.position;o.style.position="absolute";p=this.startMarker;o.insertBefore(p,o.firstChild);o.appendChild(this.endMarker);l=this.endMarker.offsetLeft-p.offsetLeft;o.removeChild(this.endMarker);o.removeChild(p);o.style.position=k}}if(n!=null){o.parentNode.HH=n/this.em}return l/this.em},Measured:function(m,l){var n=m.bbox;if(n.width==null&&n.w&&!n.isMultiline){var k=this.getW(m);n.rw+=k-n.w;n.w=k;n.exactW=true}if(!l){l=m.parentNode}if(!l.bbox){l.bbox=n}return m},Remeasured:function(l,k){k.bbox=this.Measured(l,k).bbox},MeasureSpans:function(o){var r=[],t,q,n,u,k,p,l,s;for(q=0,n=o.length;q<n;q++){t=o[q];if(!t){continue}u=t.bbox;s=this.parentNode(t);if(u.exactW||u.width||u.w===0||u.isMultiline||(this.config.noReflows&&u.exactW!==false)){if(!s.bbox){s.bbox=u}continue}if(this.negativeBBoxes||!t.firstChild||(u.w>=0&&!this.initialSkipBug)||(u.w<0&&this.msieNegativeBBoxBug)){r.push([t])}else{if(this.initialSkipBug){k=this.startMarker.cloneNode(true);p=this.endMarker.cloneNode(true);t.insertBefore(k,t.firstChild);t.appendChild(p);r.push([t,k,p,t.style.position]);t.style.position="absolute"}else{p=this.endMarker.cloneNode(true);t.appendChild(p);r.push([t,null,p])}}}for(q=0,n=r.length;q<n;q++){t=r[q][0];u=t.bbox;s=this.parentNode(t);if((u.w>=0&&!this.initialSkipBug)||this.negativeBBoxes||!t.firstChild){l=t.offsetWidth;s.HH=s.offsetHeight/this.em}else{if(u.w<0&&this.msieNegativeBBoxBug){l=-t.offsetWidth,s.HH=s.offsetHeight/this.em}else{l=r[q][2].offsetLeft-((r[q][1]||{}).offsetLeft||0)}}l/=this.em;u.rw+=l-u.w;u.w=l;u.exactW=true;if(!s.bbox){s.bbox=u}}for(q=0,n=r.length;q<n;q++){t=r[q];if(t[1]){t[1].parentNode.removeChild(t[1]),t[0].style.position=t[3]}if(t[2]){t[2].parentNode.removeChild(t[2])}}},Em:function(k){if(Math.abs(k)<0.0006){return"0em"}return k.toFixed(3).replace(/\.?0+$/,"")+"em"},EmRounded:function(k){k=(Math.round(k*d.em)+0.05)/d.em;if(Math.abs(k)<0.0006){return"0em"}return k.toFixed(3).replace(/\.?0+$/,"")+"em"},unEm:function(k){return parseFloat(k)},Px:function(k){k*=this.em;var l=(k<0?"-":"");return l+Math.abs(k).toFixed(1).replace(/\.?0+$/,"")+"px"},unPx:function(k){return parseFloat(k)/this.em},Percent:function(k){return(100*k).toFixed(1).replace(/\.?0+$/,"")+"%"},length2em:function(r,l,p){if(typeof(r)!=="string"){r=r.toString()}if(r===""){return""}if(r===g.SIZE.NORMAL){return 1}if(r===g.SIZE.BIG){return 2}if(r===g.SIZE.SMALL){return 0.71}if(r==="infinity"){return d.BIGDIMEN}var o=this.FONTDATA.TeX_factor,s=(d.zoomScale||1)/d.em;if(r.match(/mathspace$/)){return d.MATHSPACE[r]*o}var n=r.match(/^\s*([-+]?(?:\.\d+|\d+(?:\.\d*)?))?(pt|em|ex|mu|px|pc|in|mm|cm|%)?/);var k=parseFloat(n[1]||"1"),q=n[2];if(p==null){p=1}if(l==null){l=1}if(q==="em"){return k*o}if(q==="ex"){return k*d.TeX.x_height*o}if(q==="%"){return k/100*p}if(q==="px"){return k*s}if(q==="pt"){return k/10*o}if(q==="pc"){return k*1.2*o}if(q==="in"){return k*this.pxPerInch*s}if(q==="cm"){return k*this.pxPerInch*s/2.54}if(q==="mm"){return k*this.pxPerInch*s/25.4}if(q==="mu"){return k/18*o*l}return k*p},thickness2em:function(l,k){var m=d.TeX.rule_thickness;if(l===g.LINETHICKNESS.MEDIUM){return m}if(l===g.LINETHICKNESS.THIN){return 0.67*m}if(l===g.LINETHICKNESS.THICK){return 1.67*m}return this.length2em(l,k,m)},getPadding:function(l){var n={top:0,right:0,bottom:0,left:0},k=false;for(var o in n){if(n.hasOwnProperty(o)){var m=l.style["padding"+o.charAt(0).toUpperCase()+o.substr(1)];if(m){n[o]=this.length2em(m);k=true}}}return(k?n:false)},getBorders:function(p){var m={top:0,right:0,bottom:0,left:0},n={},l=false;for(var q in m){if(m.hasOwnProperty(q)){var k="border"+q.charAt(0).toUpperCase()+q.substr(1);var o=p.style[k+"Style"];if(o){l=true;m[q]=this.length2em(p.style[k+"Width"]);n[k]=[p.style[k+"Width"],p.style[k+"Style"],p.style[k+"Color"]].join(" ")}}}m.css=n;return(l?m:false)},setBorders:function(k,l){if(l){for(var m in l.css){if(l.css.hasOwnProperty(m)){k.style[m]=l.css[m]}}}},createStrut:function(m,l,n){var k=this.Element("span",{isMathJax:true,style:{display:"inline-block",overflow:"hidden",height:l+"px",width:"1px",marginRight:"-1px"}});if(n){m.insertBefore(k,m.firstChild)}else{m.appendChild(k)}return k},createBlank:function(l,k,m){var n=this.Element("span",{isMathJax:true,style:{display:"inline-block",overflow:"hidden",height:"1px",width:this.Em(k)}});if(k<0){n.style.marginRight=n.style.width;n.style.width=0}if(m){l.insertBefore(n,l.firstChild)}else{l.appendChild(n)}return n},createShift:function(l,k,n){var m=this.Element("span",{style:{marginLeft:this.Em(k)},isMathJax:true});if(n){l.insertBefore(m,l.firstChild)}else{l.appendChild(m)}return m},createSpace:function(p,n,o,q,m,s){if(n<-o){o=-n}var r=this.Em(n+o),k=this.Em(-o);if(this.msieInlineBlockAlignBug){k=this.Em(d.getHD(p.parentNode,true).d-o)}if(p.isBox||s){var l=(p.scale==null?1:p.scale);p.bbox={exactW:true,h:n*l,d:o*l,w:q*l,rw:q*l,lw:0};p.style.height=r;p.style.verticalAlign=k;p.HH=(n+o)*l}else{p=this.addElement(p,"span",{style:{height:r,verticalAlign:k},isMathJax:true})}if(q>=0){p.style.width=this.Em(q);p.style.display="inline-block";p.style.overflow="hidden"}else{if(this.msieNegativeSpaceBug){p.style.height=""}p.style.marginLeft=this.Em(q);if(d.safariNegativeSpaceBug&&p.parentNode.firstChild==p){this.createBlank(p,0,true)}}if(m&&m!==g.COLOR.TRANSPARENT){p.style.backgroundColor=m;p.style.position="relative"}return p},createRule:function(r,n,p,s,l){if(n<-p){p=-n}var m=d.TeX.min_rule_thickness,o=1;if(s>0&&s*this.em<m){s=m/this.em}if(n+p>0&&(n+p)*this.em<m){o=1/(n+p)*(m/this.em);n*=o;p*=o}if(!l){l="solid"}else{l="solid "+l}l=this.Em(s)+" "+l;var t=(o===1?this.Em(n+p):m+"px"),k=this.Em(-p);var q=this.addElement(r,"span",{style:{borderLeft:l,display:"inline-block",overflow:"hidden",width:0,height:t,verticalAlign:k},bbox:{h:n,d:p,w:s,rw:s,lw:0,exactW:true},noAdjust:true,HH:n+p,isMathJax:true});if(this.msieRuleBug&&s>0){q.style.width=this.Em(s)}if(r.isBox||r.className=="mspace"){r.bbox=q.bbox,r.HH=n+p}return q},createFrame:function(s,q,r,u,x,l){if(q<-r){r=-q}var p=2*x;if(this.msieFrameSizeBug){if(u<p){u=p}if(q+r<p){q=p-r}}if(this.msieBorderWidthBug){p=0}var v=this.Em(q+r-p),k=this.Em(-r-x),o=this.Em(u-p);var m=this.Em(x)+" "+l;var n=this.addElement(s,"span",{style:{border:m,display:"inline-block",overflow:"hidden",width:o,height:v},bbox:{h:q,d:r,w:u,rw:u,lw:0,exactW:true},noAdjust:true,HH:q+r,isMathJax:true});if(k){n.style.verticalAlign=k}return n},parentNode:function(l){var k=l.parentNode;if(k.nodeName.toLowerCase()==="a"){k=k.parentNode}return k},createStack:function(m,o,l){if(this.msiePaddingWidthBug){this.createStrut(m,0)}var n=String(l).match(/%$/);var k=(!n&&l!=null?l:0);m=this.addElement(m,"span",{noAdjust:true,HH:0,isMathJax:true,style:{display:"inline-block",position:"relative",width:(n?"100%":this.Em(k)),height:0}});if(!o){m.parentNode.bbox=m.bbox={exactW:true,h:-this.BIGDIMEN,d:-this.BIGDIMEN,w:k,lw:this.BIGDIMEN,rw:(!n&&l!=null?l:-this.BIGDIMEN)};if(n){m.bbox.width=l}}return m},createBox:function(l,k){var m=this.addElement(l,"span",{style:{position:"absolute"},isBox:true,isMathJax:true});if(k!=null){m.style.width=k}return m},addBox:function(k,l){l.style.position="absolute";l.isBox=l.isMathJax=true;return k.appendChild(l)},placeBox:function(u,s,q,o){u.isMathJax=true;var v=d.parentNode(u),C=u.bbox,z=v.bbox;if(this.msiePlaceBoxBug){this.addText(u,this.NBSP)}if(this.imgSpaceBug){this.addText(u,this.imgSpace)}var w,F=0;if(u.HH!=null){w=u.HH}else{if(C){w=Math.max(3,C.h+C.d)}else{w=u.offsetHeight/this.em}}if(!u.noAdjust){w+=1;w=Math.round(w*this.em)/this.em;if(this.msieInlineBlockAlignBug){this.addElement(u,"img",{className:"MathJax_strut",border:0,src:"about:blank",isMathJax:true,style:{width:0,height:this.Em(w)}})}else{this.addElement(u,"span",{isMathJax:true,style:{display:"inline-block",width:0,height:this.Em(w)}});if(d.chromeHeightBug){w-=(u.lastChild.offsetHeight-Math.round(w*this.em))/this.em}}}if(C){if(this.initialSkipBug){if(C.lw<0){F=C.lw;d.createBlank(u,-F,true)}if(C.rw>C.w){d.createBlank(u,C.rw-C.w+0.1)}}if(!this.msieClipRectBug&&!C.noclip&&!o){var B=3/this.em;var A=(C.H==null?C.h:C.H),m=(C.D==null?C.d:C.D);var E=w-A-B,p=w+m+B,n=-1000,k=1000;u.style.clip="rect("+this.Em(E)+" "+this.Em(k)+" "+this.Em(p)+" "+this.Em(n)+")"}}u.style.top=this.Em(-q-w);u.style.left=this.Em(s+F);if(C&&z){if(C.H!=null&&(z.H==null||C.H+q>z.H)){z.H=C.H+q}if(C.D!=null&&(z.D==null||C.D-q>z.D)){z.D=C.D-q}if(C.h+q>z.h){z.h=C.h+q}if(C.d-q>z.d){z.d=C.d-q}if(z.H!=null&&z.H<=z.h){delete z.H}if(z.D!=null&&z.D<=z.d){delete z.D}if(C.w+s>z.w){z.w=C.w+s;if(z.width==null){v.style.width=this.Em(z.w)}}if(C.rw+s>z.rw){z.rw=C.rw+s}if(C.lw+s<z.lw){z.lw=C.lw+s}if(C.width!=null&&!C.isFixed){if(z.width==null){v.style.width=z.width="100%";if(C.minWidth){v.style.minWidth=z.minWidth=C.minWidth}}u.style.width=C.width}if(C.tw){z.tw=C.tw}}},alignBox:function(s,o,q,v){if(v==null){v=0}this.placeBox(s,v,q);if(this.msiePlaceBoxBug){var m=s.lastChild;while(m&&m.nodeName!=="#text"){m=m.previousSibling}if(m){s.removeChild(m)}}var u=s.bbox;if(u.isMultiline){return}var t=u.width!=null&&!u.isFixed;var k=0,p=v-u.w/2,n="50%";if(this.initialSkipBug){k=u.w-u.rw-0.1;p+=u.lw}if(this.msieMarginScaleBug){p=(p*this.em)+"px"}else{p=this.Em(p)}if(t){p=(v===0?"":this.Em(v));n=(50-parseFloat(u.width)/2)+"%"}b.Insert(s.style,({right:{left:"",right:this.Em(k-v)},center:{left:n,marginLeft:p}})[o])},setStackWidth:function(l,k){if(typeof(k)==="number"){l.style.width=this.Em(Math.max(0,k));var m=l.bbox;if(m){m.w=k;m.exactW=true}m=l.parentNode.bbox;if(m){m.w=k;m.exactW=true}}else{l.style.width=l.parentNode.style.width="100%";if(l.bbox){l.bbox.width=k}if(l.parentNode.bbox){l.parentNode.bbox.width=k}}},createDelimiter:function(u,k,n,q,o){if(!k){u.bbox={h:0,d:0,w:this.TeX.nulldelimiterspace,lw:0};u.bbox.rw=u.bbox.w;this.createSpace(u,u.bbox.h,u.bbox.d,u.bbox.w);return}if(!q){q=1}if(!(n instanceof Array)){n=[n,n]}var t=n[1];n=n[0];var l={alias:k};while(l.alias){k=l.alias;l=this.FONTDATA.DELIMITERS[k];if(!l){l={HW:[0,this.FONTDATA.VARIANT[g.VARIANT.NORMAL]]}}}if(l.load){b.RestartAfter(h.Require(this.fontDir+"/fontdata-"+l.load+".js"))}for(var s=0,p=l.HW.length;s<p;s++){if(l.HW[s][0]*q>=n-0.01||(s==p-1&&!l.stretch)){if(l.HW[s][2]){q*=l.HW[s][2]}if(l.HW[s][3]){k=l.HW[s][3]}var r=this.addElement(u,"span");this.createChar(r,[k,l.HW[s][1]],q,o);u.bbox=r.bbox;u.offset=0.65*u.bbox.w;u.scale=q;return}}if(l.stretch){this["extendDelimiter"+l.dir](u,t,l.stretch,q,o)}},extendDelimiterV:function(A,t,E,F,w){var o=this.createStack(A,true);var v=this.createBox(o),u=this.createBox(o);this.createChar(v,(E.top||E.ext),F,w);this.createChar(u,(E.bot||E.ext),F,w);var m={bbox:{w:0,lw:0,rw:0}},D=m,p;var B=v.bbox.h+v.bbox.d+u.bbox.h+u.bbox.d;var r=-v.bbox.h;this.placeBox(v,0,r,true);r-=v.bbox.d;if(E.mid){D=this.createBox(o);this.createChar(D,E.mid,F,w);B+=D.bbox.h+D.bbox.d}if(E.min&&t<B*E.min){t=B*E.min}if(t>B){m=this.Element("span");this.createChar(m,E.ext,F,w);var C=m.bbox.h+m.bbox.d,l=C-0.05,x,q,z=(E.mid?2:1);q=x=Math.min(Math.ceil((t-B)/(z*l)),this.maxStretchyParts);if(!E.fullExtenders){l=(t-B)/(z*x)}var s=(x/(x+1))*(C-l);l=C-s;r+=s+l-m.bbox.h;while(z-->0){while(x-->0){if(!this.msieCloneNodeBug){p=m.cloneNode(true)}else{p=this.Element("span");this.createChar(p,E.ext,F,w)}p.bbox=m.bbox;r-=l;this.placeBox(this.addBox(o,p),0,r,true)}r+=s-m.bbox.d;if(E.mid&&z){this.placeBox(D,0,r-D.bbox.h,true);x=q;r+=-(D.bbox.h+D.bbox.d)+s+l-m.bbox.h}}}else{r+=(B-t)/2;if(E.mid){this.placeBox(D,0,r-D.bbox.h,true);r+=-(D.bbox.h+D.bbox.d)}r+=(B-t)/2}this.placeBox(u,0,r-u.bbox.h,true);r-=u.bbox.h+u.bbox.d;A.bbox={w:Math.max(v.bbox.w,m.bbox.w,u.bbox.w,D.bbox.w),lw:Math.min(v.bbox.lw,m.bbox.lw,u.bbox.lw,D.bbox.lw),rw:Math.max(v.bbox.rw,m.bbox.rw,u.bbox.rw,D.bbox.rw),h:0,d:-r,exactW:true};A.scale=F;A.offset=0.55*A.bbox.w;A.isMultiChar=true;this.setStackWidth(o,A.bbox.w)},extendDelimiterH:function(B,o,E,G,y){var r=this.createStack(B,true);var p=this.createBox(r),C=this.createBox(r);this.createChar(p,(E.left||E.rep),G,y);this.createChar(C,(E.right||E.rep),G,y);var l=this.Element("span");this.createChar(l,E.rep,G,y);var D={bbox:{h:-this.BIGDIMEN,d:-this.BIGDIMEN}},m;this.placeBox(p,-p.bbox.lw,0,true);var u=(p.bbox.rw-p.bbox.lw)+(C.bbox.rw-C.bbox.lw)-0.05,t=p.bbox.rw-p.bbox.lw-0.025,v;if(E.mid){D=this.createBox(r);this.createChar(D,E.mid,G,y);u+=D.bbox.w}if(E.min&&o<u*E.min){o=u*E.min}if(o>u){var F=l.bbox.rw-l.bbox.lw,q=F-0.05,z,s,A=(E.mid?2:1);s=z=Math.min(Math.ceil((o-u)/(A*q)),this.maxStretchyParts);if(!E.fillExtenders){q=(o-u)/(A*z)}v=(z/(z+1))*(F-q);q=F-v;t-=l.bbox.lw+v;while(A-->0){while(z-->0){if(!this.cloneNodeBug){m=l.cloneNode(true)}else{m=this.Element("span");this.createChar(m,E.rep,G,y)}m.bbox=l.bbox;this.placeBox(this.addBox(r,m),t,0,true);t+=q}if(E.mid&&A){this.placeBox(D,t,0,true);t+=D.bbox.w-v;z=s}}}else{t-=(u-o)/2;if(E.mid){this.placeBox(D,t,0,true);t+=D.bbox.w}t-=(u-o)/2}this.placeBox(C,t,0,true);B.bbox={w:t+C.bbox.rw,lw:0,rw:t+C.bbox.rw,H:Math.max(p.bbox.h,l.bbox.h,C.bbox.h,D.bbox.h),D:Math.max(p.bbox.d,l.bbox.d,C.bbox.d,D.bbox.d),h:l.bbox.h,d:l.bbox.d,exactW:true};B.scale=G;B.isMultiChar=true;this.setStackWidth(r,B.bbox.w)},createChar:function(s,p,n,k){s.isMathJax=true;var r=s,t="",o={fonts:[p[1]],noRemap:true};if(k&&k===g.VARIANT.BOLD){o.fonts=[p[1]+"-bold",p[1]]}if(typeof(p[1])!=="string"){o=p[1]}if(p[0] instanceof Array){for(var q=0,l=p[0].length;q<l;q++){t+=String.fromCharCode(p[0][q])}}else{t=String.fromCharCode(p[0])}if(p[4]){n*=p[4]}if(n!==1||p[3]){r=this.addElement(s,"span",{style:{fontSize:this.Percent(n)},scale:n,isMathJax:true});this.handleVariant(r,o,t);s.bbox=r.bbox}else{this.handleVariant(s,o,t)}if(p[2]){s.style.marginLeft=this.Em(p[2])}if(p[3]){s.firstChild.style.verticalAlign=this.Em(p[3]);s.bbox.h+=p[3];if(s.bbox.h<0){s.bbox.h=0}}if(p[5]){s.bbox.h+=p[5]}if(p[6]){s.bbox.d+=p[6]}if(this.AccentBug&&s.bbox.w===0){r.firstChild.nodeValue+=this.NBSP}},positionDelimiter:function(l,k){k-=l.bbox.h;l.bbox.d-=k;l.bbox.h+=k;if(k){if(this.safariVerticalAlignBug||this.konquerorVerticalAlignBug||(this.operaVerticalAlignBug&&l.isMultiChar)){if(l.firstChild.style.display===""&&l.style.top!==""){l=l.firstChild;k-=d.unEm(l.style.top)}l.style.position="relative";l.style.top=this.Em(-k)}else{l.style.verticalAlign=this.Em(k);if(d.ffVerticalAlignBug){d.createRule(l.parentNode,l.bbox.h,0,0);delete l.parentNode.bbox}}}},handleVariant:function(z,o,r){var y="",w,B,s,C,k=z,l=!!z.style.fontFamily;if(r.length===0){return}if(!z.bbox){z.bbox={w:0,h:-this.BIGDIMEN,d:-this.BIGDIMEN,rw:-this.BIGDIMEN,lw:this.BIGDIMEN}}if(!o){o=this.FONTDATA.VARIANT[g.VARIANT.NORMAL]}C=o;for(var A=0,x=r.length;A<x;A++){o=C;w=r.charCodeAt(A);B=r.charAt(A);if(w>=55296&&w<56319){A++;w=(((w-55296)<<10)+(r.charCodeAt(A)-56320))+65536;if(this.FONTDATA.RemapPlane1){var D=this.FONTDATA.RemapPlane1(w,o);w=D.n;o=D.variant}}else{var t,q,u=this.FONTDATA.RANGES;for(t=0,q=u.length;t<q;t++){if(u[t].name==="alpha"&&o.noLowerCase){continue}var p=o["offset"+u[t].offset];if(p&&w>=u[t].low&&w<=u[t].high){if(u[t].remap&&u[t].remap[w]){w=p+u[t].remap[w]}else{w=w-u[t].low+p;if(u[t].add){w+=u[t].add}}if(o["variant"+u[t].offset]){o=this.FONTDATA.VARIANT[o["variant"+u[t].offset]]}break}}}if(o.remap&&o.remap[w]){w=o.remap[w];if(o.remap.variant){o=this.FONTDATA.VARIANT[o.remap.variant]}}else{if(this.FONTDATA.REMAP[w]&&!o.noRemap){w=this.FONTDATA.REMAP[w]}}if(w instanceof Array){o=this.FONTDATA.VARIANT[w[1]];w=w[0]}if(typeof(w)==="string"){r=w+r.substr(A+1);x=r.length;A=-1;continue}s=this.lookupChar(o,w);B=s[w];if(l||(!this.checkFont(s,k.style)&&!B[5].img)){if(y.length){this.addText(k,y);y=""}var v=!!k.style.fontFamily||!!z.style.fontStyle||!!z.style.fontWeight||!s.directory||l;l=false;if(k!==z){v=!this.checkFont(s,z.style);k=z}if(v){k=this.addElement(z,"span",{isMathJax:true,subSpan:true})}this.handleFont(k,s,k!==z)}y=this.handleChar(k,s,B,w,y);if(!(B[5]||{}).space){if(B[0]/1000>z.bbox.h){z.bbox.h=B[0]/1000}if(B[1]/1000>z.bbox.d){z.bbox.d=B[1]/1000}}if(z.bbox.w+B[3]/1000<z.bbox.lw){z.bbox.lw=z.bbox.w+B[3]/1000}if(z.bbox.w+B[4]/1000>z.bbox.rw){z.bbox.rw=z.bbox.w+B[4]/1000}z.bbox.w+=B[2]/1000;if((B[5]||{}).isUnknown){z.bbox.exactW=false}}if(y.length){this.addText(k,y)}if(z.scale&&z.scale!==1){z.bbox.h*=z.scale;z.bbox.d*=z.scale;z.bbox.w*=z.scale;z.bbox.lw*=z.scale;z.bbox.rw*=z.scale}if(r.length==1&&s.skew&&s.skew[w]){z.bbox.skew=s.skew[w]}},checkFont:function(k,l){var m=(l.fontWeight||"normal");if(m.match(/^\d+$/)){m=(parseInt(m)>=600?"bold":"normal")}return(k.family.replace(/'/g,"")===l.fontFamily.replace(/'/g,"")&&(k.style||"normal")===(l.fontStyle||"normal")&&(k.weight||"normal")===m)},handleFont:function(m,k,o){m.style.fontFamily=k.family;if(!k.directory){m.style.fontSize=Math.floor(d.config.scale/d.scale+0.5)+"%"}if(!(d.FontFaceBug&&k.isWebFont)){var l=k.style||"normal",n=k.weight||"normal";if(l!=="normal"||o){m.style.fontStyle=l}if(n!=="normal"||o){m.style.fontWeight=n}}},handleChar:function(l,k,s,r,q){var p=s[5];if(p.space){if(q.length){this.addText(l,q)}d.createShift(l,s[2]/1000);return""}if(p.img){return this.handleImg(l,k,s,r,q)}if(p.isUnknown&&this.FONTDATA.DELIMITERS[r]){if(q.length){this.addText(l,q)}var o=l.scale;d.createDelimiter(l,r,0,1,k);if(this.FONTDATA.DELIMITERS[r].dir==="V"){l.style.verticalAlign=this.Em(l.bbox.d);l.bbox.h+=l.bbox.d;l.bbox.d=0}l.scale=o;s[0]=l.bbox.h*1000;s[1]=l.bbox.d*1000;s[2]=l.bbox.w*1000;s[3]=l.bbox.lw*1000;s[4]=l.bbox.rw*1000;return""}if(p.c==null){if(r<=65535){p.c=String.fromCharCode(r)}else{var m=r-65536;p.c=String.fromCharCode((m>>10)+55296)+String.fromCharCode((m&1023)+56320)}}if(p.rfix){this.addText(l,q+p.c);d.createShift(l,p.rfix/1000);return""}if(s[2]||!this.msieAccentBug||q.length){return q+p.c}d.createShift(l,s[3]/1000);d.createShift(l,(s[4]-s[3])/1000);this.addText(l,p.c);d.createShift(l,-s[4]/1000);return""},handleImg:function(l,k,p,o,m){return m},lookupChar:function(p,s){var o,k;if(!p.FONTS){var r=this.FONTDATA.FONTS;var q=(p.fonts||this.FONTDATA.VARIANT.normal.fonts);if(!(q instanceof Array)){q=[q]}if(p.fonts!=q){p.fonts=q}p.FONTS=[];for(o=0,k=q.length;o<k;o++){if(r[q[o]]){p.FONTS.push(r[q[o]]);r[q[o]].name=q[o]}}}for(o=0,k=p.FONTS.length;o<k;o++){var l=p.FONTS[o];if(typeof(l)==="string"){delete p.FONTS;this.loadFont(l)}if(l[s]){if(l[s].length===5){l[s][5]={}}if(d.allowWebFonts&&!l.available){this.loadWebFont(l)}else{return l}}else{this.findBlock(l,s)}}return this.unknownChar(p,s)},unknownChar:function(k,m){var l=(k.defaultFont||{family:d.config.undefinedFamily});if(k.bold){l.weight="bold"}if(k.italic){l.style="italic"}if(!l[m]){l[m]=[800,200,500,0,500,{isUnknown:true}]}b.signal.Post(["HTML-CSS Jax - unknown char",m,k]);return l},findBlock:function(l,q){if(l.Ranges){for(var p=0,k=l.Ranges.length;p<k;p++){if(q<l.Ranges[p][0]){return}if(q<=l.Ranges[p][1]){var o=l.Ranges[p][2];for(var n=l.Ranges.length-1;n>=0;n--){if(l.Ranges[n][2]==o){l.Ranges.splice(n,1)}}this.loadFont(l.directory+"/"+o+".js")}}}},loadFont:function(l){var k=MathJax.Callback.Queue();k.Push(["Require",h,this.fontDir+"/"+l]);if(this.imgFonts){if(!MathJax.isPacked){l=l.replace(/\/([^\/]*)$/,d.imgPacked+"/$1")}k.Push(["Require",h,this.webfontDir+"/png/"+l])}b.RestartAfter(k.Push({}))},loadWebFont:function(k){k.available=k.isWebFont=true;if(d.FontFaceBug){k.family=k.name;if(d.msieFontCSSBug){k.family+="-Web"}}b.RestartAfter(this.Font.loadWebFont(k))},loadWebFontError:function(l,k){b.Startup.signal.Post("HTML-CSS Jax - disable web fonts");l.isWebFont=false;if(this.config.imageFont&&this.config.imageFont===this.fontInUse){this.imgFonts=true;b.Startup.signal.Post("HTML-CSS Jax - switch to image fonts");b.Startup.signal.Post("HTML-CSS Jax - using image fonts");e(["WebFontNotAvailable","Web-Fonts not available -- using image fonts instead"],null,3000);h.Require(this.directory+"/imageFonts.js",k)}else{this.allowWebFonts=false;k()}},Element:MathJax.HTML.Element,addElement:MathJax.HTML.addElement,TextNode:MathJax.HTML.TextNode,addText:MathJax.HTML.addText,ucMatch:MathJax.HTML.ucMatch,BIGDIMEN:10000000,ID:0,idPostfix:"",GetID:function(){this.ID++;return this.ID},MATHSPACE:{veryverythinmathspace:1/18,verythinmathspace:2/18,thinmathspace:3/18,mediummathspace:4/18,thickmathspace:5/18,verythickmathspace:6/18,veryverythickmathspace:7/18,negativeveryverythinmathspace:-1/18,negativeverythinmathspace:-2/18,negativethinmathspace:-3/18,negativemediummathspace:-4/18,negativethickmathspace:-5/18,negativeverythickmathspace:-6/18,negativeveryverythickmathspace:-7/18},TeX:{x_height:0.430554,quad:1,num1:0.676508,num2:0.393732,num3:0.44373,denom1:0.685951,denom2:0.344841,sup1:0.412892,sup2:0.362892,sup3:0.288888,sub1:0.15,sub2:0.247217,sup_drop:0.386108,sub_drop:0.05,delim1:2.39,delim2:1,axis_height:0.25,rule_thickness:0.06,big_op_spacing1:0.111111,big_op_spacing2:0.166666,big_op_spacing3:0.2,big_op_spacing4:0.6,big_op_spacing5:0.1,scriptspace:0.1,nulldelimiterspace:0.12,delimiterfactor:901,delimitershortfall:0.3,min_rule_thickness:1.25},NBSP:"\u00A0",rfuzz:0});MathJax.Hub.Register.StartupHook("mml Jax Ready",function(){g=MathJax.ElementJax.mml;g.mbase.Augment({toHTML:function(o){o=this.HTMLcreateSpan(o);if(this.type!="mrow"){o=this.HTMLhandleSize(o)}for(var l=0,k=this.data.length;l<k;l++){if(this.data[l]){this.data[l].toHTML(o)}}var s=this.HTMLcomputeBBox(o);var n=o.bbox.h,r=o.bbox.d,p=false,q;for(l=0,k=s.length;l<k;l++){q=s[l].HTMLspanElement().bbox;if(s[l].forceStretch||q.h!==n||q.d!==r){s[l].HTMLstretchV(o,n,r);p=true}}if(p){this.HTMLcomputeBBox(o,true)}if(this.HTMLlineBreaks(o)){o=this.HTMLmultiline(o)}this.HTMLhandleSpace(o);this.HTMLhandleColor(o);if(this.data.length===1&&this.data[0]){q=this.data[0].HTMLspanElement().bbox;if(q.skew){o.bbox.skew=q.skew}}return o},HTMLlineBreaks:function(){return false},HTMLmultiline:function(){g.mbase.HTMLautoloadFile("multiline")},HTMLcomputeBBox:function(q,p,o,k){if(o==null){o=0}if(k==null){k=this.data.length}var n=q.bbox={exactW:true},r=[];while(o<k){var l=this.data[o];if(!l){continue}if(!p&&l.HTMLcanStretch("Vertical")){r.push(l);l=(l.CoreMO()||l)}this.HTMLcombineBBoxes(l,n);o++}this.HTMLcleanBBox(n);return r},HTMLcombineBBoxes:function(k,l){if(l.w==null){this.HTMLemptyBBox(l)}var n=(k.bbox?k:k.HTMLspanElement());if(!n||!n.bbox){return}var m=n.bbox;if(m.d>l.d){l.d=m.d}if(m.h>l.h){l.h=m.h}if(m.D!=null&&m.D>l.D){l.D=m.D}if(m.H!=null&&m.H>l.H){l.H=m.H}if(n.style.paddingLeft){l.w+=d.unEm(n.style.paddingLeft)*(n.scale||1)}if(l.w+m.lw<l.lw){l.lw=l.w+m.lw}if(l.w+m.rw>l.rw){l.rw=l.w+m.rw}l.w+=m.w;if(n.style.paddingRight){l.w+=d.unEm(n.style.paddingRight)*(n.scale||1)}if(m.width){l.width=m.width;l.minWidth=m.minWidth}if(m.tw){l.tw=m.tw}if(m.ic){l.ic=m.ic}else{delete l.ic}if(l.exactW&&!m.exactW){l.exactW=m.exactW}},HTMLemptyBBox:function(k){k.h=k.d=k.H=k.D=k.rw=-d.BIGDIMEN;k.w=0;k.lw=d.BIGDIMEN;return k},HTMLcleanBBox:function(k){if(k.h===this.BIGDIMEN){k.h=k.d=k.H=k.D=k.w=k.rw=k.lw=0}if(k.D<=k.d){delete k.D}if(k.H<=k.h){delete k.H}},HTMLzeroBBox:function(){return{h:0,d:0,w:0,lw:0,rw:0}},HTMLcanStretch:function(l){if(this.isEmbellished()){var k=this.Core();if(k&&k!==this){return k.HTMLcanStretch(l)}}return false},HTMLstretchH:function(l,k){return this.HTMLspanElement()},HTMLstretchV:function(l,k,m){return this.HTMLspanElement()},HTMLnotEmpty:function(k){while(k){if((k.type!=="mrow"&&k.type!=="texatom")||k.data.length>1){return true}k=k.data[0]}return false},HTMLmeasureChild:function(l,k){if(this.data[l]){d.Measured(this.data[l].toHTML(k),k)}else{k.bbox=this.HTMLzeroBBox()}},HTMLboxChild:function(l,k){if(!this.data[l]){this.SetData(l,g.mrow())}return this.data[l].toHTML(k)},HTMLcreateSpan:function(k){if(this.spanID){var l=this.HTMLspanElement();if(l&&(l.parentNode===k||(l.parentNode||{}).parentNode===k)){while(l.firstChild){l.removeChild(l.firstChild)}l.bbox=this.HTMLzeroBBox();l.scale=1;l.isMultChar=l.HH=null;l.style.cssText="";return l}}if(this.href){k=d.addElement(k,"a",{href:this.href,isMathJax:true})}k=d.addElement(k,"span",{className:this.type,isMathJax:true});if(d.imgHeightBug){k.style.display="inline-block"}if(this["class"]){k.className+=" "+this["class"]}if(!this.spanID){this.spanID=d.GetID()}k.id=(this.id||"MathJax-Span-"+this.spanID)+d.idPostfix;k.bbox=this.HTMLzeroBBox();this.styles={};if(this.style){k.style.cssText=this.style;if(k.style.fontSize){this.mathsize=k.style.fontSize;k.style.fontSize=""}this.styles={border:d.getBorders(k),padding:d.getPadding(k)};if(this.styles.border){k.style.border=""}if(this.styles.padding){k.style.padding=""}}if(this.href){k.parentNode.bbox=k.bbox}this.HTMLaddAttributes(k);return k},HTMLaddAttributes:function(n){if(this.attrNames){var s=this.attrNames,o=g.nocopyAttributes,r=b.config.ignoreMMLattributes;var p=(this.type==="mstyle"?g.math.prototype.defaults:this.defaults);for(var l=0,k=s.length;l<k;l++){var q=s[l];if(r[q]==false||(!o[q]&&!r[q]&&p[q]==null&&typeof(n[q])==="undefined")){n.setAttribute(q,this.attr[q])}}}},HTMLspanElement:function(){if(!this.spanID){return null}return document.getElementById((this.id||"MathJax-Span-"+this.spanID)+d.idPostfix)},HTMLhandleVariant:function(l,k,m){d.handleVariant(l,k,m)},HTMLhandleSize:function(k){if(!k.scale){k.scale=this.HTMLgetScale();if(k.scale!==1){k.style.fontSize=d.Percent(k.scale)}}return k},HTMLhandleDir:function(l){var k=this.Get("dir",true);if(k){l.dir=k}return l},HTMLhandleColor:function(w){var y=this.getValues("mathcolor","color");if(this.mathbackground){y.mathbackground=this.mathbackground}if(this.background){y.background=this.background}if(this.style&&w.style.backgroundColor){y.mathbackground=w.style.backgroundColor;w.style.backgroundColor="transparent"}var t=(this.styles||{}).border,v=(this.styles||{}).padding;if(y.color&&!this.mathcolor){y.mathcolor=y.color}if(y.background&&!this.mathbackground){y.mathbackground=y.background}if(y.mathcolor){w.style.color=y.mathcolor}if((y.mathbackground&&y.mathbackground!==g.COLOR.TRANSPARENT)||t||v){var A=w.bbox,z=(A.exact?0:1/d.em),u=0,s=0,m=w.style.paddingLeft,q=w.style.paddingRight;if(this.isToken){u=A.lw;s=A.rw-A.w}if(m!==""){u+=d.unEm(m)*(w.scale||1)}if(q!==""){s-=d.unEm(q)*(w.scale||1)}var l=(d.PaddingWidthBug||A.keepPadding||A.exactW?0:s-u);var o=Math.max(0,d.getW(w)+l);var x=A.h+A.d,k=-A.d,r=0,p=0;if(o>0){o+=2*z;u-=z}if(x>0){x+=2*z;k-=z}s=-o-u;if(t){s-=t.right;k-=t.bottom;r+=t.left;p+=t.right;A.h+=t.top;A.d+=t.bottom;A.w+=t.left+t.right;A.lw-=t.left;A.rw+=t.right}if(v){x+=v.top+v.bottom;o+=v.left+v.right;s-=v.right;k-=v.bottom;r+=v.left;p+=v.right;A.h+=v.top;A.d+=v.bottom;A.w+=v.left+v.right;A.lw-=v.left;A.rw+=v.right}if(p){w.style.paddingRight=d.Em(p)}var n=d.Element("span",{id:"MathJax-Color-"+this.spanID+d.idPostfix,isMathJax:true,style:{display:"inline-block",backgroundColor:y.mathbackground,width:d.Em(o),height:d.Em(x),verticalAlign:d.Em(k),marginLeft:d.Em(u),marginRight:d.Em(s)}});d.setBorders(n,t);if(A.width){n.style.width=A.width;n.style.marginRight="-"+A.width}if(d.msieInlineBlockAlignBug){n.style.position="relative";n.style.width=n.style.height=0;n.style.verticalAlign=n.style.marginLeft=n.style.marginRight="";n.style.border=n.style.padding="";if(t&&d.msieBorderWidthBug){x+=t.top+t.bottom;o+=t.left+t.right}n.style.width=d.Em(r+z);d.placeBox(d.addElement(n,"span",{noAdjust:true,isMathJax:true,style:{display:"inline-block",position:"absolute",overflow:"hidden",background:(y.mathbackground||"transparent"),width:d.Em(o),height:d.Em(x)}}),u,A.h+z);d.setBorders(n.firstChild,t)}w.parentNode.insertBefore(n,w);if(d.msieColorPositionBug){w.style.position="relative"}return n}return null},HTMLremoveColor:function(){var k=document.getElementById("MathJax-Color-"+this.spanID+d.idPostfix);if(k){k.parentNode.removeChild(k)}},HTMLhandleSpace:function(o){if(this.useMMLspacing){if(this.type!=="mo"){return}var m=this.getValues("scriptlevel","lspace","rspace");if(m.scriptlevel<=0||this.hasValue("lspace")||this.hasValue("rspace")){var l=this.HTMLgetMu(o);m.lspace=Math.max(0,d.length2em(m.lspace,l));m.rspace=Math.max(0,d.length2em(m.rspace,l));var k=this,n=this.Parent();while(n&&n.isEmbellished()&&n.Core()===k){k=n;n=n.Parent();o=k.HTMLspanElement()}if(m.lspace){o.style.paddingLeft=d.Em(m.lspace)}if(m.rspace){o.style.paddingRight=d.Em(m.rspace)}}}else{var p=this.texSpacing();if(p!==""){this.HTMLgetScale();p=d.length2em(p,this.scale)/(o.scale||1)*this.mscale;if(o.style.paddingLeft){p+=d.unEm(o.style.paddingLeft)}o.style.paddingLeft=d.Em(p)}}},HTMLgetScale:function(){if(this.scale){return this.scale*this.mscale}var m=1,k=this.getValues("scriptlevel","fontsize");k.mathsize=(this.isToken?this:this.Parent()).Get("mathsize");if(this.style){var l=this.HTMLspanElement();if(l.style.fontSize!=""){k.fontsize=l.style.fontSize}}if(k.fontsize&&!this.mathsize){k.mathsize=k.fontsize}if(k.scriptlevel!==0){if(k.scriptlevel>2){k.scriptlevel=2}m=Math.pow(this.Get("scriptsizemultiplier"),k.scriptlevel);k.scriptminsize=d.length2em(this.Get("scriptminsize"));if(m<k.scriptminsize){m=k.scriptminsize}}this.scale=m;this.mscale=d.length2em(k.mathsize);return m*this.mscale},HTMLgetMu:function(m){var k=1,l=this.getValues("scriptlevel","scriptsizemultiplier");if(m.scale&&m.scale!==1){k=1/m.scale}if(l.scriptlevel!==0){if(l.scriptlevel>2){l.scriptlevel=2}k=Math.sqrt(Math.pow(l.scriptsizemultiplier,l.scriptlevel))}return k},HTMLgetVariant:function(){var k=this.getValues("mathvariant","fontfamily","fontweight","fontstyle");k.hasVariant=this.Get("mathvariant",true);if(!k.hasVariant){k.family=k.fontfamily;k.weight=k.fontweight;k.style=k.fontstyle}if(this.style){var m=this.HTMLspanElement();if(!k.family&&m.style.fontFamily){k.family=m.style.fontFamily}if(!k.weight&&m.style.fontWeight){k.weight=m.style.fontWeight}if(!k.style&&m.style.fontStyle){k.style=m.style.fontStyle}}if(k.weight&&k.weight.match(/^\d+$/)){k.weight=(parseInt(k.weight)>600?"bold":"normal")}var l=k.mathvariant;if(this.variantForm){l="-"+d.fontInUse+"-variant"}if(k.family&&!k.hasVariant){if(!k.weight&&k.mathvariant.match(/bold/)){k.weight="bold"}if(!k.style&&k.mathvariant.match(/italic/)){k.style="italic"}return{FONTS:[],fonts:[],noRemap:true,defaultFont:{family:k.family,style:k.style,weight:k.weight}}}if(k.weight==="bold"){l={normal:g.VARIANT.BOLD,italic:g.VARIANT.BOLDITALIC,fraktur:g.VARIANT.BOLDFRAKTUR,script:g.VARIANT.BOLDSCRIPT,"sans-serif":g.VARIANT.BOLDSANSSERIF,"sans-serif-italic":g.VARIANT.SANSSERIFBOLDITALIC}[l]||l}else{if(k.weight==="normal"){l={bold:g.VARIANT.normal,"bold-italic":g.VARIANT.ITALIC,"bold-fraktur":g.VARIANT.FRAKTUR,"bold-script":g.VARIANT.SCRIPT,"bold-sans-serif":g.VARIANT.SANSSERIF,"sans-serif-bold-italic":g.VARIANT.SANSSERIFITALIC}[l]||l}}if(k.style==="italic"){l={normal:g.VARIANT.ITALIC,bold:g.VARIANT.BOLDITALIC,"sans-serif":g.VARIANT.SANSSERIFITALIC,"bold-sans-serif":g.VARIANT.SANSSERIFBOLDITALIC}[l]||l}else{if(k.style==="normal"){l={italic:g.VARIANT.NORMAL,"bold-italic":g.VARIANT.BOLD,"sans-serif-italic":g.VARIANT.SANSSERIF,"sans-serif-bold-italic":g.VARIANT.BOLDSANSSERIF}[l]||l}}if(!(l in d.FONTDATA.VARIANT)){l="normal"}return d.FONTDATA.VARIANT[l]}},{HTMLautoload:function(){var k=d.autoloadDir+"/"+this.type+".js";b.RestartAfter(h.Require(k))},HTMLautoloadFile:function(k){var l=d.autoloadDir+"/"+k+".js";b.RestartAfter(h.Require(l))},HTMLstretchH:function(l,k){this.HTMLremoveColor();return this.toHTML(l,k)},HTMLstretchV:function(l,k,m){this.HTMLremoveColor();return this.toHTML(l,k,m)}});g.chars.Augment({toHTML:function(n,m,l,o){var r=this.data.join("").replace(/[\u2061-\u2064]/g,"");if(l){r=l(r,o)}if(m.fontInherit){var q=Math.floor(d.config.scale/d.scale+0.5)+"%";d.addElement(n,"span",{style:{"font-size":q}},[r]);if(m.bold){n.lastChild.style.fontWeight="bold"}if(m.italic){n.lastChild.style.fontStyle="italic"}n.bbox=null;var p=d.getHD(n),k=d.getW(n);n.bbox={h:p.h,d:p.d,w:k,lw:0,rw:k,exactW:true}}else{this.HTMLhandleVariant(n,m,r)}}});g.entity.Augment({toHTML:function(n,m,l,o){var r=this.toString().replace(/[\u2061-\u2064]/g,"");if(l){r=l(r,o)}if(m.fontInherit){var q=Math.floor(d.config.scale/d.scale+0.5)+"%";d.addElement(n,"span",{style:{"font-size":q}},[r]);if(m.bold){n.lastChild.style.fontWeight="bold"}if(m.italic){n.lastChild.style.fontStyle="italic"}delete n.bbox;var p=d.getHD(n),k=d.getW(n);n.bbox={h:p.h,d:p.d,w:k,lw:0,rw:k,exactW:true}}else{this.HTMLhandleVariant(n,m,r)}}});g.mi.Augment({toHTML:function(o){o=this.HTMLhandleSize(this.HTMLcreateSpan(o));o.bbox=null;var n=this.HTMLgetVariant();for(var l=0,k=this.data.length;l<k;l++){if(this.data[l]){this.data[l].toHTML(o,n)}}if(!o.bbox){o.bbox=this.HTMLzeroBBox()}var q=this.data.join(""),p=o.bbox;if(p.skew&&q.length!==1){delete p.skew}if(p.rw>p.w&&q.length===1&&!n.noIC){p.ic=p.rw-p.w;d.createBlank(o,p.ic/this.mscale);p.w=p.rw}this.HTMLhandleSpace(o);this.HTMLhandleColor(o);this.HTMLhandleDir(o);return o}});g.mn.Augment({toHTML:function(o){o=this.HTMLhandleSize(this.HTMLcreateSpan(o));o.bbox=null;var n=this.HTMLgetVariant();for(var l=0,k=this.data.length;l<k;l++){if(this.data[l]){this.data[l].toHTML(o,n)}}if(!o.bbox){o.bbox=this.HTMLzeroBBox()}if(this.data.join("").length!==1){delete o.bbox.skew}this.HTMLhandleSpace(o);this.HTMLhandleColor(o);this.HTMLhandleDir(o);return o}});g.mo.Augment({toHTML:function(v){v=this.HTMLhandleSize(this.HTMLcreateSpan(v));if(this.data.length==0){return v}else{v.bbox=null}var y=this.data.join("");var q=this.HTMLgetVariant();var x=this.getValues("largeop","displaystyle");if(x.largeop){q=d.FONTDATA.VARIANT[x.displaystyle?"-largeOp":"-smallOp"]}var w=this.CoreParent(),o=(w&&w.isa(g.msubsup)&&this!==w.data[w.base]),l=(o?this.remapChars:null);if(y.length===1&&w&&w.isa(g.munderover)&&this.CoreText(w.data[w.base]).length===1){var s=w.data[w.over],u=w.data[w.under];if(s&&this===s.CoreMO()&&w.Get("accent")){l=d.FONTDATA.REMAPACCENT}else{if(u&&this===u.CoreMO()&&w.Get("accentunder")){l=d.FONTDATA.REMAPACCENTUNDER}}}if(o&&y.match(/['`"\u00B4\u2032-\u2037\u2057]/)){q=d.FONTDATA.VARIANT["-"+d.fontInUse+"-variant"]}for(var r=0,n=this.data.length;r<n;r++){if(this.data[r]){this.data[r].toHTML(v,q,this.remap,l)}}if(!v.bbox){v.bbox=this.HTMLzeroBBox()}if(y.length!==1){delete v.bbox.skew}if(d.AccentBug&&v.bbox.w===0&&y.length===1&&v.firstChild){v.firstChild.nodeValue+=d.NBSP;d.createSpace(v,0,0,-v.offsetWidth/d.em)}if(x.largeop){var t=d.TeX.axis_height*this.scale*this.mscale;var k=(v.bbox.h-v.bbox.d)/2-t;if(d.safariVerticalAlignBug&&v.lastChild.nodeName==="IMG"){v.lastChild.style.verticalAlign=d.Em(d.unEm(v.lastChild.style.verticalAlign||0)/d.em-k/v.scale)}else{if(d.konquerorVerticalAlignBug&&v.lastChild.nodeName==="IMG"){v.style.position="relative";v.lastChild.style.position="relative";v.lastChild.style.top=d.Em(k/v.scale)}else{v.style.verticalAlign=d.Em(-k/v.scale)}}v.bbox.h-=k;v.bbox.d+=k;if(v.bbox.rw>v.bbox.w){v.bbox.ic=v.bbox.rw-v.bbox.w;d.createBlank(v,v.bbox.ic/this.mscale);v.bbox.w=v.bbox.rw}}this.HTMLhandleSpace(v);this.HTMLhandleColor(v);this.HTMLhandleDir(v);return v},HTMLcanStretch:function(o){if(!this.Get("stretchy")){return false}var p=this.data.join("");if(p.length>1){return false}var m=this.CoreParent();if(m&&m.isa(g.munderover)&&this.CoreText(m.data[m.base]).length===1){var n=m.data[m.over],l=m.data[m.under];if(n&&this===n.CoreMO()&&m.Get("accent")){p=d.FONTDATA.REMAPACCENT[p]||p}else{if(l&&this===l.CoreMO()&&m.Get("accentunder")){p=d.FONTDATA.REMAPACCENTUNDER[p]||p}}}p=d.FONTDATA.DELIMITERS[p.charCodeAt(0)];var k=(p&&p.dir===o.substr(0,1));this.forceStretch=(k&&(this.Get("minsize",true)||this.Get("maxsize",true)));return k},HTMLstretchV:function(m,n,o){this.HTMLremoveColor();var r=this.getValues("symmetric","maxsize","minsize");var p=this.HTMLspanElement(),s=this.HTMLgetMu(p),q;var l=this.HTMLgetScale(),k=d.TeX.axis_height*l;if(r.symmetric){q=2*Math.max(n-k,o+k)}else{q=n+o}r.maxsize=d.length2em(r.maxsize,s,p.bbox.h+p.bbox.d);r.minsize=d.length2em(r.minsize,s,p.bbox.h+p.bbox.d);q=Math.max(r.minsize,Math.min(r.maxsize,q));if(q!=r.minsize){q=[Math.max(q*d.TeX.delimiterfactor/1000,q-d.TeX.delimitershortfall),q]}p=this.HTMLcreateSpan(m);d.createDelimiter(p,this.data.join("").charCodeAt(0),q,l);if(r.symmetric){q=(p.bbox.h+p.bbox.d)/2+k}else{q=(p.bbox.h+p.bbox.d)*n/(n+o)}d.positionDelimiter(p,q);this.HTMLhandleSpace(p);this.HTMLhandleColor(p);return p},HTMLstretchH:function(o,k){this.HTMLremoveColor();var m=this.getValues("maxsize","minsize","mathvariant","fontweight");if((m.fontweight==="bold"||parseInt(m.fontweight)>=600)&&!this.Get("mathvariant",true)){m.mathvariant=g.VARIANT.BOLD}var n=this.HTMLspanElement(),l=this.HTMLgetMu(n),p=n.scale;m.maxsize=d.length2em(m.maxsize,l,n.bbox.w);m.minsize=d.length2em(m.minsize,l,n.bbox.w);k=Math.max(m.minsize,Math.min(m.maxsize,k));n=this.HTMLcreateSpan(o);d.createDelimiter(n,this.data.join("").charCodeAt(0),k,p,m.mathvariant);this.HTMLhandleSpace(n);this.HTMLhandleColor(n);return n}});g.mtext.Augment({toHTML:function(o){o=this.HTMLhandleSize(this.HTMLcreateSpan(o));var n=this.HTMLgetVariant();if(d.config.mtextFontInherit||this.Parent().type==="merror"){var p=this.Get("mathvariant");if(p==="monospace"){o.className+=" MJX-monospace"}else{if(p.match(/sans-serif/)){o.className+=" MJX-sans-serif"}}n={bold:n.bold,italic:n.italic,fontInherit:true}}for(var l=0,k=this.data.length;l<k;l++){if(this.data[l]){this.data[l].toHTML(o,n)}}if(!o.bbox){o.bbox=this.HTMLzeroBBox()}if(this.data.join("").length!==1){delete o.bbox.skew}this.HTMLhandleSpace(o);this.HTMLhandleColor(o);this.HTMLhandleDir(o);return o}});g.merror.Augment({toHTML:function(l){var n=MathJax.HTML.addElement(l,"span",{style:{display:"inline-block"}});l=this.SUPER(arguments).toHTML.call(this,n);var m=d.getHD(n),k=d.getW(n);n.bbox={h:m.h,d:m.d,w:k,lw:0,rw:k,exactW:true};n.id=l.id;l.id=null;return n}});g.ms.Augment({toHTML:g.mbase.HTMLautoload});g.mglyph.Augment({toHTML:g.mbase.HTMLautoload});g.mspace.Augment({toHTML:function(o){o=this.HTMLcreateSpan(o);var m=this.getValues("height","depth","width");var l=this.HTMLgetMu(o);this.HTMLgetScale();m.mathbackground=this.mathbackground;if(this.background&&!this.mathbackground){m.mathbackground=this.background}var n=d.length2em(m.height,l)*this.mscale,p=d.length2em(m.depth,l)*this.mscale,k=d.length2em(m.width,l)*this.mscale;d.createSpace(o,n,p,k,m.mathbackground,true);return o}});g.mphantom.Augment({toHTML:function(o,l,q){o=this.HTMLcreateSpan(o);if(this.data[0]!=null){var p=this.data[0].toHTML(o);if(q!=null){d.Remeasured(this.data[0].HTMLstretchV(o,l,q),o)}else{if(l!=null){d.Remeasured(this.data[0].HTMLstretchH(o,l),o)}else{p=d.Measured(p,o)}}o.bbox={w:p.bbox.w,h:p.bbox.h,d:p.bbox.d,lw:0,rw:0,exactW:true};for(var n=0,k=o.childNodes.length;n<k;n++){o.childNodes[n].style.visibility="hidden"}}this.HTMLhandleSpace(o);this.HTMLhandleColor(o);return o},HTMLstretchH:g.mbase.HTMLstretchH,HTMLstretchV:g.mbase.HTMLstretchV});g.mpadded.Augment({toHTML:function(s,m,k){s=this.HTMLcreateSpan(s);if(this.data[0]!=null){var q=d.createStack(s,true);var n=d.createBox(q);var l=this.data[0].toHTML(n);if(k!=null){d.Remeasured(this.data[0].HTMLstretchV(n,m,k),n)}else{if(m!=null){d.Remeasured(this.data[0].HTMLstretchH(n,m),n)}else{d.Measured(l,n)}}var t=this.getValues("height","depth","width","lspace","voffset"),r=0,p=0,u=this.HTMLgetMu(s);this.HTMLgetScale();if(t.lspace){r=this.HTMLlength2em(n,t.lspace,u)}if(t.voffset){p=this.HTMLlength2em(n,t.voffset,u)}d.placeBox(n,r,p);r/=this.mscale;p/=this.mscale;s.bbox={h:n.bbox.h,d:n.bbox.d,w:n.bbox.w,exactW:true,lw:n.bbox.lw+r,rw:n.bbox.rw+r,H:Math.max((n.bbox.H==null?-d.BIGDIMEN:n.bbox.H+p),n.bbox.h+p),D:Math.max((n.bbox.D==null?-d.BIGDIMEN:n.bbox.D-p),n.bbox.d-p)};if(t.height!==""){s.bbox.h=this.HTMLlength2em(n,t.height,u,"h",0)}if(t.depth!==""){s.bbox.d=this.HTMLlength2em(n,t.depth,u,"d",0)}if(t.width!==""){s.bbox.w=this.HTMLlength2em(n,t.width,u,"w",0)}if(s.bbox.H<=s.bbox.h){delete s.bbox.H}if(s.bbox.D<=s.bbox.d){delete s.bbox.D}var o=/^\s*(\d+(\.\d*)?|\.\d+)\s*(pt|em|ex|mu|px|pc|in|mm|cm)\s*$/;s.bbox.exact=!!((this.data[0]&&this.data[0].data.length==0)||o.exec(t.height)||o.exec(t.width)||o.exec(t.depth));d.setStackWidth(q,s.bbox.w)}this.HTMLhandleSpace(s);this.HTMLhandleColor(s);return s},HTMLlength2em:function(q,r,l,s,k){if(k==null){k=-d.BIGDIMEN}var o=String(r).match(/width|height|depth/);var p=(o?q.bbox[o[0].charAt(0)]:(s?q.bbox[s]:0));var n=d.length2em(r,l,p/this.mscale)*this.mscale;if(s&&String(r).match(/^\s*[-+]/)){return Math.max(k,q.bbox[s]+n)}else{return n}},HTMLstretchH:g.mbase.HTMLstretchH,HTMLstretchV:g.mbase.HTMLstretchV});g.mrow.Augment({HTMLlineBreaks:function(k){if(!this.parent.linebreakContainer){return false}return(d.config.linebreaks.automatic&&k.bbox.w>d.linebreakWidth)||this.hasNewline()},HTMLstretchH:function(m,k){this.HTMLremoveColor();var l=this.HTMLspanElement();this.data[this.core].HTMLstretchH(l,k);this.HTMLcomputeBBox(l,true);this.HTMLhandleColor(l);return l},HTMLstretchV:function(m,l,n){this.HTMLremoveColor();var k=this.HTMLspanElement();this.data[this.core].HTMLstretchV(k,l,n);this.HTMLcomputeBBox(k,true);this.HTMLhandleColor(k);return k}});g.mstyle.Augment({toHTML:function(l,k,m){l=this.HTMLcreateSpan(l);if(this.data[0]!=null){var n=this.data[0].toHTML(l);if(m!=null){this.data[0].HTMLstretchV(l,k,m)}else{if(k!=null){this.data[0].HTMLstretchH(l,k)}}l.bbox=n.bbox}this.HTMLhandleSpace(l);this.HTMLhandleColor(l);return l},HTMLstretchH:g.mbase.HTMLstretchH,HTMLstretchV:g.mbase.HTMLstretchV});g.mfrac.Augment({toHTML:function(D){D=this.HTMLcreateSpan(D);var m=d.createStack(D);var r=d.createBox(m),o=d.createBox(m);d.MeasureSpans([this.HTMLboxChild(0,r),this.HTMLboxChild(1,o)]);var k=this.getValues("displaystyle","linethickness","numalign","denomalign","bevelled");var I=this.HTMLgetScale(),C=k.displaystyle;var G=d.TeX.axis_height*I;if(k.bevelled){var F=(C?0.4:0.15);var s=Math.max(r.bbox.h+r.bbox.d,o.bbox.h+o.bbox.d)+2*F;var E=d.createBox(m);d.createDelimiter(E,47,s);d.placeBox(r,0,(r.bbox.d-r.bbox.h)/2+G+F);d.placeBox(E,r.bbox.w-F/2,(E.bbox.d-E.bbox.h)/2+G);d.placeBox(o,r.bbox.w+E.bbox.w-F,(o.bbox.d-o.bbox.h)/2+G-F)}else{var l=Math.max(r.bbox.w,o.bbox.w);var y=d.thickness2em(k.linethickness,this.scale)*this.mscale,A,z,x,w;var B=d.TeX.min_rule_thickness/this.em;if(C){x=d.TeX.num1;w=d.TeX.denom1}else{x=(y===0?d.TeX.num3:d.TeX.num2);w=d.TeX.denom2}x*=I;w*=I;if(y===0){A=Math.max((C?7:3)*d.TeX.rule_thickness,2*B);z=(x-r.bbox.d)-(o.bbox.h-w);if(z<A){x+=(A-z)/2;w+=(A-z)/2}}else{A=Math.max((C?2:0)*B+y,y/2+1.5*B);z=(x-r.bbox.d)-(G+y/2);if(z<A){x+=A-z}z=(G-y/2)-(o.bbox.h-w);if(z<A){w+=A-z}var n=d.createBox(m);d.createRule(n,y,0,l+2*y);d.placeBox(n,0,G-y/2)}d.alignBox(r,k.numalign,x);d.alignBox(o,k.denomalign,-w)}this.HTMLhandleSpace(D);this.HTMLhandleColor(D);return D},HTMLcanStretch:function(k){return false},HTMLhandleSpace:function(l){if(!this.texWithDelims&&!this.useMMLspacing){var m=d.TeX.nulldelimiterspace*this.mscale;var k=l.childNodes[d.msiePaddingWidthBug?1:0].style;k.marginLeft=k.marginRight=d.Em(m);l.bbox.w+=2*m;l.bbox.r+=2*m}this.SUPER(arguments).HTMLhandleSpace.call(this,l)}});g.msqrt.Augment({toHTML:function(w){w=this.HTMLcreateSpan(w);var z=d.createStack(w);var n=d.createBox(z),u=d.createBox(z),s=d.createBox(z);var r=this.HTMLgetScale();var A=d.TeX.rule_thickness*r,m,l,y,o;if(this.Get("displaystyle")){m=d.TeX.x_height*r}else{m=A}l=Math.max(A+m/4,1.5*d.TeX.min_rule_thickness/this.em);var k=this.HTMLboxChild(0,n);y=k.bbox.h+k.bbox.d+l+A;d.createDelimiter(s,8730,y,r);d.MeasureSpans([k,s]);o=k.bbox.w;var v=0;if(s.isMultiChar||(d.AdjustSurd&&d.imgFonts)){s.bbox.w*=0.95}if(s.bbox.h+s.bbox.d>y){l=((s.bbox.h+s.bbox.d)-(y-A))/2}var B=d.FONTDATA.DELIMITERS[d.FONTDATA.RULECHAR];if(!B||o<B.HW[0][0]*r||r<0.75){d.createRule(u,0,A,o)}else{d.createDelimiter(u,d.FONTDATA.RULECHAR,o,r)}y=k.bbox.h+l+A;l=y*d.rfuzz;if(s.isMultiChar){l=d.rfuzz}v=this.HTMLaddRoot(z,s,v,s.bbox.h+s.bbox.d-y,r);d.placeBox(s,v,y-s.bbox.h);d.placeBox(u,v+s.bbox.w,y-u.bbox.h+l);d.placeBox(n,v+s.bbox.w,0);this.HTMLhandleSpace(w);this.HTMLhandleColor(w);return w},HTMLaddRoot:function(m,l,k,o,n){return k}});g.mroot.Augment({toHTML:g.msqrt.prototype.toHTML,HTMLaddRoot:function(s,l,q,o,k){var m=d.createBox(s);if(this.data[1]){var p=this.data[1].toHTML(m);p.style.paddingRight=p.style.paddingLeft="";d.Measured(p,m)}else{m.bbox=this.HTMLzeroBBox()}var n=this.HTMLrootHeight(l.bbox.h+l.bbox.d,k,m)-o;var r=Math.min(m.bbox.w,m.bbox.rw);q=Math.max(r,l.offset);d.placeBox(m,q-r,n);return q-l.offset},HTMLrootHeight:function(m,l,k){return 0.45*(m-0.9*l)+0.6*l+Math.max(0,k.bbox.d-0.075)}});g.mfenced.Augment({toHTML:function(o){o=this.HTMLcreateSpan(o);if(this.data.open){this.data.open.toHTML(o)}if(this.data[0]!=null){this.data[0].toHTML(o)}for(var l=1,k=this.data.length;l<k;l++){if(this.data[l]){if(this.data["sep"+l]){this.data["sep"+l].toHTML(o)}this.data[l].toHTML(o)}}if(this.data.close){this.data.close.toHTML(o)}var q=this.HTMLcomputeBBox(o);var n=o.bbox.h,p=o.bbox.d;for(l=0,k=q.length;l<k;l++){q[l].HTMLstretchV(o,n,p)}if(q.length){this.HTMLcomputeBBox(o,true)}this.HTMLhandleSpace(o);this.HTMLhandleColor(o);return o},HTMLcomputeBBox:function(p,o){var l=p.bbox={},q=[];this.HTMLcheckStretchy(this.data.open,l,q,o);this.HTMLcheckStretchy(this.data[0],l,q,o);for(var n=1,k=this.data.length;n<k;n++){if(this.data[n]){this.HTMLcheckStretchy(this.data["sep"+n],l,q,o);this.HTMLcheckStretchy(this.data[n],l,q,o)}}this.HTMLcheckStretchy(this.data.close,l,q,o);this.HTMLcleanBBox(l);return q},HTMLcheckStretchy:function(k,l,n,m){if(k){if(!m&&k.HTMLcanStretch("Vertical")){n.push(k);k=(k.CoreMO()||k)}this.HTMLcombineBBoxes(k,l)}}});g.menclose.Augment({toHTML:g.mbase.HTMLautoload});g.maction.Augment({toHTML:g.mbase.HTMLautoload});g.semantics.Augment({toHTML:function(l,k,m){l=this.HTMLcreateSpan(l);if(this.data[0]!=null){var n=this.data[0].toHTML(l);if(m!=null){this.data[0].HTMLstretchV(l,k,m)}else{if(k!=null){this.data[0].HTMLstretchH(l,k)}}l.bbox=n.bbox}this.HTMLhandleSpace(l);return l},HTMLstretchH:g.mbase.HTMLstretchH,HTMLstretchV:g.mbase.HTMLstretchV});g.munderover.Augment({toHTML:function(L,H,F){var l=this.getValues("displaystyle","accent","accentunder","align");if(!l.displaystyle&&this.data[this.base]!=null&&this.data[this.base].CoreMO().Get("movablelimits")){return g.msubsup.prototype.toHTML.call(this,L)}L=this.HTMLcreateSpan(L);var P=this.HTMLgetScale();var q=d.createStack(L);var r=[],o=[],N=[],w,M,I;for(M=0,I=this.data.length;M<I;M++){if(this.data[M]!=null){w=r[M]=d.createBox(q);o[M]=this.data[M].toHTML(w);if(M==this.base){if(F!=null){this.data[this.base].HTMLstretchV(w,H,F)}else{if(H!=null){this.data[this.base].HTMLstretchH(w,H)}}N[M]=(F==null&&H!=null?false:this.data[M].HTMLcanStretch("Horizontal"))}else{N[M]=this.data[M].HTMLcanStretch("Horizontal");o[M].style.paddingLeft=o[M].style.paddingRight=""}}}d.MeasureSpans(o);var n=-d.BIGDIMEN,K=n;for(M=0,I=this.data.length;M<I;M++){if(this.data[M]){if(r[M].bbox.w>K){K=r[M].bbox.w}if(!N[M]&&K>n){n=K}}}if(F==null&&H!=null){n=H}else{if(n==-d.BIGDIMEN){n=K}}for(M=K=0,I=this.data.length;M<I;M++){if(this.data[M]){w=r[M];if(N[M]){w.bbox=this.data[M].HTMLstretchH(w,n).bbox;if(M!==this.base){o[M].style.paddingLeft=o[M].style.paddingRight=""}}if(w.bbox.w>K){K=w.bbox.w}}}var E=d.TeX.rule_thickness*this.mscale,G=d.FONTDATA.TeX_factor;var p=r[this.base]||{bbox:this.HTMLzeroBBox()};var v,s,A,z,u,C,J,O=0;if(p.bbox.ic){O=1.3*p.bbox.ic+0.05}for(M=0,I=this.data.length;M<I;M++){if(this.data[M]!=null){w=r[M];u=d.TeX.big_op_spacing5*P;var B=(M!=this.base&&l[this.ACCENTS[M]]);if(B&&w.bbox.w<=1/d.em+0.0001){w.bbox.w=w.bbox.rw-w.bbox.lw;w.bbox.noclip=true;if(w.bbox.lw){w.insertBefore(d.createSpace(w.parentNode,0,0,-w.bbox.lw),w.firstChild)}d.createBlank(w,0,0,w.bbox.rw+0.1)}C={left:0,center:(K-w.bbox.w)/2,right:K-w.bbox.w}[l.align];v=C;s=0;if(M==this.over){if(B){J=Math.max(E*P*G,2.5/this.em);u=0;if(p.bbox.skew){v+=p.bbox.skew;L.bbox.skew=p.bbox.skew;if(v+w.bbox.w>K){L.bbox.skew+=(K-w.bbox.w-v)/2}}}else{A=d.TeX.big_op_spacing1*P*G;z=d.TeX.big_op_spacing3*P*G;J=Math.max(A,z-Math.max(0,w.bbox.d))}J=Math.max(J,1.5/this.em);v+=O/2;s=p.bbox.h+w.bbox.d+J;w.bbox.h+=u}else{if(M==this.under){if(B){J=3*E*P*G;u=0}else{A=d.TeX.big_op_spacing2*P*G;z=d.TeX.big_op_spacing4*P*G;J=Math.max(A,z-w.bbox.h)}J=Math.max(J,1.5/this.em);v-=O/2;s=-(p.bbox.d+w.bbox.h+J);w.bbox.d+=u}}d.placeBox(w,v,s)}}this.HTMLhandleSpace(L);this.HTMLhandleColor(L);return L},HTMLstretchH:g.mbase.HTMLstretchH,HTMLstretchV:g.mbase.HTMLstretchV});g.msubsup.Augment({toHTML:function(K,I,C){K=this.HTMLcreateSpan(K);var N=this.HTMLgetScale(),H=this.HTMLgetMu(K);var w=d.createStack(K),l,n=[];var o=d.createBox(w);if(this.data[this.base]){n.push(this.data[this.base].toHTML(o));if(C!=null){this.data[this.base].HTMLstretchV(o,I,C)}else{if(I!=null){this.data[this.base].HTMLstretchH(o,I)}}}else{o.bbox=this.HTMLzeroBBox()}var L=d.TeX.x_height*N,B=d.TeX.scriptspace*N*0.75;var k,x;if(this.HTMLnotEmpty(this.data[this.sup])){k=d.createBox(w);n.push(this.data[this.sup].toHTML(k))}if(this.HTMLnotEmpty(this.data[this.sub])){x=d.createBox(w);n.push(this.data[this.sub].toHTML(x))}d.MeasureSpans(n);if(k){k.bbox.w+=B;k.bbox.rw=Math.max(k.bbox.w,k.bbox.rw)}if(x){x.bbox.w+=B;x.bbox.rw=Math.max(x.bbox.w,x.bbox.rw)}d.placeBox(o,0,0);var m=N;if(k){m=this.data[this.sup].HTMLgetScale()}else{if(x){m=this.data[this.sub].HTMLgetScale()}}var F=d.TeX.sup_drop*m,E=d.TeX.sub_drop*m;var z=o.bbox.h-F,y=o.bbox.d+E,M=0,G;if(o.bbox.ic){o.bbox.w-=o.bbox.ic;M=1.3*o.bbox.ic+0.05}if(this.data[this.base]&&I==null&&C==null&&(this.data[this.base].type==="mi"||this.data[this.base].type==="mo")){if(this.data[this.base].data.join("").length===1&&n[0].scale===1&&!this.data[this.base].Get("largeop")){z=y=0}}var J=this.getValues("subscriptshift","superscriptshift");J.subscriptshift=(J.subscriptshift===""?0:d.length2em(J.subscriptshift,H));J.superscriptshift=(J.superscriptshift===""?0:d.length2em(J.superscriptshift,H));if(!k){if(x){y=Math.max(y,d.TeX.sub1*N,x.bbox.h-(4/5)*L,J.subscriptshift);d.placeBox(x,o.bbox.w,-y,x.bbox)}}else{if(!x){l=this.getValues("displaystyle","texprimestyle");G=d.TeX[(l.displaystyle?"sup1":(l.texprimestyle?"sup3":"sup2"))];z=Math.max(z,G*N,k.bbox.d+(1/4)*L,J.superscriptshift);d.placeBox(k,o.bbox.w+M,z,k.bbox)}else{y=Math.max(y,d.TeX.sub2*N);var A=d.TeX.rule_thickness*N;if((z-k.bbox.d)-(x.bbox.h-y)<3*A){y=3*A-z+k.bbox.d+x.bbox.h;F=(4/5)*L-(z-k.bbox.d);if(F>0){z+=F;y-=F}}d.placeBox(k,o.bbox.w+M,Math.max(z,J.superscriptshift));d.placeBox(x,o.bbox.w,-Math.max(y,J.subscriptshift))}}this.HTMLhandleSpace(K);this.HTMLhandleColor(K);return K},HTMLstretchH:g.mbase.HTMLstretchH,HTMLstretchV:g.mbase.HTMLstretchV});g.mmultiscripts.Augment({toHTML:g.mbase.HTMLautoload});g.mtable.Augment({toHTML:g.mbase.HTMLautoload});g["annotation-xml"].Augment({toHTML:g.mbase.HTMLautoload});g.annotation.Augment({toHTML:function(k){return this.HTMLcreateSpan(k)}});g.math.Augment({toHTML:function(A,x,n){var q,s,t,m;if(!n||n===d.PHASE.I){var y=d.addElement(A,"nobr",{isMathJax:true});A=this.HTMLcreateSpan(y);var k=this.Get("alttext");if(k&&!A.getAttribute("aria-label")){A.setAttribute("aria-label",k)}if(!A.getAttribute("role")){A.setAttribute("role","math")}q=d.createStack(A);s=d.createBox(q);q.style.fontSize=y.parentNode.style.fontSize;y.parentNode.style.fontSize="";if(this.data[0]!=null){g.mbase.prototype.displayAlign=b.config.displayAlign;g.mbase.prototype.displayIndent=b.config.displayIndent;if(String(b.config.displayIndent).match(/^0($|[a-z%])/i)){g.mbase.prototype.displayIndent="0"}t=this.data[0].toHTML(s);t.bbox.exactW=false}}else{A=A.firstChild.firstChild;if(this.href){A=A.firstChild}q=A.firstChild;if(q.style.position!=="relative"){q=q.nextSibling}s=q.firstChild;t=s.firstChild}m=((!n||n===d.PHASE.II)?d.Measured(t,s):t);if(!n||n===d.PHASE.III){d.placeBox(s,0,0);A.style.width=d.Em(Math.max(0,Math.round(m.bbox.w*this.em)+0.25)/d.outerEm);A.style.display="inline-block";var w=1/d.em,C=d.em/d.outerEm;d.em/=C;A.bbox.h*=C;A.bbox.d*=C;A.bbox.w*=C;A.bbox.lw*=C;A.bbox.rw*=C;if(A.bbox.H){A.bbox.H*=C}if(A.bbox.D){A.bbox.D*=C}if(m&&m.bbox.width!=null){A.style.minWidth=(m.bbox.minWidth||A.style.width);A.style.width=m.bbox.width;s.style.width=q.style.width="100%"}var z=this.HTMLhandleColor(A);if(m){d.createRule(A,(m.bbox.h+w)*C,(m.bbox.d+w)*C,0)}if(!this.isMultiline&&this.Get("display")==="block"&&A.bbox.width==null){var l=this.getValues("indentalignfirst","indentshiftfirst","indentalign","indentshift");if(l.indentalignfirst!==g.INDENTALIGN.INDENTALIGN){l.indentalign=l.indentalignfirst}if(l.indentalign===g.INDENTALIGN.AUTO){l.indentalign=this.displayAlign}if(l.indentshiftfirst!==g.INDENTSHIFT.INDENTSHIFT){l.indentshift=l.indentshiftfirst}if(l.indentshift==="auto"){l.indentshift="0"}var B=d.length2em(l.indentshift,1,d.scale*d.cwidth);if(this.displayIndent!=="0"){var u=d.length2em(this.displayIndent,1,d.scale*d.cwidth);B+=(l.indentalign===g.INDENTALIGN.RIGHT?-u:u)}x.style.textAlign=l.indentalign;if(B){B*=d.em/d.outerEm;b.Insert(A.style,({left:{marginLeft:d.Em(B)},right:{marginLeft:d.Em(Math.max(0,A.bbox.w+B)),marginRight:d.Em(-B)},center:{marginLeft:d.Em(B),marginRight:d.Em(-B)}})[l.indentalign]);if(z){var r=parseFloat(z.style.marginLeft||"0")+B,o=parseFloat(z.style.marginRight||"0")-B;z.style.marginLeft=d.Em(r);z.style.marginRight=d.Em(o+(l.indentalign==="right"?Math.min(0,A.bbox.w+B)-A.bbox.w:0));if(d.msieColorBug&&l.indentalign==="right"){if(parseFloat(z.style.marginLeft)>0){var v=MathJax.HTML.addElement(z.parentNode,"span");v.style.marginLeft=d.Em(o+Math.min(0,A.bbox.w+B));z.nextSibling.style.marginRight="0em"}z.nextSibling.style.marginLeft="0em";z.style.marginRight=z.style.marginLeft="0em"}}}}}return A},HTMLspanElement:g.mbase.prototype.HTMLspanElement});g.TeXAtom.Augment({toHTML:function(o,m,q){o=this.HTMLcreateSpan(o);if(this.data[0]!=null){if(this.texClass===g.TEXCLASS.VCENTER){var k=d.createStack(o);var p=d.createBox(k);var r=this.data[0].toHTML(p);if(q!=null){d.Remeasured(this.data[0].HTMLstretchV(p,m,q),p)}else{if(m!=null){d.Remeasured(this.data[0].HTMLstretchH(p,m),p)}else{d.Measured(r,p)}}var l=d.TeX.axis_height*this.HTMLgetScale();d.placeBox(p,0,l-(p.bbox.h+p.bbox.d)/2+p.bbox.d)}else{var n=this.data[0].toHTML(o,m,q);if(q!=null){n=this.data[0].HTMLstretchV(p,m,q)}else{if(m!=null){n=this.data[0].HTMLstretchH(p,m)}}o.bbox=n.bbox}}this.HTMLhandleSpace(o);this.HTMLhandleColor(o);return o},HTMLstretchH:g.mbase.HTMLstretchH,HTMLstretchV:g.mbase.HTMLstretchV});b.Register.StartupHook("onLoad",function(){setTimeout(MathJax.Callback(["loadComplete",d,"jax.js"]),0)})});b.Register.StartupHook("End Config",function(){b.Browser.Select({MSIE:function(k){var o=(document.documentMode||0);var n=k.versionAtLeast("7.0");var m=k.versionAtLeast("8.0")&&o>7;var l=(document.compatMode==="BackCompat");if(o<9){d.config.styles[".MathJax .MathJax_HitBox"]["background-color"]="white";d.config.styles[".MathJax .MathJax_HitBox"].opacity=0;d.config.styles[".MathJax .MathJax_HitBox"].filter="alpha(opacity=0)"}d.Augment({PaddingWidthBug:true,msieAccentBug:true,msieColorBug:(o<8),msieColorPositionBug:true,msieRelativeWidthBug:l,msieDisappearingBug:(o>=8),msieMarginScaleBug:(o<8),msiePaddingWidthBug:true,msieBorderWidthBug:l,msieFrameSizeBug:(o<=8),msieInlineBlockAlignBug:(!m||l),msiePlaceBoxBug:(m&&!l),msieClipRectBug:!m,msieNegativeSpaceBug:l,msieRuleBug:(o<7),cloneNodeBug:(m&&k.version==="8.0"),msieItalicWidthBug:true,initialSkipBug:(o<8),msieNegativeBBoxBug:(o>=8),msieIE6:!n,msieItalicWidthBug:true,FontFaceBug:(o<9),msieFontCSSBug:k.isIE9,allowWebFonts:(o>=9?"woff":"eot")})},Firefox:function(l){var m=false;if(l.versionAtLeast("3.5")){var k=String(document.location).replace(/[^\/]*$/,"");if(document.location.protocol!=="file:"||b.config.root.match(/^https?:\/\//)||(b.config.root+"/").substr(0,k.length)===k){m="otf"}}d.Augment({ffVerticalAlignBug:!l.versionAtLeast("20.0"),AccentBug:true,allowWebFonts:m})},Safari:function(p){var n=p.versionAtLeast("3.0");var m=p.versionAtLeast("3.1");var k=navigator.appVersion.match(/ Safari\/\d/)&&navigator.appVersion.match(/ Version\/\d/)&&navigator.vendor.match(/Apple/);var l=(navigator.appVersion.match(/ Android (\d+)\.(\d+)/));var q=(m&&p.isMobile&&((navigator.platform.match(/iPad|iPod|iPhone/)&&!p.versionAtLeast("5.0"))||(l!=null&&(l[1]<2||(l[1]==2&&l[2]<2)))));d.Augment({config:{styles:{".MathJax img, .MathJax nobr, .MathJax a":{"max-width":"5000em","max-height":"5000em"}}},Em:((p.webkit||0)>=538?d.EmRounded:d.Em),rfuzz:0.011,AccentBug:true,AdjustSurd:true,negativeBBoxes:true,safariNegativeSpaceBug:true,safariVerticalAlignBug:!m,safariTextNodeBug:!n,forceReflow:true,FontFaceBug:true,allowWebFonts:(m&&!q?"otf":false)});if(k){d.Augment({webFontDefault:(p.isMobile?"sans-serif":"serif")})}if(p.isPC){d.Augment({adjustAvailableFonts:d.removeSTIXfonts,checkWebFontsTwice:true})}if(q){var o=b.config["HTML-CSS"];if(o){o.availableFonts=[];o.preferredFont=null}else{b.config["HTML-CSS"]={availableFonts:[],preferredFont:null}}}},Chrome:function(k){d.Augment({Em:d.EmRounded,cloneNodeBug:true,rfuzz:-0.02,AccentBug:true,AdjustSurd:true,FontFaceBug:k.versionAtLeast("32.0"),negativeBBoxes:true,safariNegativeSpaceBug:true,safariWebFontSerif:[""],forceReflow:true,allowWebFonts:(k.versionAtLeast("4.0")?"otf":"svg")})},Opera:function(k){k.isMini=(navigator.appVersion.match("Opera Mini")!=null);d.config.styles[".MathJax .merror"]["vertical-align"]=null;d.config.styles[".MathJax span"]["z-index"]=0;d.Augment({operaHeightBug:true,operaVerticalAlignBug:true,operaFontSizeBug:k.versionAtLeast("10.61"),initialSkipBug:true,FontFaceBug:true,PaddingWidthBug:true,allowWebFonts:(k.versionAtLeast("10.0")&&!k.isMini?"otf":false),adjustAvailableFonts:d.removeSTIXfonts})},Konqueror:function(k){d.Augment({konquerorVerticalAlignBug:true})}})});MathJax.Hub.Register.StartupHook("End Cookie",function(){if(b.config.menuSettings.zoom!=="None"){h.Require("[MathJax]/extensions/MathZoom.js")}})})(MathJax.Ajax,MathJax.Hub,MathJax.OutputJax["HTML-CSS"]);
| taydakov/cdnjs | ajax/libs/mathjax/2.5.3/jax/output/HTML-CSS/jax.js | JavaScript | mit | 79,295 |
#!/bin/sh
set -e
mkdir -p "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"
RESOURCES_TO_COPY=${PODS_ROOT}/resources-to-copy-${TARGETNAME}.txt
> "$RESOURCES_TO_COPY"
XCASSET_FILES=""
install_resource()
{
case $1 in
*.storyboard)
echo "ibtool --reference-external-strings-file --errors --warnings --notices --output-format human-readable-text --compile ${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$1\" .storyboard`.storyboardc ${PODS_ROOT}/$1 --sdk ${SDKROOT}"
ibtool --reference-external-strings-file --errors --warnings --notices --output-format human-readable-text --compile "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$1\" .storyboard`.storyboardc" "${PODS_ROOT}/$1" --sdk "${SDKROOT}"
;;
*.xib)
echo "ibtool --reference-external-strings-file --errors --warnings --notices --output-format human-readable-text --compile ${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$1\" .xib`.nib ${PODS_ROOT}/$1 --sdk ${SDKROOT}"
ibtool --reference-external-strings-file --errors --warnings --notices --output-format human-readable-text --compile "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$1\" .xib`.nib" "${PODS_ROOT}/$1" --sdk "${SDKROOT}"
;;
*.framework)
echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
echo "rsync -av ${PODS_ROOT}/$1 ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
rsync -av "${PODS_ROOT}/$1" "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
;;
*.xcdatamodel)
echo "xcrun momc \"${PODS_ROOT}/$1\" \"${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1"`.mom\""
xcrun momc "${PODS_ROOT}/$1" "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1" .xcdatamodel`.mom"
;;
*.xcdatamodeld)
echo "xcrun momc \"${PODS_ROOT}/$1\" \"${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1" .xcdatamodeld`.momd\""
xcrun momc "${PODS_ROOT}/$1" "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1" .xcdatamodeld`.momd"
;;
*.xcmappingmodel)
echo "xcrun mapc \"${PODS_ROOT}/$1\" \"${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1" .xcmappingmodel`.cdm\""
xcrun mapc "${PODS_ROOT}/$1" "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1" .xcmappingmodel`.cdm"
;;
*.xcassets)
XCASSET_FILES="$XCASSET_FILES '${PODS_ROOT}/$1'"
;;
/*)
echo "$1"
echo "$1" >> "$RESOURCES_TO_COPY"
;;
*)
echo "${PODS_ROOT}/$1"
echo "${PODS_ROOT}/$1" >> "$RESOURCES_TO_COPY"
;;
esac
}
rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"
if [[ "${ACTION}" == "install" ]]; then
rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"
fi
rm -f "$RESOURCES_TO_COPY"
if [[ -n "${WRAPPER_EXTENSION}" ]] && [ "`xcrun --find actool`" ] && [ -n "$XCASSET_FILES" ]
then
case "${TARGETED_DEVICE_FAMILY}" in
1,2)
TARGET_DEVICE_ARGS="--target-device ipad --target-device iphone"
;;
1)
TARGET_DEVICE_ARGS="--target-device iphone"
;;
2)
TARGET_DEVICE_ARGS="--target-device ipad"
;;
*)
TARGET_DEVICE_ARGS="--target-device mac"
;;
esac
while read line; do XCASSET_FILES="$XCASSET_FILES '$line'"; done <<<$(find "$PWD" -name "*.xcassets" | egrep -v "^$PODS_ROOT")
echo $XCASSET_FILES | xargs actool --output-format human-readable-text --notices --warnings --platform "${PLATFORM_NAME}" --minimum-deployment-target "${IPHONEOS_DEPLOYMENT_TARGET}" ${TARGET_DEVICE_ARGS} --compress-pngs --compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"
fi
| augmify/Locksmith | Example/Pods/Target Support Files/Pods-Tests/Pods-Tests-resources.sh | Shell | mit | 4,098 |
/**!
* AngularJS file upload/drop directive and service with progress and abort
* @author Danial <danial.farid@gmail.com>
* @version 3.1.0
*/
(function() {
function patchXHR(fnName, newFn) {
window.XMLHttpRequest.prototype[fnName] = newFn(window.XMLHttpRequest.prototype[fnName]);
}
if (window.XMLHttpRequest && !window.XMLHttpRequest.__isFileAPIShim) {
patchXHR('setRequestHeader', function(orig) {
return function(header, value) {
if (header === '__setXHR_') {
var val = value(this);
// fix for angular < 1.2.0
if (val instanceof Function) {
val(this);
}
} else {
orig.apply(this, arguments);
}
}
});
}
var angularFileUpload = angular.module('angularFileUpload', []);
angularFileUpload.version = '3.1.0';
angularFileUpload.service('$upload', ['$http', '$q', '$timeout', function($http, $q, $timeout) {
function sendHttp(config) {
config.method = config.method || 'POST';
config.headers = config.headers || {};
config.transformRequest = config.transformRequest || function(data, headersGetter) {
if (window.ArrayBuffer && data instanceof window.ArrayBuffer) {
return data;
}
return $http.defaults.transformRequest[0](data, headersGetter);
};
var deferred = $q.defer();
var promise = deferred.promise;
config.headers['__setXHR_'] = function() {
return function(xhr) {
if (!xhr) return;
config.__XHR = xhr;
config.xhrFn && config.xhrFn(xhr);
xhr.upload.addEventListener('progress', function(e) {
e.config = config;
deferred.notify ? deferred.notify(e) : promise.progress_fn && $timeout(function(){promise.progress_fn(e)});
}, false);
//fix for firefox not firing upload progress end, also IE8-9
xhr.upload.addEventListener('load', function(e) {
if (e.lengthComputable) {
e.config = config;
deferred.notify ? deferred.notify(e) : promise.progress_fn && $timeout(function(){promise.progress_fn(e)});
}
}, false);
};
};
$http(config).then(function(r){deferred.resolve(r)}, function(e){deferred.reject(e)}, function(n){deferred.notify(n)});
promise.success = function(fn) {
promise.then(function(response) {
fn(response.data, response.status, response.headers, config);
});
return promise;
};
promise.error = function(fn) {
promise.then(null, function(response) {
fn(response.data, response.status, response.headers, config);
});
return promise;
};
promise.progress = function(fn) {
promise.progress_fn = fn;
promise.then(null, null, function(update) {
fn(update);
});
return promise;
};
promise.abort = function() {
if (config.__XHR) {
$timeout(function() {
config.__XHR.abort();
});
}
return promise;
};
promise.xhr = function(fn) {
config.xhrFn = (function(origXhrFn) {
return function() {
origXhrFn && origXhrFn.apply(promise, arguments);
fn.apply(promise, arguments);
}
})(config.xhrFn);
return promise;
};
return promise;
}
this.upload = function(config) {
config.headers = config.headers || {};
config.headers['Content-Type'] = undefined;
var origTransformRequest = config.transformRequest;
config.transformRequest = config.transformRequest ?
(Object.prototype.toString.call(config.transformRequest) === '[object Array]' ?
config.transformRequest : [config.transformRequest]) : [];
config.transformRequest.push(function(data, headerGetter) {
var formData = new FormData();
var allFields = {};
for (var key in config.fields) allFields[key] = config.fields[key];
if (data) allFields['data'] = data;
if (config.formDataAppender) {
for (var key in allFields) {
config.formDataAppender(formData, key, allFields[key]);
}
} else {
for (var key in allFields) {
var val = allFields[key];
if (val !== undefined) {
if (Object.prototype.toString.call(val) === '[object String]') {
formData.append(key, val);
} else {
if (config.sendObjectsAsJsonBlob && typeof val === 'object') {
formData.append(key, new Blob([val], { type: 'application/json' }));
} else {
formData.append(key, JSON.stringify(val));
}
}
}
}
}
if (config.file != null) {
var fileFormName = config.fileFormDataName || 'file';
if (Object.prototype.toString.call(config.file) === '[object Array]') {
var isFileFormNameString = Object.prototype.toString.call(fileFormName) === '[object String]';
for (var i = 0; i < config.file.length; i++) {
formData.append(isFileFormNameString ? fileFormName : fileFormName[i], config.file[i],
(config.fileName && config.fileName[i]) || config.file[i].name);
}
} else {
formData.append(fileFormName, config.file, config.fileName || config.file.name);
}
}
return formData;
});
return sendHttp(config);
};
this.http = function(config) {
return sendHttp(config);
};
}]);
angularFileUpload.directive('ngFileSelect', [ '$parse', '$timeout', '$compile',
function($parse, $timeout, $compile) { return {
restrict: 'AEC',
require:'?ngModel',
link: function(scope, elem, attr, ngModel) {
handleFileSelect(scope, elem, attr, ngModel, $parse, $timeout, $compile);
}
}}]);
function handleFileSelect(scope, elem, attr, ngModel, $parse, $timeout, $compile) {
function isInputTypeFile() {
return elem[0].tagName.toLowerCase() === 'input' && elem.attr('type') && elem.attr('type').toLowerCase() === 'file';
}
var watchers = [];
function watch(attrVal) {
$timeout(function() {
if (elem.parent().length) {
watchers.push(scope.$watch(attrVal, function(val, oldVal) {
if (val != oldVal) {
recompileElem();
}
}));
}
});
}
function recompileElem() {
var clone = elem.clone();
if (elem.attr('__afu_gen__')) {
angular.element(document.getElementById(elem.attr('id').substring(1))).remove();
}
if (elem.parent().length) {
for (var i = 0; i < watchers.length; i++) {
watchers[i]();
}
elem.replaceWith(clone);
$compile(clone)(scope);
}
return clone;
}
function bindAttr(bindAttr, attrName) {
if (bindAttr) {
watch(bindAttr);
var val = $parse(bindAttr)(scope);
if (val) {
elem.attr(attrName, val);
attr[attrName] = val;
} else {
elem.attr(attrName, null);
delete attr[attrName];
}
}
}
bindAttr(attr.ngMultiple, 'multiple');
bindAttr(attr.ngAccept, 'accept');
bindAttr(attr.ngCapture, 'capture');
if (attr['ngFileSelect'] != '') {
attr.ngFileChange = attr.ngFileSelect;
}
function onChangeFn(evt) {
var files = [], fileList, i;
fileList = evt.__files_ || (evt.target && evt.target.files);
updateModel(fileList, attr, ngModel, scope, evt);
};
var fileElem = elem;
if (!isInputTypeFile()) {
fileElem = angular.element('<input type="file">')
if (attr['multiple']) fileElem.attr('multiple', attr['multiple']);
if (attr['accept']) fileElem.attr('accept', attr['accept']);
if (attr['capture']) fileElem.attr('capture', attr['capture']);
for (var key in attr) {
if (key.indexOf('inputFile') == 0) {
var name = key.substring('inputFile'.length);
name = name[0].toLowerCase() + name.substring(1);
fileElem.attr(name, attr[key]);
}
}
fileElem.css('width', '0px').css('height', '0px').css('position', 'absolute').css('padding', 0).css('margin', 0)
.css('overflow', 'hidden').attr('tabindex', '-1').css('opacity', 0).attr('__afu_gen__', true);
elem.attr('__refElem__', true);
fileElem[0].__refElem__ = elem[0];
elem.parent()[0].insertBefore(fileElem[0], elem[0])
elem.css('overflow', 'hidden');
elem.bind('click', function(e) {
if (!resetAndClick(e)) {
fileElem[0].click();
}
});
} else {
elem.bind('click', resetAndClick);
}
function resetAndClick(evt) {
if (fileElem[0].value != null && fileElem[0].value != '') {
fileElem[0].value = null;
// IE 11 already fires change event when you set the value to null
if (navigator.userAgent.indexOf("Trident/7") === -1) {
onChangeFn({target: {files: []}});
}
}
// if this is manual click trigger we don't need to reset again
if (!elem.attr('__afu_clone__')) {
// fix for IE10 cannot set the value of the input to null programmatically by cloning and replacing input
// IE 11 setting the value to null event will be fired after file change clearing the selected file so
// we just recreate the element for IE 11 as well
if (navigator.appVersion.indexOf("MSIE 10") !== -1 || navigator.userAgent.indexOf("Trident/7") !== -1) {
var clone = recompileElem();
clone.attr('__afu_clone__', true);
clone[0].click();
evt.preventDefault();
evt.stopPropagation();
return true;
}
} else {
elem.attr('__afu_clone__', null);
}
}
fileElem.bind('change', onChangeFn);
elem.on('$destroy', function() {
for (var i = 0; i < watchers.length; i++) {
watchers[i]();
}
if (elem[0] != fileElem[0]) fileElem.remove();
});
watchers.push(scope.$watch(attr.ngModel, function(val, oldVal) {
if (val != oldVal && (val == null || !val.length)) {
if (navigator.appVersion.indexOf("MSIE 10") !== -1) {
recompileElem();
} else {
fileElem[0].value = null;
}
}
}));
function updateModel(fileList, attr, ngModel, scope, evt) {
var files = [], rejFiles = [];
var accept = $parse(attr.ngAccept)(scope);
var regexp = angular.isString(accept) && accept ? new RegExp(globStringToRegex(accept), 'gi') : null;
var acceptFn = regexp ? null : attr.ngAccept;
for (var i = 0; i < fileList.length; i++) {
var file = fileList.item(i);
if ((!regexp || file.type.match(regexp) || (file.name != null && file.name.match(regexp))) &&
(!acceptFn || $parse(acceptFn)(scope, {$file: file, $event: evt}))) {
files.push(file);
} else {
rejFiles.push(file);
}
}
$timeout(function() {
if (ngModel) {
$parse(attr.ngModel).assign(scope, files);
ngModel && ngModel.$setViewValue(files != null && files.length == 0 ? '' : files);
if (attr.ngModelRejected) {
$parse(attr.ngModelRejected).assign(scope, rejFiles);
}
}
if (attr.ngFileChange && attr.ngFileChange != "") {
$parse(attr.ngFileChange)(scope, {
$files: files,
$rejectedFiles: rejFiles,
$event: evt
});
}
});
}
}
angularFileUpload.directive('ngFileDrop', [ '$parse', '$timeout', '$location', function($parse, $timeout, $location) { return {
restrict: 'AEC',
require:'?ngModel',
link: function(scope, elem, attr, ngModel) {
handleDrop(scope, elem, attr, ngModel, $parse, $timeout, $location);
}
}}]);
angularFileUpload.directive('ngNoFileDrop', function() {
return function(scope, elem, attr) {
if (dropAvailable()) elem.css('display', 'none')
}
});
//for backward compatibility
angularFileUpload.directive('ngFileDropAvailable', [ '$parse', '$timeout', function($parse, $timeout) {
return function(scope, elem, attr) {
if (dropAvailable()) {
var fn = $parse(attr['ngFileDropAvailable']);
$timeout(function() {
fn(scope);
});
}
}
}]);
function handleDrop(scope, elem, attr, ngModel, $parse, $timeout, $location) {
var available = dropAvailable();
if (attr['dropAvailable']) {
$timeout(function() {
scope.dropAvailable ? scope.dropAvailable.value = available : scope.dropAvailable = available;
});
}
if (!available) {
if ($parse(attr.hideOnDropNotAvailable)(scope) != false) {
elem.css('display', 'none');
}
return;
}
var leaveTimeout = null;
var stopPropagation = $parse(attr.stopPropagation)(scope);
var dragOverDelay = 1;
var accept = $parse(attr.ngAccept)(scope) || attr.accept;
var regexp = angular.isString(accept) && accept ? new RegExp(globStringToRegex(accept), 'gi') : null;
var acceptFn = regexp ? null : attr.ngAccept;
var actualDragOverClass;
elem[0].addEventListener('dragover', function(evt) {
evt.preventDefault();
if (stopPropagation) evt.stopPropagation();
// handling dragover events from the Chrome download bar
if (navigator.userAgent.indexOf("Chrome") > -1) {
var b = evt.dataTransfer.effectAllowed;
evt.dataTransfer.dropEffect = ('move' === b || 'linkMove' === b) ? 'move' : 'copy';
}
$timeout.cancel(leaveTimeout);
if (!scope.actualDragOverClass) {
actualDragOverClass = calculateDragOverClass(scope, attr, evt);
}
elem.addClass(actualDragOverClass);
}, false);
elem[0].addEventListener('dragenter', function(evt) {
evt.preventDefault();
if (stopPropagation) evt.stopPropagation();
}, false);
elem[0].addEventListener('dragleave', function(evt) {
leaveTimeout = $timeout(function() {
elem.removeClass(actualDragOverClass);
actualDragOverClass = null;
}, dragOverDelay || 1);
}, false);
if (attr['ngFileDrop'] != '') {
attr.ngFileChange = scope.ngFileDrop;
}
elem[0].addEventListener('drop', function(evt) {
evt.preventDefault();
if (stopPropagation) evt.stopPropagation();
elem.removeClass(actualDragOverClass);
actualDragOverClass = null;
extractFiles(evt, function(files, rejFiles) {
$timeout(function() {
if (ngModel) {
$parse(attr.ngModel).assign(scope, files);
ngModel && ngModel.$setViewValue(files != null && files.length == 0 ? '' : files);
}
if (attr['ngModelRejected']) {
if (scope[attr.ngModelRejected]) {
$parse(attr.ngModelRejected).assign(scope, rejFiles);
}
}
});
$timeout(function() {
$parse(attr.ngFileChange)(scope, {
$files: files,
$rejectedFiles: rejFiles,
$event: evt
});
});
}, $parse(attr.allowDir)(scope) != false, attr.multiple || $parse(attr.ngMultiple)(scope));
}, false);
function calculateDragOverClass(scope, attr, evt) {
var valid = true;
if (regexp || acceptFn) {
var items = evt.dataTransfer.items;
if (items != null) {
for (var i = 0 ; i < items.length && valid; i++) {
valid = valid && (items[i].kind == 'file' || items[i].kind == '') &&
((acceptFn && $parse(acceptFn)(scope, {$file: items[i], $event: evt})) ||
(regexp && (items[i].type != null && items[i].type.match(regexp)) ||
(items[i].name != null && items[i].name.match(regexp))));
}
}
}
var clazz = $parse(attr.dragOverClass)(scope, {$event : evt});
if (clazz) {
if (clazz.delay) dragOverDelay = clazz.delay;
if (clazz.accept) clazz = valid ? clazz.accept : clazz.reject;
}
return clazz || attr['dragOverClass'] || 'dragover';
}
function extractFiles(evt, callback, allowDir, multiple) {
var files = [], rejFiles = [], items = evt.dataTransfer.items, processing = 0;
function addFile(file) {
if ((!regexp || file.type.match(regexp) || (file.name != null && file.name.match(regexp))) &&
(!acceptFn || $parse(acceptFn)(scope, {$file: file, $event: evt}))) {
files.push(file);
} else {
rejFiles.push(file);
}
}
if (items && items.length > 0 && $location.protocol() != 'file') {
for (var i = 0; i < items.length; i++) {
if (items[i].webkitGetAsEntry && items[i].webkitGetAsEntry() && items[i].webkitGetAsEntry().isDirectory) {
var entry = items[i].webkitGetAsEntry();
if (entry.isDirectory && !allowDir) {
continue;
}
if (entry != null) {
traverseFileTree(files, entry);
}
} else {
var f = items[i].getAsFile();
if (f != null) addFile(f);
}
if (!multiple && files.length > 0) break;
}
} else {
var fileList = evt.dataTransfer.files;
if (fileList != null) {
for (var i = 0; i < fileList.length; i++) {
addFile(fileList.item(i));
if (!multiple && files.length > 0) break;
}
}
}
var delays = 0;
(function waitForProcess(delay) {
$timeout(function() {
if (!processing) {
if (!multiple && files.length > 1) {
var i = 0;
while (files[i].type == 'directory') i++;
files = [files[i]];
}
callback(files, rejFiles);
} else {
if (delays++ * 10 < 20 * 1000) {
waitForProcess(10);
}
}
}, delay || 0)
})();
function traverseFileTree(files, entry, path) {
if (entry != null) {
if (entry.isDirectory) {
var filePath = (path || '') + entry.name;
addFile({name: entry.name, type: 'directory', path: filePath});
var dirReader = entry.createReader();
var entries = [];
processing++;
var readEntries = function() {
dirReader.readEntries(function(results) {
try {
if (!results.length) {
for (var i = 0; i < entries.length; i++) {
traverseFileTree(files, entries[i], (path ? path : '') + entry.name + '/');
}
processing--;
} else {
entries = entries.concat(Array.prototype.slice.call(results || [], 0));
readEntries();
}
} catch (e) {
processing--;
console.error(e);
}
}, function() {
processing--;
});
};
readEntries();
} else {
processing++;
entry.file(function(file) {
try {
processing--;
file.path = (path ? path : '') + file.name;
addFile(file);
} catch (e) {
processing--;
console.error(e);
}
}, function(e) {
processing--;
});
}
}
}
}
}
function dropAvailable() {
var div = document.createElement('div');
return ('draggable' in div) && ('ondrop' in div);
}
function globStringToRegex(str) {
if (str.length > 2 && str[0] === '/' && str[str.length -1] === '/') {
return str.substring(1, str.length - 1);
}
var split = str.split(','), result = '';
if (split.length > 1) {
for (var i = 0; i < split.length; i++) {
result += '(' + globStringToRegex(split[i]) + ')';
if (i < split.length - 1) {
result += '|'
}
}
} else {
if (str.indexOf('.') == 0) {
str= '*' + str;
}
result = '^' + str.replace(new RegExp('[.\\\\+*?\\[\\^\\]$(){}=!<>|:\\' + '-]', 'g'), '\\$&') + '$';
result = result.replace(/\\\*/g, '.*').replace(/\\\?/g, '.');
}
return result;
}
var ngFileUpload = angular.module('ngFileUpload', []);
for (var key in angularFileUpload) {
ngFileUpload[key] = angularFileUpload[key];
}
})();
/**!
* AngularJS file upload/drop directive and service with progress and abort
* FileAPI Flash shim for old browsers not supporting FormData
* @author Danial <danial.farid@gmail.com>
* @version 3.1.0
*/
(function() {
var hasFlash = function() {
try {
var fo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
if (fo) return true;
} catch(e) {
if (navigator.mimeTypes['application/x-shockwave-flash'] != undefined) return true;
}
return false;
}
function patchXHR(fnName, newFn) {
window.XMLHttpRequest.prototype[fnName] = newFn(window.XMLHttpRequest.prototype[fnName]);
};
if ((window.XMLHttpRequest && !window.FormData) || (window.FileAPI && FileAPI.forceLoad)) {
var initializeUploadListener = function(xhr) {
if (!xhr.__listeners) {
if (!xhr.upload) xhr.upload = {};
xhr.__listeners = [];
var origAddEventListener = xhr.upload.addEventListener;
xhr.upload.addEventListener = function(t, fn, b) {
xhr.__listeners[t] = fn;
origAddEventListener && origAddEventListener.apply(this, arguments);
};
}
}
patchXHR('open', function(orig) {
return function(m, url, b) {
initializeUploadListener(this);
this.__url = url;
try {
orig.apply(this, [m, url, b]);
} catch (e) {
if (e.message.indexOf('Access is denied') > -1) {
this.__origError = e;
orig.apply(this, [m, '_fix_for_ie_crossdomain__', b]);
}
}
}
});
patchXHR('getResponseHeader', function(orig) {
return function(h) {
return this.__fileApiXHR && this.__fileApiXHR.getResponseHeader ? this.__fileApiXHR.getResponseHeader(h) : (orig == null ? null : orig.apply(this, [h]));
};
});
patchXHR('getAllResponseHeaders', function(orig) {
return function() {
return this.__fileApiXHR && this.__fileApiXHR.getAllResponseHeaders ? this.__fileApiXHR.getAllResponseHeaders() : (orig == null ? null : orig.apply(this));
}
});
patchXHR('abort', function(orig) {
return function() {
return this.__fileApiXHR && this.__fileApiXHR.abort ? this.__fileApiXHR.abort() : (orig == null ? null : orig.apply(this));
}
});
patchXHR('setRequestHeader', function(orig) {
return function(header, value) {
if (header === '__setXHR_') {
initializeUploadListener(this);
var val = value(this);
// fix for angular < 1.2.0
if (val instanceof Function) {
val(this);
}
} else {
this.__requestHeaders = this.__requestHeaders || {};
this.__requestHeaders[header] = value;
orig.apply(this, arguments);
}
}
});
function redefineProp(xhr, prop, fn) {
try {
Object.defineProperty(xhr, prop, {get: fn});
} catch (e) {/*ignore*/}
}
patchXHR('send', function(orig) {
return function() {
var xhr = this;
if (arguments[0] && arguments[0].__isFileAPIShim) {
var formData = arguments[0];
var config = {
url: xhr.__url,
jsonp: false, //removes the callback form param
cache: true, //removes the ?fileapiXXX in the url
complete: function(err, fileApiXHR) {
xhr.__completed = true;
if (!err && xhr.__listeners['load'])
xhr.__listeners['load']({type: 'load', loaded: xhr.__loaded, total: xhr.__total, target: xhr, lengthComputable: true});
if (!err && xhr.__listeners['loadend'])
xhr.__listeners['loadend']({type: 'loadend', loaded: xhr.__loaded, total: xhr.__total, target: xhr, lengthComputable: true});
if (err === 'abort' && xhr.__listeners['abort'])
xhr.__listeners['abort']({type: 'abort', loaded: xhr.__loaded, total: xhr.__total, target: xhr, lengthComputable: true});
if (fileApiXHR.status !== undefined) redefineProp(xhr, 'status', function() {return (fileApiXHR.status == 0 && err && err !== 'abort') ? 500 : fileApiXHR.status});
if (fileApiXHR.statusText !== undefined) redefineProp(xhr, 'statusText', function() {return fileApiXHR.statusText});
redefineProp(xhr, 'readyState', function() {return 4});
if (fileApiXHR.response !== undefined) redefineProp(xhr, 'response', function() {return fileApiXHR.response});
var resp = fileApiXHR.responseText || (err && fileApiXHR.status == 0 && err !== 'abort' ? err : undefined);
redefineProp(xhr, 'responseText', function() {return resp});
redefineProp(xhr, 'response', function() {return resp});
if (err) redefineProp(xhr, 'err', function() {return err});
xhr.__fileApiXHR = fileApiXHR;
if (xhr.onreadystatechange) xhr.onreadystatechange();
if (xhr.onload) xhr.onload();
},
fileprogress: function(e) {
e.target = xhr;
xhr.__listeners['progress'] && xhr.__listeners['progress'](e);
xhr.__total = e.total;
xhr.__loaded = e.loaded;
if (e.total === e.loaded) {
// fix flash issue that doesn't call complete if there is no response text from the server
var _this = this
setTimeout(function() {
if (!xhr.__completed) {
xhr.getAllResponseHeaders = function(){};
_this.complete(null, {status: 204, statusText: 'No Content'});
}
}, FileAPI.noContentTimeout || 10000);
}
},
headers: xhr.__requestHeaders
}
config.data = {};
config.files = {}
for (var i = 0; i < formData.data.length; i++) {
var item = formData.data[i];
if (item.val != null && item.val.name != null && item.val.size != null && item.val.type != null) {
config.files[item.key] = item.val;
} else {
config.data[item.key] = item.val;
}
}
setTimeout(function() {
if (!hasFlash()) {
throw 'Adode Flash Player need to be installed. To check ahead use "FileAPI.hasFlash"';
}
xhr.__fileApiXHR = FileAPI.upload(config);
}, 1);
} else {
if (this.__origError) {
throw this.__origError;
}
orig.apply(xhr, arguments);
}
}
});
window.XMLHttpRequest.__isFileAPIShim = true;
var addFlash = function(elem) {
if (!hasFlash()) {
throw 'Adode Flash Player need to be installed. To check ahead use "FileAPI.hasFlash"';
}
var el = angular.element(elem);
if (!el.attr('disabled')) {
var hasFileSelect = false;
for (var i = 0; i < el[0].attributes.length; i++) {
var attrib = el[0].attributes[i];
if (attrib.name.indexOf('file-select') !== -1) {
hasFileSelect = true;
break;
}
}
if (!el.hasClass('js-fileapi-wrapper') && (hasFileSelect || el.attr('__afu_gen__') != null)) {
el.addClass('js-fileapi-wrapper');
if (el.attr('__afu_gen__') != null) {
var ref = (el[0].__refElem__ && angular.element(el[0].__refElem__)) || el;
while (ref && !ref.attr('__refElem__')) {
ref = angular.element(ref[0].nextSibling);
}
ref.bind('mouseover', function() {
if (el.parent().css('position') === '' || el.parent().css('position') === 'static') {
el.parent().css('position', 'relative');
}
el.css('position', 'absolute').css('top', ref[0].offsetTop + 'px').css('left', ref[0].offsetLeft + 'px')
.css('width', ref[0].offsetWidth + 'px').css('height', ref[0].offsetHeight + 'px')
.css('padding', ref.css('padding')).css('margin', ref.css('margin')).css('filter', 'alpha(opacity=0)');
ref.attr('onclick', '');
el.css('z-index', '1000');
});
}
}
}
};
var changeFnWrapper = function(fn) {
return function(evt) {
var files = FileAPI.getFiles(evt);
//just a double check for #233
for (var i = 0; i < files.length; i++) {
if (files[i].size === undefined) files[i].size = 0;
if (files[i].name === undefined) files[i].name = 'file';
if (files[i].type === undefined) files[i].type = 'undefined';
}
if (!evt.target) {
evt.target = {};
}
evt.target.files = files;
// if evt.target.files is not writable use helper field
if (evt.target.files != files) {
evt.__files_ = files;
}
(evt.__files_ || evt.target.files).item = function(i) {
return (evt.__files_ || evt.target.files)[i] || null;
}
if (fn) fn.apply(this, [evt]);
};
};
var isFileChange = function(elem, e) {
return (e.toLowerCase() === 'change' || e.toLowerCase() === 'onchange') && elem.getAttribute('type') == 'file';
}
if (HTMLInputElement.prototype.addEventListener) {
HTMLInputElement.prototype.addEventListener = (function(origAddEventListener) {
return function(e, fn, b, d) {
if (isFileChange(this, e)) {
addFlash(this);
origAddEventListener.apply(this, [e, changeFnWrapper(fn), b, d]);
} else {
origAddEventListener.apply(this, [e, fn, b, d]);
}
}
})(HTMLInputElement.prototype.addEventListener);
}
if (HTMLInputElement.prototype.attachEvent) {
HTMLInputElement.prototype.attachEvent = (function(origAttachEvent) {
return function(e, fn) {
if (isFileChange(this, e)) {
addFlash(this);
if (window.jQuery) {
// fix for #281 jQuery on IE8
angular.element(this).bind('change', changeFnWrapper(null));
} else {
origAttachEvent.apply(this, [e, changeFnWrapper(fn)]);
}
} else {
origAttachEvent.apply(this, [e, fn]);
}
}
})(HTMLInputElement.prototype.attachEvent);
}
window.FormData = FormData = function() {
return {
append: function(key, val, name) {
if (val.__isFileAPIBlobShim) {
val = val.data[0];
}
this.data.push({
key: key,
val: val,
name: name
});
},
data: [],
__isFileAPIShim: true
};
};
window.Blob = Blob = function(b) {
return {
data: b,
__isFileAPIBlobShim: true
};
};
(function () {
//load FileAPI
if (!window.FileAPI) {
window.FileAPI = {};
}
if (FileAPI.forceLoad) {
FileAPI.html5 = false;
}
if (!FileAPI.upload) {
var jsUrl, basePath, script = document.createElement('script'), allScripts = document.getElementsByTagName('script'), i, index, src;
if (window.FileAPI.jsUrl) {
jsUrl = window.FileAPI.jsUrl;
} else if (window.FileAPI.jsPath) {
basePath = window.FileAPI.jsPath;
} else {
for (i = 0; i < allScripts.length; i++) {
src = allScripts[i].src;
index = src.search(/\/angular\-file\-upload[\-a-zA-z0-9\.]*\.js/)
if (index > -1) {
basePath = src.substring(0, index + 1);
break;
}
}
}
if (FileAPI.staticPath == null) FileAPI.staticPath = basePath;
script.setAttribute('src', jsUrl || basePath + 'FileAPI.min.js');
document.getElementsByTagName('head')[0].appendChild(script);
FileAPI.hasFlash = hasFlash();
}
})();
FileAPI.disableFileInput = function(elem, disable) {
if (disable) {
elem.removeClass('js-fileapi-wrapper')
} else {
elem.addClass('js-fileapi-wrapper');
}
}
}
if (!window.FileReader) {
window.FileReader = function() {
var _this = this, loadStarted = false;
this.listeners = {};
this.addEventListener = function(type, fn) {
_this.listeners[type] = _this.listeners[type] || [];
_this.listeners[type].push(fn);
};
this.removeEventListener = function(type, fn) {
_this.listeners[type] && _this.listeners[type].splice(_this.listeners[type].indexOf(fn), 1);
};
this.dispatchEvent = function(evt) {
var list = _this.listeners[evt.type];
if (list) {
for (var i = 0; i < list.length; i++) {
list[i].call(_this, evt);
}
}
};
this.onabort = this.onerror = this.onload = this.onloadstart = this.onloadend = this.onprogress = null;
var constructEvent = function(type, evt) {
var e = {type: type, target: _this, loaded: evt.loaded, total: evt.total, error: evt.error};
if (evt.result != null) e.target.result = evt.result;
return e;
};
var listener = function(evt) {
if (!loadStarted) {
loadStarted = true;
_this.onloadstart && _this.onloadstart(constructEvent('loadstart', evt));
}
if (evt.type === 'load') {
_this.onloadend && _this.onloadend(constructEvent('loadend', evt));
var e = constructEvent('load', evt);
_this.onload && _this.onload(e);
_this.dispatchEvent(e);
} else if (evt.type === 'progress') {
var e = constructEvent('progress', evt);
_this.onprogress && _this.onprogress(e);
_this.dispatchEvent(e);
} else {
var e = constructEvent('error', evt);
_this.onerror && _this.onerror(e);
_this.dispatchEvent(e);
}
};
this.readAsArrayBuffer = function(file) {
FileAPI.readAsBinaryString(file, listener);
}
this.readAsBinaryString = function(file) {
FileAPI.readAsBinaryString(file, listener);
}
this.readAsDataURL = function(file) {
FileAPI.readAsDataURL(file, listener);
}
this.readAsText = function(file) {
FileAPI.readAsText(file, listener);
}
}
}
})();
| humbletim/cdnjs | ajax/libs/danialfarid-angular-file-upload/3.1.0/angular-file-upload-all.js | JavaScript | mit | 30,740 |
/*
TimelineJS - ver. 2.32.0 - 2014-05-08
Copyright (c) 2012-2013 Northwestern University
a project of the Northwestern University Knight Lab, originally created by Zach Wise
https://github.com/NUKnightLab/TimelineJS
This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
/* Spanish LANGUAGE
================================================== */typeof VMM!="undefined"&&(VMM.Language={lang:"es",api:{wikipedia:"es"},date:{month:["Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"],month_abbr:["Ene.","Feb.","Mar.","Abr.","May.","Jun.","Jul.","Ago.","Sep.","Oct.","Nov.","Dic."],day:["Domingo","Lunes","Martes","Miércoles","Jueves","Viernes","Sábado"],day_abbr:["Dom.","Lun.","Mar.","Mié.","Jue.","Vie.","Sáb."]},dateformats:{year:"yyyy",month_short:"mmm",month:"mmmm yyyy",full_short:"d mmm",full:"d mmmm yyyy",time_short:"HH:MM:SS",time_no_seconds_short:"HH:MM",time_no_seconds_small_date:"'<small>'d mmmm yyyy'</small>' HH:MM",full_long:"dddd',' d mmm yyyy HH:MM",full_long_small_date:"HH:MM'<br/><small>d mmm yyyy'</small>'"},messages:{loading_timeline:"La cronología esta cargando",return_to_title:"Volver al título",expand_timeline:"Expandir la cronología",contract_timeline:"Reducir la cronología",wikipedia:"Desde Wikipedia, la enciclopedia libre",loading_content:"cargando",loading:"cargando"}}); | simudream/cdnjs | ajax/libs/timelinejs/2.32.0/js/locale/es.js | JavaScript | mit | 1,539 |
/**
* Editable Inline
* ---------------------
*/
(function ($) {
//extend methods
$.extend($.fn.editableContainer.Constructor.prototype, {
containerName: 'editableform',
innerCss: null,
initContainer: function(){
//no init for container
//only convert anim to miliseconds (int)
if(!this.options.anim) {
this.options.anim = 0;
}
},
splitOptions: function() {
this.containerOptions = {};
this.formOptions = this.options;
},
tip: function() {
return this.$form;
},
innerShow: function () {
this.$element.hide();
if(this.$form) {
this.$form.remove();
}
this.initForm();
this.tip().addClass('editable-container').addClass('editable-inline');
this.$form.insertAfter(this.$element);
this.$form.show(this.options.anim);
this.$form.editableform('render');
},
innerHide: function () {
this.$form.hide(this.options.anim, $.proxy(function() {
this.$element.show();
//return focus on element
if (this.options.enablefocus) {
this.$element.focus();
}
}, this));
},
destroy: function() {
this.tip().remove();
}
});
//defaults
$.fn.editableContainer.defaults = $.extend({}, $.fn.editableContainer.defaults, {
anim: 'fast',
enablefocus: false
});
}(window.jQuery)); | iamJoeTaylor/cdnjs | ajax/libs/x-editable/1.1.1/containers/editable-inline.js | JavaScript | mit | 1,755 |
/*! loglevel - v0.6.0 - https://github.com/pimterry/loglevel - (c) 2014 Tim Perry - licensed MIT */
!function(a){var b="undefined";!function(a,b){"undefined"!=typeof module?module.exports=b():"function"==typeof define&&"object"==typeof define.amd?define(b):this[a]=b()}("log",function(){function c(c){return typeof console===b?l:console[c]===a?console.log!==a?d(console,"log"):l:d(console,c)}function d(b,c){var d=b[c];if(d.bind!==a)return b[c].bind(b);if(Function.prototype.bind===a)return e(d,b);try{return Function.prototype.bind.call(b[c],b)}catch(f){return e(d,b)}}function e(a,b){return function(){Function.prototype.apply.apply(a,[b,arguments])}}function f(a){for(var b=0;b<m.length;b++)k[m[b]]=a(m[b])}function g(){return typeof window!==b&&window.document!==a&&window.document.cookie!==a}function h(){try{return typeof window!==b&&window.localStorage!==a}catch(c){return!1}}function i(a){var b,c=!1;for(var d in k.levels)if(k.levels.hasOwnProperty(d)&&k.levels[d]===a){b=d;break}if(h())try{window.localStorage.loglevel=b}catch(e){c=!0}else c=!0;c&&g()&&(window.document.cookie="loglevel="+b+";")}function j(){var b;if(h()&&(b=window.localStorage.loglevel),b===a&&g()){var c=n.exec(window.document.cookie)||[];b=c[1]}k.levels[b]===a&&(b="WARN"),k.setLevel(k.levels[b])}var k={},l=function(){},m=["trace","debug","info","warn","error"],n=/loglevel=([^;]+)/;return k.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},k.setLevel=function(d){if("number"==typeof d&&d>=0&&d<=k.levels.SILENT){if(i(d),d===k.levels.SILENT)return void f(function(){return l});if(typeof console===b)return f(function(a){return function(){typeof console!==b&&(k.setLevel(d),k[a].apply(k,arguments))}}),"No console available for logging";f(function(a){return d<=k.levels[a.toUpperCase()]?c(a):l})}else{if("string"!=typeof d||k.levels[d.toUpperCase()]===a)throw"log.setLevel() called with invalid level: "+d;k.setLevel(k.levels[d.toUpperCase()])}},k.enableAll=function(){k.setLevel(k.levels.TRACE)},k.disableAll=function(){k.setLevel(k.levels.SILENT)},j(),k})}(); | alexmojaki/cdnjs | ajax/libs/loglevel/0.6.0/loglevel.min.js | JavaScript | mit | 2,049 |
/**
* Editable Popover
* ---------------------
* requires bootstrap-popover.js
*/
(function ($) {
//extend methods
$.extend($.fn.editableContainer.Constructor.prototype, {
containerName: 'popover',
//for compatibility with bootstrap <= 2.2.1 (content inserted into <p> instead of directly .popover-content)
innerCss: $($.fn.popover.defaults.template).find('p').length ? '.popover-content p' : '.popover-content',
initContainer: function(){
$.extend(this.containerOptions, {
trigger: 'manual',
selector: false,
content: ' '
});
this.call(this.containerOptions);
},
setContainerOption: function(key, value) {
this.container().options[key] = value;
},
/**
* move popover to new position. This function mainly copied from bootstrap-popover.
*/
/*jshint laxcomma: true*/
setPosition: function () {
(function() {
var $tip = this.tip()
, inside
, pos
, actualWidth
, actualHeight
, placement
, tp;
placement = typeof this.options.placement === 'function' ?
this.options.placement.call(this, $tip[0], this.$element[0]) :
this.options.placement;
inside = /in/.test(placement);
$tip
// .detach()
//vitalets: remove any placement class because otherwise they dont influence on re-positioning of visible popover
.removeClass('top right bottom left')
.css({ top: 0, left: 0, display: 'block' });
// .insertAfter(this.$element);
pos = this.getPosition(inside);
actualWidth = $tip[0].offsetWidth;
actualHeight = $tip[0].offsetHeight;
switch (inside ? placement.split(' ')[1] : placement) {
case 'bottom':
tp = {top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2};
break;
case 'top':
tp = {top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2};
break;
case 'left':
tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth};
break;
case 'right':
tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width};
break;
}
$tip
.offset(tp)
.addClass(placement)
.addClass('in');
}).call(this.container());
/*jshint laxcomma: false*/
}
});
//defaults
/*
$.fn.editableContainer.defaults = $.extend({}, $.fn.popover.defaults, $.fn.editableContainer.defaults, {
});
*/
}(window.jQuery)); | Stavrakakis/cdnjs | ajax/libs/x-editable/1.3.0/containers/editable-popover.js | JavaScript | mit | 3,246 |
/* Copyright (c) 2006-2013 by OpenLayers Contributors (see authors.txt for
* full list of contributors). Published under the 2-clause BSD license.
* See license.txt in the OpenLayers distribution or repository for the
* full text of the license. */
/**
* @requires OpenLayers/Layer/SphericalMercator.js
* @requires OpenLayers/Layer/EventPane.js
* @requires OpenLayers/Layer/FixedZoomLevels.js
* @requires OpenLayers/Lang.js
*/
/**
* Class: OpenLayers.Layer.Google
*
* Provides a wrapper for Google's Maps API
* Normally the Terms of Use for this API do not allow wrapping, but Google
* have provided written consent to OpenLayers for this - see email in
* http://osgeo-org.1560.n6.nabble.com/Google-Maps-API-Terms-of-Use-changes-tp4910013p4911981.html
*
* Inherits from:
* - <OpenLayers.Layer.SphericalMercator>
* - <OpenLayers.Layer.EventPane>
* - <OpenLayers.Layer.FixedZoomLevels>
*/
OpenLayers.Layer.Google = OpenLayers.Class(
OpenLayers.Layer.EventPane,
OpenLayers.Layer.FixedZoomLevels, {
/**
* Constant: MIN_ZOOM_LEVEL
* {Integer} 0
*/
MIN_ZOOM_LEVEL: 0,
/**
* Constant: MAX_ZOOM_LEVEL
* {Integer} 21
*/
MAX_ZOOM_LEVEL: 21,
/**
* Constant: RESOLUTIONS
* {Array(Float)} Hardcode these resolutions so that they are more closely
* tied with the standard wms projection
*/
RESOLUTIONS: [
1.40625,
0.703125,
0.3515625,
0.17578125,
0.087890625,
0.0439453125,
0.02197265625,
0.010986328125,
0.0054931640625,
0.00274658203125,
0.001373291015625,
0.0006866455078125,
0.00034332275390625,
0.000171661376953125,
0.0000858306884765625,
0.00004291534423828125,
0.00002145767211914062,
0.00001072883605957031,
0.00000536441802978515,
0.00000268220901489257,
0.0000013411045074462891,
0.00000067055225372314453
],
/**
* APIProperty: type
* {GMapType}
*/
type: null,
/**
* APIProperty: wrapDateLine
* {Boolean} Allow user to pan forever east/west. Default is true.
* Setting this to false only restricts panning if
* <sphericalMercator> is true.
*/
wrapDateLine: true,
/**
* APIProperty: sphericalMercator
* {Boolean} Should the map act as a mercator-projected map? This will
* cause all interactions with the map to be in the actual map
* projection, which allows support for vector drawing, overlaying
* other maps, etc.
*/
sphericalMercator: false,
/**
* Property: version
* {Number} The version of the Google Maps API
*/
version: null,
/**
* Constructor: OpenLayers.Layer.Google
*
* Parameters:
* name - {String} A name for the layer.
* options - {Object} An optional object whose properties will be set
* on the layer.
*/
initialize: function(name, options) {
options = options || {};
if(!options.version) {
options.version = typeof GMap2 === "function" ? "2" : "3";
}
var mixin = OpenLayers.Layer.Google["v" +
options.version.replace(/\./g, "_")];
if (mixin) {
OpenLayers.Util.applyDefaults(options, mixin);
} else {
throw "Unsupported Google Maps API version: " + options.version;
}
OpenLayers.Util.applyDefaults(options, mixin.DEFAULTS);
if (options.maxExtent) {
options.maxExtent = options.maxExtent.clone();
}
OpenLayers.Layer.EventPane.prototype.initialize.apply(this,
[name, options]);
OpenLayers.Layer.FixedZoomLevels.prototype.initialize.apply(this,
[name, options]);
if (this.sphericalMercator) {
OpenLayers.Util.extend(this, OpenLayers.Layer.SphericalMercator);
this.initMercatorParameters();
}
},
/**
* Method: clone
* Create a clone of this layer
*
* Returns:
* {<OpenLayers.Layer.Google>} An exact clone of this layer
*/
clone: function() {
/**
* This method isn't intended to be called by a subclass and it
* doesn't call the same method on the superclass. We don't call
* the super's clone because we don't want properties that are set
* on this layer after initialize (i.e. this.mapObject etc.).
*/
return new OpenLayers.Layer.Google(
this.name, this.getOptions()
);
},
/**
* APIMethod: setVisibility
* Set the visibility flag for the layer and hide/show & redraw
* accordingly. Fire event unless otherwise specified
*
* Note that visibility is no longer simply whether or not the layer's
* style.display is set to "block". Now we store a 'visibility' state
* property on the layer class, this allows us to remember whether or
* not we *desire* for a layer to be visible. In the case where the
* map's resolution is out of the layer's range, this desire may be
* subverted.
*
* Parameters:
* visible - {Boolean} Display the layer (if in range)
*/
setVisibility: function(visible) {
// sharing a map container, opacity has to be set per layer
var opacity = this.opacity == null ? 1 : this.opacity;
OpenLayers.Layer.EventPane.prototype.setVisibility.apply(this, arguments);
this.setOpacity(opacity);
},
/**
* APIMethod: display
* Hide or show the Layer
*
* Parameters:
* visible - {Boolean}
*/
display: function(visible) {
if (!this._dragging) {
this.setGMapVisibility(visible);
}
OpenLayers.Layer.EventPane.prototype.display.apply(this, arguments);
},
/**
* Method: moveTo
*
* Parameters:
* bounds - {<OpenLayers.Bounds>}
* zoomChanged - {Boolean} Tells when zoom has changed, as layers have to
* do some init work in that case.
* dragging - {Boolean}
*/
moveTo: function(bounds, zoomChanged, dragging) {
this._dragging = dragging;
OpenLayers.Layer.EventPane.prototype.moveTo.apply(this, arguments);
delete this._dragging;
},
/**
* APIMethod: setOpacity
* Sets the opacity for the entire layer (all images)
*
* Parameters:
* opacity - {Float}
*/
setOpacity: function(opacity) {
if (opacity !== this.opacity) {
if (this.map != null) {
this.map.events.triggerEvent("changelayer", {
layer: this,
property: "opacity"
});
}
this.opacity = opacity;
}
// Though this layer's opacity may not change, we're sharing a container
// and need to update the opacity for the entire container.
if (this.getVisibility()) {
var container = this.getMapContainer();
OpenLayers.Util.modifyDOMElement(
container, null, null, null, null, null, null, opacity
);
}
},
/**
* APIMethod: destroy
* Clean up this layer.
*/
destroy: function() {
/**
* We have to override this method because the event pane destroy
* deletes the mapObject reference before removing this layer from
* the map.
*/
if (this.map) {
this.setGMapVisibility(false);
var cache = OpenLayers.Layer.Google.cache[this.map.id];
if (cache && cache.count <= 1) {
this.removeGMapElements();
}
}
OpenLayers.Layer.EventPane.prototype.destroy.apply(this, arguments);
},
/**
* Method: removeGMapElements
* Remove all elements added to the dom. This should only be called if
* this is the last of the Google layers for the given map.
*/
removeGMapElements: function() {
var cache = OpenLayers.Layer.Google.cache[this.map.id];
if (cache) {
// remove shared elements from dom
var container = this.mapObject && this.getMapContainer();
if (container && container.parentNode) {
container.parentNode.removeChild(container);
}
var termsOfUse = cache.termsOfUse;
if (termsOfUse && termsOfUse.parentNode) {
termsOfUse.parentNode.removeChild(termsOfUse);
}
var poweredBy = cache.poweredBy;
if (poweredBy && poweredBy.parentNode) {
poweredBy.parentNode.removeChild(poweredBy);
}
if (this.mapObject && window.google && google.maps &&
google.maps.event && google.maps.event.clearListeners) {
google.maps.event.clearListeners(this.mapObject, 'tilesloaded');
}
}
},
/**
* APIMethod: removeMap
* On being removed from the map, also remove termsOfUse and poweredBy divs
*
* Parameters:
* map - {<OpenLayers.Map>}
*/
removeMap: function(map) {
// hide layer before removing
if (this.visibility && this.mapObject) {
this.setGMapVisibility(false);
}
// check to see if last Google layer in this map
var cache = OpenLayers.Layer.Google.cache[map.id];
if (cache) {
if (cache.count <= 1) {
this.removeGMapElements();
delete OpenLayers.Layer.Google.cache[map.id];
} else {
// decrement the layer count
--cache.count;
}
}
// remove references to gmap elements
delete this.termsOfUse;
delete this.poweredBy;
delete this.mapObject;
delete this.dragObject;
OpenLayers.Layer.EventPane.prototype.removeMap.apply(this, arguments);
},
//
// TRANSLATION: MapObject Bounds <-> OpenLayers.Bounds
//
/**
* APIMethod: getOLBoundsFromMapObjectBounds
*
* Parameters:
* moBounds - {Object}
*
* Returns:
* {<OpenLayers.Bounds>} An <OpenLayers.Bounds>, translated from the
* passed-in MapObject Bounds.
* Returns null if null value is passed in.
*/
getOLBoundsFromMapObjectBounds: function(moBounds) {
var olBounds = null;
if (moBounds != null) {
var sw = moBounds.getSouthWest();
var ne = moBounds.getNorthEast();
if (this.sphericalMercator) {
sw = this.forwardMercator(sw.lng(), sw.lat());
ne = this.forwardMercator(ne.lng(), ne.lat());
} else {
sw = new OpenLayers.LonLat(sw.lng(), sw.lat());
ne = new OpenLayers.LonLat(ne.lng(), ne.lat());
}
olBounds = new OpenLayers.Bounds(sw.lon,
sw.lat,
ne.lon,
ne.lat );
}
return olBounds;
},
/**
* APIMethod: getWarningHTML
*
* Returns:
* {String} String with information on why layer is broken, how to get
* it working.
*/
getWarningHTML:function() {
return OpenLayers.i18n("googleWarning");
},
/************************************
* *
* MapObject Interface Controls *
* *
************************************/
// Get&Set Center, Zoom
/**
* APIMethod: getMapObjectCenter
*
* Returns:
* {Object} The mapObject's current center in Map Object format
*/
getMapObjectCenter: function() {
return this.mapObject.getCenter();
},
/**
* APIMethod: getMapObjectZoom
*
* Returns:
* {Integer} The mapObject's current zoom, in Map Object format
*/
getMapObjectZoom: function() {
return this.mapObject.getZoom();
},
/************************************
* *
* MapObject Primitives *
* *
************************************/
// LonLat
/**
* APIMethod: getLongitudeFromMapObjectLonLat
*
* Parameters:
* moLonLat - {Object} MapObject LonLat format
*
* Returns:
* {Float} Longitude of the given MapObject LonLat
*/
getLongitudeFromMapObjectLonLat: function(moLonLat) {
return this.sphericalMercator ?
this.forwardMercator(moLonLat.lng(), moLonLat.lat()).lon :
moLonLat.lng();
},
/**
* APIMethod: getLatitudeFromMapObjectLonLat
*
* Parameters:
* moLonLat - {Object} MapObject LonLat format
*
* Returns:
* {Float} Latitude of the given MapObject LonLat
*/
getLatitudeFromMapObjectLonLat: function(moLonLat) {
var lat = this.sphericalMercator ?
this.forwardMercator(moLonLat.lng(), moLonLat.lat()).lat :
moLonLat.lat();
return lat;
},
// Pixel
/**
* APIMethod: getXFromMapObjectPixel
*
* Parameters:
* moPixel - {Object} MapObject Pixel format
*
* Returns:
* {Integer} X value of the MapObject Pixel
*/
getXFromMapObjectPixel: function(moPixel) {
return moPixel.x;
},
/**
* APIMethod: getYFromMapObjectPixel
*
* Parameters:
* moPixel - {Object} MapObject Pixel format
*
* Returns:
* {Integer} Y value of the MapObject Pixel
*/
getYFromMapObjectPixel: function(moPixel) {
return moPixel.y;
},
CLASS_NAME: "OpenLayers.Layer.Google"
});
/**
* Property: OpenLayers.Layer.Google.cache
* {Object} Cache for elements that should only be created once per map.
*/
OpenLayers.Layer.Google.cache = {};
/**
* Constant: OpenLayers.Layer.Google.v2
*
* Mixin providing functionality specific to the Google Maps API v2.
*
* This API has been deprecated by Google.
* Developers are encouraged to migrate to v3 of the API; support for this
* is provided by <OpenLayers.Layer.Google.v3>
*/
OpenLayers.Layer.Google.v2 = {
/**
* Property: termsOfUse
* {DOMElement} Div for Google's copyright and terms of use link
*/
termsOfUse: null,
/**
* Property: poweredBy
* {DOMElement} Div for Google's powered by logo and link
*/
poweredBy: null,
/**
* Property: dragObject
* {GDraggableObject} Since 2.93, Google has exposed the ability to get
* the maps GDraggableObject. We can now use this for smooth panning
*/
dragObject: null,
/**
* Method: loadMapObject
* Load the GMap and register appropriate event listeners. If we can't
* load GMap2, then display a warning message.
*/
loadMapObject:function() {
if (!this.type) {
this.type = G_NORMAL_MAP;
}
var mapObject, termsOfUse, poweredBy;
var cache = OpenLayers.Layer.Google.cache[this.map.id];
if (cache) {
// there are already Google layers added to this map
mapObject = cache.mapObject;
termsOfUse = cache.termsOfUse;
poweredBy = cache.poweredBy;
// increment the layer count
++cache.count;
} else {
// this is the first Google layer for this map
var container = this.map.viewPortDiv;
var div = document.createElement("div");
div.id = this.map.id + "_GMap2Container";
div.style.position = "absolute";
div.style.width = "100%";
div.style.height = "100%";
container.appendChild(div);
// create GMap and shuffle elements
try {
mapObject = new GMap2(div);
// move the ToS and branding stuff up to the container div
termsOfUse = div.lastChild;
container.appendChild(termsOfUse);
termsOfUse.style.zIndex = "1100";
termsOfUse.style.right = "";
termsOfUse.style.bottom = "";
termsOfUse.className = "olLayerGoogleCopyright";
poweredBy = div.lastChild;
container.appendChild(poweredBy);
poweredBy.style.zIndex = "1100";
poweredBy.style.right = "";
poweredBy.style.bottom = "";
poweredBy.className = "olLayerGooglePoweredBy gmnoprint";
} catch (e) {
throw(e);
}
// cache elements for use by any other google layers added to
// this same map
OpenLayers.Layer.Google.cache[this.map.id] = {
mapObject: mapObject,
termsOfUse: termsOfUse,
poweredBy: poweredBy,
count: 1
};
}
this.mapObject = mapObject;
this.termsOfUse = termsOfUse;
this.poweredBy = poweredBy;
// ensure this layer type is one of the mapObject types
if (OpenLayers.Util.indexOf(this.mapObject.getMapTypes(),
this.type) === -1) {
this.mapObject.addMapType(this.type);
}
//since v 2.93 getDragObject is now available.
if(typeof mapObject.getDragObject == "function") {
this.dragObject = mapObject.getDragObject();
} else {
this.dragPanMapObject = null;
}
if(this.isBaseLayer === false) {
this.setGMapVisibility(this.div.style.display !== "none");
}
},
/**
* APIMethod: onMapResize
*/
onMapResize: function() {
// workaround for resizing of invisible or not yet fully loaded layers
// where GMap2.checkResize() does not work. We need to load the GMap
// for the old div size, then checkResize(), and then call
// layer.moveTo() to trigger GMap.setCenter() (which will finish
// the GMap initialization).
if(this.visibility && this.mapObject.isLoaded()) {
this.mapObject.checkResize();
} else {
if(!this._resized) {
var layer = this;
var handle = GEvent.addListener(this.mapObject, "load", function() {
GEvent.removeListener(handle);
delete layer._resized;
layer.mapObject.checkResize();
layer.moveTo(layer.map.getCenter(), layer.map.getZoom());
});
}
this._resized = true;
}
},
/**
* Method: setGMapVisibility
* Display the GMap container and associated elements.
*
* Parameters:
* visible - {Boolean} Display the GMap elements.
*/
setGMapVisibility: function(visible) {
var cache = OpenLayers.Layer.Google.cache[this.map.id];
if (cache) {
var container = this.mapObject.getContainer();
if (visible === true) {
this.mapObject.setMapType(this.type);
container.style.display = "";
this.termsOfUse.style.left = "";
this.termsOfUse.style.display = "";
this.poweredBy.style.display = "";
cache.displayed = this.id;
} else {
if (cache.displayed === this.id) {
delete cache.displayed;
}
if (!cache.displayed) {
container.style.display = "none";
this.termsOfUse.style.display = "none";
// move ToU far to the left in addition to setting display
// to "none", because at the end of the GMap2 load
// sequence, display: none will be unset and ToU would be
// visible after loading a map with a google layer that is
// initially hidden.
this.termsOfUse.style.left = "-9999px";
this.poweredBy.style.display = "none";
}
}
}
},
/**
* Method: getMapContainer
*
* Returns:
* {DOMElement} the GMap container's div
*/
getMapContainer: function() {
return this.mapObject.getContainer();
},
//
// TRANSLATION: MapObject Bounds <-> OpenLayers.Bounds
//
/**
* APIMethod: getMapObjectBoundsFromOLBounds
*
* Parameters:
* olBounds - {<OpenLayers.Bounds>}
*
* Returns:
* {Object} A MapObject Bounds, translated from olBounds
* Returns null if null value is passed in
*/
getMapObjectBoundsFromOLBounds: function(olBounds) {
var moBounds = null;
if (olBounds != null) {
var sw = this.sphericalMercator ?
this.inverseMercator(olBounds.bottom, olBounds.left) :
new OpenLayers.LonLat(olBounds.bottom, olBounds.left);
var ne = this.sphericalMercator ?
this.inverseMercator(olBounds.top, olBounds.right) :
new OpenLayers.LonLat(olBounds.top, olBounds.right);
moBounds = new GLatLngBounds(new GLatLng(sw.lat, sw.lon),
new GLatLng(ne.lat, ne.lon));
}
return moBounds;
},
/************************************
* *
* MapObject Interface Controls *
* *
************************************/
// Get&Set Center, Zoom
/**
* APIMethod: setMapObjectCenter
* Set the mapObject to the specified center and zoom
*
* Parameters:
* center - {Object} MapObject LonLat format
* zoom - {int} MapObject zoom format
*/
setMapObjectCenter: function(center, zoom) {
this.mapObject.setCenter(center, zoom);
},
/**
* APIMethod: dragPanMapObject
*
* Parameters:
* dX - {Integer}
* dY - {Integer}
*/
dragPanMapObject: function(dX, dY) {
this.dragObject.moveBy(new GSize(-dX, dY));
},
// LonLat - Pixel Translation
/**
* APIMethod: getMapObjectLonLatFromMapObjectPixel
*
* Parameters:
* moPixel - {Object} MapObject Pixel format
*
* Returns:
* {Object} MapObject LonLat translated from MapObject Pixel
*/
getMapObjectLonLatFromMapObjectPixel: function(moPixel) {
return this.mapObject.fromContainerPixelToLatLng(moPixel);
},
/**
* APIMethod: getMapObjectPixelFromMapObjectLonLat
*
* Parameters:
* moLonLat - {Object} MapObject LonLat format
*
* Returns:
* {Object} MapObject Pixel transtlated from MapObject LonLat
*/
getMapObjectPixelFromMapObjectLonLat: function(moLonLat) {
return this.mapObject.fromLatLngToContainerPixel(moLonLat);
},
// Bounds
/**
* APIMethod: getMapObjectZoomFromMapObjectBounds
*
* Parameters:
* moBounds - {Object} MapObject Bounds format
*
* Returns:
* {Object} MapObject Zoom for specified MapObject Bounds
*/
getMapObjectZoomFromMapObjectBounds: function(moBounds) {
return this.mapObject.getBoundsZoomLevel(moBounds);
},
/************************************
* *
* MapObject Primitives *
* *
************************************/
// LonLat
/**
* APIMethod: getMapObjectLonLatFromLonLat
*
* Parameters:
* lon - {Float}
* lat - {Float}
*
* Returns:
* {Object} MapObject LonLat built from lon and lat params
*/
getMapObjectLonLatFromLonLat: function(lon, lat) {
var gLatLng;
if(this.sphericalMercator) {
var lonlat = this.inverseMercator(lon, lat);
gLatLng = new GLatLng(lonlat.lat, lonlat.lon);
} else {
gLatLng = new GLatLng(lat, lon);
}
return gLatLng;
},
// Pixel
/**
* APIMethod: getMapObjectPixelFromXY
*
* Parameters:
* x - {Integer}
* y - {Integer}
*
* Returns:
* {Object} MapObject Pixel from x and y parameters
*/
getMapObjectPixelFromXY: function(x, y) {
return new GPoint(x, y);
}
};
| bragma/cdnjs | ajax/libs/openlayers/2.13.1/lib/OpenLayers/Layer/Google.js | JavaScript | mit | 24,919 |
/* =============================================================
* bootstrap-scrollspy.js v2.3.1
* http://twitter.github.com/bootstrap/javascript.html#scrollspy
* =============================================================
* Copyright 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============================================================== */
!function ($) {
"use strict"; // jshint ;_;
/* SCROLLSPY CLASS DEFINITION
* ========================== */
function ScrollSpy(element, options) {
var process = $.proxy(this.process, this)
, $element = $(element).is('body') ? $(window) : $(element)
, href
this.options = $.extend({}, $.fn.scrollspy.defaults, options)
this.$scrollElement = $element.on('scroll.scroll-spy.data-api', process)
this.selector = (this.options.target
|| ((href = $(element).attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7
|| '') + ' .nav li > a'
this.$body = $('body')
this.refresh()
this.process()
}
ScrollSpy.prototype = {
constructor: ScrollSpy
, refresh: function () {
var self = this
, $targets
this.offsets = $([])
this.targets = $([])
$targets = this.$body
.find(this.selector)
.map(function () {
var $el = $(this)
, href = $el.data('target') || $el.attr('href')
, $href = /^#\w/.test(href) && $(href)
return ( $href
&& $href.length
&& [[ $href.position().top + (!$.isWindow(self.$scrollElement.get(0)) && self.$scrollElement.scrollTop()), href ]] ) || null
})
.sort(function (a, b) { return a[0] - b[0] })
.each(function () {
self.offsets.push(this[0])
self.targets.push(this[1])
})
}
, process: function () {
var scrollTop = this.$scrollElement.scrollTop() + this.options.offset
, scrollHeight = this.$scrollElement[0].scrollHeight || this.$body[0].scrollHeight
, maxScroll = scrollHeight - this.$scrollElement.height()
, offsets = this.offsets
, targets = this.targets
, activeTarget = this.activeTarget
, i
if (scrollTop >= maxScroll) {
return activeTarget != (i = targets.last()[0])
&& this.activate ( i )
}
for (i = offsets.length; i--;) {
activeTarget != targets[i]
&& scrollTop >= offsets[i]
&& (!offsets[i + 1] || scrollTop <= offsets[i + 1])
&& this.activate( targets[i] )
}
}
, activate: function (target) {
var active
, selector
this.activeTarget = target
$(this.selector)
.parent('.active')
.removeClass('active')
selector = this.selector
+ '[data-target="' + target + '"],'
+ this.selector + '[href="' + target + '"]'
active = $(selector)
.parent('li')
.addClass('active')
if (active.parent('.dropdown-menu').length) {
active = active.closest('li.dropdown').addClass('active')
}
active.trigger('activate')
}
}
/* SCROLLSPY PLUGIN DEFINITION
* =========================== */
var old = $.fn.scrollspy
$.fn.scrollspy = function (option) {
return this.each(function () {
var $this = $(this)
, data = $this.data('scrollspy')
, options = typeof option == 'object' && option
if (!data) $this.data('scrollspy', (data = new ScrollSpy(this, options)))
if (typeof option == 'string') data[option]()
})
}
$.fn.scrollspy.Constructor = ScrollSpy
$.fn.scrollspy.defaults = {
offset: 10
}
/* SCROLLSPY NO CONFLICT
* ===================== */
$.fn.scrollspy.noConflict = function () {
$.fn.scrollspy = old
return this
}
/* SCROLLSPY DATA-API
* ================== */
$(window).on('load', function () {
$('[data-spy="scroll"]').each(function () {
var $spy = $(this)
$spy.scrollspy($spy.data())
})
})
}(window.jQuery); | babiola/dasaac | assets/plugins1/jasny/docs/assets/js/bootstrap-scrollspy.js | JavaScript | mit | 4,655 |
html {
font-family: sans-serif;
background-color: #335;
font-size: 16px;
}
body {
}
h1 {
text-align: center;
font-size: 20px;
color: #fff;
padding: 10px 10px 20px 10px;
}
h2 {
border-bottom: 1px solid black;
display: block;
font-size: 18px;
}
div#main {
width: 600px;
margin: 0px auto 0px auto;
padding: 0px;
background-color: #fff;
height: 460px;
}
div#warnings {
color: red;
font-weight: bold;
margin: 10px;
}
div#join-section {
float: left;
margin: 10px;
}
div#users-section {
width: 170px;
float: right;
padding: 0px;
margin: 10px;
}
ul#users {
list-style-type: none;
padding-left: 0px;
height: 300px;
overflow: auto;
}
div#chat-section {
width: 390px;
float: left;
margin: 10px;
}
div#messages {
margin: 0px;
height: 300px;
overflow: auto;
}
div#messages p {
margin: 0px;
padding: 0px;
}
div#footer {
text-align: center;
font-size: 12px;
color: #fff;
margin: 10px 0px 30px 0px;
}
div#footer a {
color: #fff;
}
div.clear {
clear: both;
}
| frontrowed/wai | wai-websockets/static/screen.css | CSS | mit | 1,124 |
<!--
Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->
<!--
`paper-slider` allows user to select a value from a range of values by
moving the slider thumb. The interactive nature of the slider makes it a
great choice for settings that reflect intensity levels, such as volume,
brightness, or color saturation.
Example:
<paper-slider></paper-slider>
Use `min` and `max` to specify the slider range. Default is 0 to 100.
Example:
<paper-slider min="10" max="200" value="110"></paper-slider>
Styling slider:
To change the slider progress bar color:
paper-slider::shadow #sliderBar::shadow #activeProgress {
background-color: #0f9d58;
}
To change the slider knob color:
paper-slider::shadow #sliderKnobInner {
background-color: #0f9d58;
}
To change the slider pin color:
paper-slider::shadow #sliderKnobInner::before {
background-color: #0f9d58;
}
To change the slider pin's font color:
paper-slider::shadow #sliderKnob > #sliderKnobInner::after {
color: #0f9d58
}
To change the slider secondary progress bar color:
paper-slider::shadow #sliderBar::shadow #secondaryProgress {
background-color: #0f9d58;
}
@group Paper Elements
@element paper-slider
@extends core-range
@homepage github.io
-->
<link rel="import" href="../core-a11y-keys/core-a11y-keys.html">
<link rel="import" href="../paper-progress/paper-progress.html">
<link rel="import" href="../paper-input/paper-input.html">
<polymer-element name="paper-slider" extends="core-range" attributes="snaps pin disabled secondaryProgress editable immediateValue" role="slider" tabindex="0" aria-valuemin="0" aria-valuemax="100">
<template>
<link rel="stylesheet" href="paper-slider.css">
<template if="{{!disabled}}">
<core-a11y-keys target="{{}}" keys="left down pagedown home" on-keys-pressed="{{decrementKey}}"></core-a11y-keys>
<core-a11y-keys target="{{}}" keys="right up pageup end" on-keys-pressed="{{incrementKey}}"></core-a11y-keys>
</template>
<div id="sliderContainer" class="{{ {disabled: disabled, pin: pin, snaps: snaps, ring: immediateValue <= min, expand: expand, dragging: dragging, transiting: transiting, editable: editable} | tokenList }}">
<div class="bar-container">
<paper-progress id="sliderBar" aria-hidden="true" min="{{min}}" max="{{max}}" value="{{immediateValue}}" secondaryProgress="{{secondaryProgress}}"
on-down="{{bardown}}" on-up="{{resetKnob}}"
on-trackstart="{{trackStart}}" on-trackx="{{trackx}}" on-trackend="{{trackEnd}}"></paper-progress>
</div>
<template if="{{snaps && !disabled}}">
<div class="slider-markers" horizontal layout>
<template repeat="{{markers}}">
<div flex class="slider-marker"></div>
</template>
</div>
</template>
<div id="sliderKnob" on-down="{{knobdown}}" on-up="{{resetKnob}}"
on-trackstart="{{trackStart}}" on-trackx="{{trackx}}" on-trackend="{{trackEnd}}"
on-transitionend="{{knobTransitionEnd}}"
center-justified center horizontal layout>
<div id="sliderKnobInner" value="{{immediateValue}}"></div>
</div>
</div>
<template if="{{editable}}">
<paper-input id="input" class="slider-input" value="{{immediateValue}}" disabled?="{{disabled}}" on-change="{{inputChange}}"></paper-input>
</template>
</template>
<script>
Polymer('paper-slider', {
/**
* Fired when the slider's value changes.
*
* @event core-change
*/
/**
* Fired when the slider's value changes due to user interaction.
*
* Changes to the slider's value due to changes in an underlying
* bound variable will not trigger this event.
*
* @event change
*/
/**
* If true, the slider thumb snaps to tick marks evenly spaced based
* on the `step` property value.
*
* @attribute snaps
* @type boolean
* @default false
*/
snaps: false,
/**
* If true, a pin with numeric value label is shown when the slider thumb
* is pressed. Use for settings for which users need to know the exact
* value of the setting.
*
* @attribute pin
* @type boolean
* @default false
*/
pin: false,
/**
* If true, this slider is disabled. A disabled slider cannot be tapped
* or dragged to change the slider value.
*
* @attribute disabled
* @type boolean
* @default false
*/
disabled: false,
/**
* The number that represents the current secondary progress.
*
* @attribute secondaryProgress
* @type number
* @default 0
*/
secondaryProgress: 0,
/**
* If true, an input is shown and user can use it to set the slider value.
*
* @attribute editable
* @type boolean
* @default false
*/
editable: false,
/**
* The immediate value of the slider. This value is updated while the user
* is dragging the slider.
*
* @attribute immediateValue
* @type number
* @default 0
*/
maxMarkers: 100,
observe: {
'step snaps': 'update'
},
ready: function() {
this.update();
},
update: function() {
this.positionKnob(this.calcRatio(this.value));
this.updateMarkers();
},
minChanged: function() {
this.update();
this.setAttribute('aria-valuemin', this.min);
},
maxChanged: function() {
this.update();
this.setAttribute('aria-valuemax', this.max);
},
valueChanged: function() {
this.update();
this.setAttribute('aria-valuenow', this.value);
this.fire('core-change');
},
disabledChanged: function() {
if (this.disabled) {
this.removeAttribute('tabindex');
} else {
this.tabIndex = 0;
}
},
immediateValueChanged: function() {
if (!this.dragging) {
this.value = this.immediateValue;
}
},
expandKnob: function() {
this.expand = true;
},
resetKnob: function() {
this.expandJob && this.expandJob.stop();
this.expand = false;
},
positionKnob: function(ratio) {
this.immediateValue = this.calcStep(this.calcKnobPosition(ratio)) || 0;
this._ratio = this.snaps ? this.calcRatio(this.immediateValue) : ratio;
this.$.sliderKnob.style.left = this._ratio * 100 + '%';
},
inputChange: function() {
this.value = this.$.input.value;
this.fire('change');
},
calcKnobPosition: function(ratio) {
return (this.max - this.min) * ratio + this.min;
},
trackStart: function(e) {
this._w = this.$.sliderBar.offsetWidth;
this._x = this._ratio * this._w;
this._startx = this._x || 0;
this._minx = - this._startx;
this._maxx = this._w - this._startx;
this.$.sliderKnob.classList.add('dragging');
this.dragging = true;
e.preventTap();
},
trackx: function(e) {
var x = Math.min(this._maxx, Math.max(this._minx, e.dx));
this._x = this._startx + x;
this.immediateValue = this.calcStep(
this.calcKnobPosition(this._x / this._w)) || 0;
var s = this.$.sliderKnob.style;
s.transform = s.webkitTransform = 'translate3d(' + (this.snaps ?
(this.calcRatio(this.immediateValue) * this._w) - this._startx : x) + 'px, 0, 0)';
},
trackEnd: function() {
var s = this.$.sliderKnob.style;
s.transform = s.webkitTransform = '';
this.$.sliderKnob.classList.remove('dragging');
this.dragging = false;
this.resetKnob();
this.value = this.immediateValue;
this.fire('change');
},
knobdown: function(e) {
e.preventDefault();
this.expandKnob();
},
bardown: function(e) {
e.preventDefault();
this.transiting = true;
this._w = this.$.sliderBar.offsetWidth;
var rect = this.$.sliderBar.getBoundingClientRect();
var ratio = (e.x - rect.left) / this._w;
this.positionKnob(ratio);
this.expandJob = this.job(this.expandJob, this.expandKnob, 60);
this.fire('change');
},
knobTransitionEnd: function(e) {
if (e.target === this.$.sliderKnob) {
this.transiting = false;
}
},
updateMarkers: function() {
this.markers = [], l = (this.max - this.min) / this.step;
if (!this.snaps && l > this.maxMarkers) {
return;
}
for (var i = 0; i < l; i++) {
this.markers.push('');
}
},
increment: function() {
this.value = this.clampValue(this.value + this.step);
},
decrement: function() {
this.value = this.clampValue(this.value - this.step);
},
incrementKey: function(ev, keys) {
if (keys.key === "end") {
this.value = this.max;
} else {
this.increment();
}
this.fire('change');
},
decrementKey: function(ev, keys) {
if (keys.key === "home") {
this.value = this.min;
} else {
this.decrement();
}
this.fire('change');
}
});
</script>
</polymer-element>
| chuycepeda/polymer-elements | bower_components/paper-slider/paper-slider.html | HTML | mit | 9,594 |
/*Copyright (c) 2014, TT Labs, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
Neither the name of the TT Labs, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.*/
/***************************************************************************************************
* *
* version 1.2.0 *
* *
***************************************************************************************************/
(function () {
var FAR_FUTURE = new Date('2060-10-22');
var Evaporate = function (config) {
var PENDING = 0, EVAPORATING = 2, COMPLETE = 3, PAUSED = 4, CANCELED = 5, ERROR = 10, ABORTED = 20, AWS_URL = config.aws_url || 'https://s3.amazonaws.com', ETAG_OF_0_LENGTH_BLOB = '"d41d8cd98f00b204e9800998ecf8427e"';
var _ = this;
var files = [];
function noOpLogger() { return {d: function () {}, w: function () {}, e: function () {}}; }
var l = noOpLogger();
var con = extend({
logging: true,
maxConcurrentParts: 5,
partSize: 6 * 1024 * 1024,
retryBackoffPower: 2,
maxRetryBackoffSecs: 300,
progressIntervalMS: 500,
cloudfront: false,
encodeFilename: true,
computeContentMd5: false,
allowS3ExistenceOptimization: false,
onlyRetryForSameFileName: false,
timeUrl: null,
cryptoMd5Method: null,
s3FileCacheHoursAgo: null, // Must be a whole number of hours. Will be interpreted as negative (hours in the past).
signParams:{},
signHeaders: {},
awsLambda: null,
awsLambdaFunction: null,
maxFileSize: null,
// undocumented
testUnsupported: false,
simulateStalling: false,
simulateErrors: false
}, config);
if (console && console.log) {
l = console;
l.d = l.log;
l.w = console.warn ? l.warn : l.d;
l.e = console.error ? l.error : l.d;
}
this.supported = !(
typeof File === 'undefined' ||
typeof Blob === 'undefined' ||
typeof (
Blob.prototype['webkitSlice'] ||
Blob.prototype['mozSlice']||
Blob.prototype['slice']) === 'undefined' ||
!!config.testUnsupported);
if (!this.supported) {
l.e('The browser does not support the necessary features of File and Blob [webkitSlice || mozSlice || slice]');
return;
}
if (con.computeContentMd5) {
this.supported = typeof FileReader.prototype.readAsArrayBuffer !== 'undefined';
if (!this.supported) {
l.e('The browser\'s FileReader object does not support readAsArrayBuffer');
return;
}
if (typeof con.cryptoMd5Method !== 'function') {
l.e('Option computeContentMd5 has been set but cryptoMd5Method is not defined.');
return;
}
}
if (!con.logging) {
// Reset the logger to be a no_op
l = noOpLogger();
}
var historyCache = {
supported: (function () {
var result = false;
if (typeof window !== 'undefined') {
if (!('localStorage' in window)) {
return result;
}
} else {
return result;
}
// Try to use storage (it might be disabled, e.g. user is in private mode)
try {
localStorage.setItem('___test', 'OK');
var test = localStorage.getItem('___test');
localStorage.removeItem('___test');
result = test === 'OK';
} catch (e) {
return result;
}
return result;
})(),
getItem: function (key) {
if (this.supported) {
return localStorage.getItem(key)
}
},
setItem: function (key, value) {
if (this.supported) {
return localStorage.setItem(key, value);
}
},
clear: function () {
if (this.supported) {
return localStorage.clear();
}
},
key: function (key) {
if (this.supported) {
return localStorage.key(key);
}
},
removeItem: function (key) {
if (this.supported) {
return localStorage.removeItem(key);
}
}
};
var _d = new Date(),
HOURS_AGO = new Date(_d.setHours(_d.getHours() - (con.s3FileCacheHoursAgo || -100))),
localTimeOffset = 0;
if (con.timeUrl) {
var xhr = new XMLHttpRequest();
xhr.open("GET", con.timeUrl + '?requestTime=' + new Date().getTime());
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
var server_date = new Date(Date.parse(xhr.responseText)),
now = new Date();
localTimeOffset = now - server_date;
l.d('localTimeOsset is', localTimeOffset, 'ms');
}
}
};
xhr.onerror = function () {
l.e('xhr error timeUrl', xhr);
};
xhr.send();
}
//con.simulateStalling = true
_.add = function (file) {
l.d('add');
var err;
if (typeof file === 'undefined') {
return 'Missing file';
}
if (con.maxFileSize && file.size > con.maxFileSize) {
return 'File size too large. Maximum size allowed is ' + con.maxFileSize;
}
if (typeof file.name === 'undefined') {
err = 'Missing attribute: name ';
} else if (con.encodeFilename) {
file.name = encodeURIComponent(file.name); // prevent signature fail in case file name has spaces
}
/*if (!(file.file instanceof File)){
err += '.file attribute must be instanceof File';
}*/
if (err) { return err; }
var newId = addFile(file);
asynProcessQueue();
return newId;
};
_.cancel = function (id) {
l.d('cancel ', id);
if (files[id]) {
files[id].stop();
return true;
} else {
return false;
}
};
_.pause = function (id) {};
_.resume = function (id) {};
_.forceRetry = function () {};
function addFile(file) {
var id = files.length;
files.push(new FileUpload(extend({
progress: function () {},
complete: function () {},
cancelled: function () {},
info: function () {},
warn: function () {},
error: function () {}
}, file, {
id: id,
status: PENDING,
priority: 0,
onStatusChange: onFileUploadStatusChange,
loadedBytes: 0,
sizeBytes: file.file.size,
eTag: ''
})));
return id;
}
function onFileUploadStatusChange() {
l.d('onFileUploadStatusChange');
processQueue();
}
function asynProcessQueue() {
setTimeout(processQueue,1);
}
function processQueue() {
l.d('processQueue length: ' + files.length);
var next = -1, priorityOfNext = -1, readyForNext = true;
files.forEach(function (file, i) {
if (file.priority > priorityOfNext && file.status === PENDING) {
next = i;
priorityOfNext = file.priority;
}
if (file.status === EVAPORATING) {
readyForNext = false;
}
});
if (readyForNext && next >= 0) {
files[next].start();
}
}
function FileUpload(file) {
var me = this, parts = [], completedParts = [], progressTotalInterval, progressPartsInterval, countUploadAttempts = 0,
countInitiateAttempts = 0, countCompleteAttempts = 0;
extend(me,file);
me.start = function () {
l.d('starting FileUpload ' + me.id);
setStatus(EVAPORATING);
var awsKey = me.name;
getUnfinishedFileUpload();
if (typeof me.uploadId === 'undefined') {
initiateUpload(awsKey);
} else {
if (typeof me.eTag === 'undefined' || !me.firstMd5Digest) {
getUploadParts(0);
} else {
var reader = new FileReader();
reader.onloadend = function () {
var md5_digest = con.cryptoMd5Method.call(this, this.result);
if (con.allowS3ExistenceOptimization && me.firstMd5Digest === md5_digest) {
headObject(awsKey);
} else {
me.firstMd5Digest = md5_digest; // let's store the digest to avoid having to calculate it again
initiateUpload(awsKey);
}
};
reader.readAsArrayBuffer(getFilePart(me.file, 0, con.partSize));
}
}
};
me.stop = function () {
l.d('stopping FileUpload ', me.id);
me.cancelled();
setStatus(CANCELED);
me.info('Canceling uploads...');
cancelAllRequests();
};
function setStatus(s) {
if (s === COMPLETE || s === ERROR || s === CANCELED) {
clearInterval(progressTotalInterval);
clearInterval(progressPartsInterval);
}
me.status = s;
me.onStatusChange();
}
function cancelAllRequests() {
l.d('cancelAllRequests()');
for (var i = 1; i < parts.length; i++) {
abortPart(i, true);
}
abortUpload();
}
function processFileParts() {
if (con.computeContentMd5 && me.file.size > 0) {
processPartsListWithMd5Digests();
} else {
createUploadFile();
processPartsList();
}
}
function initiateUpload(awsKey) { // see: http://docs.amazonwebservices.com/AmazonS3/latest/API/mpUploadInitiate.html
var initiate = {
method: 'POST',
path: getPath() + '?uploads',
step: 'initiate',
x_amz_headers: me.xAmzHeadersAtInitiate,
not_signed_headers: me.notSignedHeadersAtInitiate
},
originalStatus = me.status,
hasErrored;
if (me.contentType) {
initiate.contentType = me.contentType;
}
initiate.onErr = function (xhr) {
if (hasErrored || me.status === ABORTED || me.status === CANCELED) {
return;
}
hasErrored = true;
l.d('onInitiateError for FileUpload ' + me.id);
me.warn('Error initiating upload');
setStatus(ERROR);
xhr.abort();
setTimeout(function () {
if (me.status !== ABORTED && me.status !== CANCELED) {
me.status = originalStatus;
initiateUpload(awsKey);
}
}, backOffWait(countInitiateAttempts++));
};
initiate.on200 = function (xhr) {
var match = xhr.response.match(/<UploadId>(.+)<\/UploadId>/);
if (match && match[1]) {
me.uploadId = match[1];
me.awsKey = awsKey;
l.d('requester success. got uploadId ' + me.uploadId);
makeParts();
processFileParts();
} else {
initiate.onErr();
}
};
setupRequest(initiate);
authorizedSend(initiate);
monitorProgress();
}
function uploadPart(partNumber) { //http://docs.amazonwebservices.com/AmazonS3/latest/API/mpUploadUploadPart.html
var backOff, hasErrored, upload, part;
part = parts[partNumber];
part.status = EVAPORATING;
countUploadAttempts++;
part.loadedBytesPrevious = null;
backOff = backOffWait(part.attempts++);
l.d('uploadPart #' + partNumber + ' will wait ' + backOff + 'ms to try');
function getAwsResponse(xhr) {
var oParser = new DOMParser(),
oDOM = oParser.parseFromString(xhr.responseText, "text/xml"),
code = oDOM.getElementsByTagName("Code"),
msg = oDOM.getElementsByTagName("Message");
code = code.length ? code[0].innerHTML : '';
msg = msg.length ? msg[0].innerHTML : '';
return code.length ? {code: code, msg: msg} : {};
}
upload = {
method: 'PUT',
path: getPath() + '?partNumber=' + partNumber + '&uploadId=' + me.uploadId,
step: 'upload #' + partNumber,
x_amz_headers: me.xAmzHeadersAtUpload,
md5_digest: part.md5_digest,
attempts: part.attempts,
part: part
};
upload.onErr = function (xhr, isOnError) {
if (me.status === CANCELED || me.status === ABORTED) {
return;
}
var msg = 'problem uploading part #' + partNumber + ', http status: ' + xhr.status +
', hasErrored: ' + !!hasErrored + ', part status: ' + part.status +
', readyState: ' + xhr.readyState + (isOnError ? ', isOnError' : '');
l.w(msg);
me.warn(msg);
if (hasErrored) {
return;
}
hasErrored = true;
if (xhr.status === 404) {
var errMsg = '404 error resulted in abortion of both this part and the entire file.';
l.w(errMsg + ' Server response: ' + xhr.response);
me.error(errMsg);
part.status = ABORTED;
abortUpload();
} else {
part.status = ERROR;
part.loadedBytes = 0;
var awsResponse = getAwsResponse(xhr);
if (awsResponse.code) {
l.e('AWS Server response: code="' + awsResponse.code + '", message="' + awsResponse.msg + '"');
}
processPartsList();
}
xhr.abort();
};
upload.on200 = function (xhr) {
var eTag = xhr.getResponseHeader('ETag'), msg;
l.d('uploadPart 200 response for part #' + partNumber + ' ETag: ' + eTag);
if (part.isEmpty || (eTag !== ETAG_OF_0_LENGTH_BLOB)) { // issue #58
part.eTag = eTag;
part.status = COMPLETE;
} else {
part.status = ERROR;
part.loadedBytes = 0;
msg = 'eTag matches MD5 of 0 length blob for part #' + partNumber + ' Retrying part.';
l.w(msg);
me.warn(msg);
}
processPartsList();
};
upload.onProgress = function (evt) {
part.loadedBytes = evt.loaded;
};
upload.toSend = function () {
var slice = getFilePart(me.file, part.start, part.end);
l.d('part # ' + partNumber + ' (bytes ' + part.start + ' -> ' + part.end + ') reported length: ' + slice.size);
if (!part.isEmpty && slice.size === 0) { // issue #58
l.w(' *** WARN: blob reporting size of 0 bytes. Will try upload anyway..');
}
return slice;
};
upload.onFailedAuth = function () {
var msg = 'onFailedAuth for uploadPart #' + partNumber + '. Will set status to ERROR';
l.w(msg);
me.warn(msg);
part.status = ERROR;
part.loadedBytes = 0;
processPartsList();
};
setupRequest(upload);
setTimeout(function () {
if (me.status !== ABORTED && me.status !== CANCELED) {
authorizedSend(upload);
l.d('upload #', partNumber, upload);
}
}, backOff);
part.uploader = upload;
}
function abortPart(partNumber, clearReadyStateCallback) {
var part = parts[partNumber];
if (part.currentXhr) {
if (!!clearReadyStateCallback) {
part.currentXhr.onreadystatechange = function () {};
}
part.currentXhr.abort();
}
}
function completeUpload() { //http://docs.amazonwebservices.com/AmazonS3/latest/API/mpUploadComplete.html
l.d('completeUpload');
me.info('will attempt to complete upload');
var completeDoc = [],
originalStatus = me.status,
hasErrored;
completeDoc.push('<CompleteMultipartUpload>');
parts.forEach(function (part, partNumber) {
if (part) {
completeDoc.push(['<Part><PartNumber>', partNumber, '</PartNumber><ETag>', part.eTag, '</ETag></Part>'].join(""));
}
});
completeDoc.push('</CompleteMultipartUpload>');
var complete = {
method: 'POST',
contentType: 'application/xml; charset=UTF-8',
path: getPath() + '?uploadId=' + me.uploadId,
x_amz_headers: me.xAmzHeadersAtComplete,
step: 'complete'
};
complete.onErr = function (xhr) {
if (hasErrored || me.status === ABORTED || me.status === CANCELED) {
return;
}
hasErrored = true;
var msg = 'Error completing upload.';
l.w(msg);
me.error(msg);
setStatus(ERROR);
xhr.abort();
setTimeout(function () {
if (me.status !== ABORTED && me.status !== CANCELED) {
me.status = originalStatus;
completeUpload();
monitorProgress();
}
}, backOffWait(countCompleteAttempts++));
};
complete.on200 = function (xhr) {
var oDOM = parseXml(xhr.responseText),
result = oDOM.getElementsByTagName("CompleteMultipartUploadResult")[0];
me.eTag = nodeValue(result, "ETag");
me.complete(xhr, me.name);
completeUploadFile();
};
complete.toSend = function () {
return completeDoc.join("");
};
setupRequest(complete);
authorizedSend(complete);
}
function headObject(awsKey) { //http://docs.amazonwebservices.com/AmazonS3/latest/API/mpUploadComplete.html
l.d('headObject');
me.info('will attempt to verify existence of the file');
var head_object = {
method: 'HEAD',
path: getPath(),
step: 'head_object'
};
head_object.onErr = function () {
var msg = 'Error completing head object. Will re-upload file.';
l.w(msg);
initiateUpload(awsKey);
};
head_object.on200 = function (xhr) {
var eTag = xhr.getResponseHeader('Etag');
if (eTag === me.eTag) {
l.d('headObject found matching object on S3.');
me.progress(1.0);
me.complete(xhr, me.name);
setStatus(COMPLETE);
} else {
l.d('headObject not found on S3.');
initiateUpload(awsKey);
}
};
setupRequest(head_object);
authorizedSend(head_object);
}
var numDigestsProcessed = 0,
numParts = -1;
function computePartMd5Digest(part) {
return function () {
var s = me.status;
if (s === ERROR || s === CANCELED || s === ABORTED) {
return;
}
var md5_digest = con.cryptoMd5Method.call(this, this.result);
l.d(['part #', part.part, ' MD5 digest is ', md5_digest].join(''));
part.md5_digest = md5_digest;
if (part.part === 1) {
createUploadFile();
}
delete part.reader; // release potentially large memory allocation
numDigestsProcessed += 1;
processPartsList();
if (numDigestsProcessed === numParts) {
l.d('All parts have MD5 digests');
}
setTimeout(processPartsListWithMd5Digests, 1500);
}
}
function processPartsListWithMd5Digests() {
// We need the request body to compute the MD5 checksum but the body is only available
// as a FileReader object whose value is fetched asynchronously.
// This method delays submitting the part for upload until its MD5 digest is ready
for (var i = 1; i <= numParts; i++) {
var part = parts[i];
if (part.status !== COMPLETE && part.md5_digest === null) {
if (i > 1 || typeof me.firstMd5Digest === 'undefined') {
part.reader = new FileReader();
part.reader.onloadend = computePartMd5Digest(part);
part.reader.readAsArrayBuffer(getFilePart(me.file, part.start, part.end));
break;
} else { // We already calculated the first part's md5_digest
part.md5_digest = me.firstMd5Digest;
createUploadFile();
processPartsList();
}
}
}
}
function abortUpload() { //http://docs.amazonwebservices.com/AmazonS3/latest/API/mpUploadAbort.html
l.d('abortUpload');
me.info('will attempt to abort the upload');
var abort = {
method: 'DELETE',
path: getPath() + '?uploadId=' + me.uploadId,
step: 'abort',
successStatus: 204
};
abort.onErr = function () {
var msg = 'Error aborting upload.';
l.w(msg);
me.error(msg);
};
abort.on200 = function () {
setStatus(ABORTED);
checkForParts();
};
setupRequest(abort);
authorizedSend(abort);
}
function checkForParts() { //http://docs.amazonwebservices.com/AmazonS3/latest/API/mpUploadListParts.html
l.d('listParts');
me.info('list parts');
var list = {
method: 'GET',
path: getPath() + '?uploadId=' + me.uploadId,
step: 'list'
};
list.onErr = function (xhr) {
if (xhr.status === 404) {
// Success! Parts are not found because the uploadid has been cleared
removeUploadFile();
me.info('upload canceled');
} else {
var msg = 'Error listing parts.';
l.w(msg);
me.error(msg);
}
};
list.on200 = function (xhr) {
var oDOM = parseXml(xhr.responseText);
var parts = oDOM.getElementsByTagName("Part");
if (parts.length) { // Some parts are still uploading
l.d('Parts still found after abort...waiting.');
setTimeout(function () { abortUpload(); }, 1000);
} else {
me.info('upload canceled');
}
};
setupRequest(list);
authorizedSend(list);
}
function getUploadParts(partNumberMarker) { //http://docs.amazonwebservices.com/AmazonS3/latest/API/mpUploadListParts.html
l.d('getUploadParts() for uploadId starting at part # ' + partNumberMarker);
me.info('getUploadParts() for uploadId starting at part # ' + partNumberMarker);
var list = {
method: 'GET',
path: getPath() + '?uploadId=' + me.uploadId,
query_string: "&part-number-marker=" + partNumberMarker,
step: 'get upload parts'
};
list.onErr = function (xhr) {
if (xhr.status === 404) {
// Success! Upload is no longer recognized, so there is nothing to fetch
me.info(['uploadId ', me.uploadId, ' does not exist.'].join(''));
removeUploadFile();
monitorProgress();
makeParts();
processPartsList();
} else {
var msg = 'Error listing parts for getUploadParts() starting at part # ' + partNumberMarker;
l.w(msg);
me.error(msg);
}
};
list.on200 = function (xhr) {
me.info(['uploadId ', me.uploadId, ' is not complete. Fetching parts from part marker=', partNumberMarker].join(''));
var oDOM = parseXml(xhr.responseText),
listPartsResult = oDOM.getElementsByTagName("ListPartsResult")[0],
isTruncated = nodeValue(listPartsResult, "IsTruncated") === 'true',
uploadedParts = oDOM.getElementsByTagName("Part"),
uploadedPart,
parts_len = uploadedParts.length,
cp;
for (var i = 0; i < parts_len; i++) {
cp = uploadedParts[i];
completedParts.push({
eTag: nodeValue(cp, "ETag"),
partNumber: parseInt(nodeValue(cp, "PartNumber")),
size: parseInt(nodeValue(cp, "Size")),
LastModified: nodeValue(cp, "LastModified")
});
}
oDOM = uploadedParts = null; // We don't need these potentially large objects any longer
if (isTruncated) {
var nextPartNumberMarker = nodeValue(listPartsResult, "NextPartNumberMarker");
getUploadParts(nextPartNumberMarker); // let's fetch the next set of parts
} else {
makeParts();
completedParts.forEach(function (cp) {
uploadedPart = makePart(cp.partNumber, COMPLETE, cp.size);
uploadedPart.eTag = cp.eTag;
uploadedPart.attempts = 1;
uploadedPart.loadedBytes = cp.size;
uploadedPart.loadedBytesPrevious = cp.size;
uploadedPart.finishedUploadingAt = cp.LastModified;
uploadedPart.md5_digest = 'n/a';
parts[cp.partNumber] = uploadedPart;
});
monitorProgress();
processFileParts();
}
listPartsResult = null; // We don't need these potentially large object any longer
};
setupRequest(list);
authorizedSend(list);
}
function makeParts() {
numParts = Math.ceil(me.file.size / con.partSize) || 1; // issue #58
for (var part = 1; part <= numParts; part++) {
var status = (typeof parts[part] === 'undefined') ? PENDING : parts[part].status;
if (status !== COMPLETE) {
parts[part] = makePart(part, PENDING, me.file.size);
}
}
}
function makePart(partNumber, status, size) {
return {
status: status,
start: (partNumber - 1) * con.partSize,
end: partNumber * con.partSize,
attempts: 0,
loadedBytes: 0,
loadedBytesPrevious: null,
isEmpty: (size === 0), // issue #58
md5_digest: null,
part: partNumber
};
}
function createUploadFile() {
var fileKey = uploadKey(me),
newUpload = {
awsKey: me.name,
bucket: con.bucket,
uploadId: me.uploadId,
fileSize: me.file.size,
fileType: me.file.type,
lastModifiedDate: dateISOString(me.file.lastModifiedDate),
partSize: con.partSize,
signParams: me.signParams,
createdAt: new Date().toISOString()
};
if (con.computeContentMd5 && parts.length && typeof parts[1].md5_digest !== 'undefined') {
newUpload.firstMd5Digest = parts[1].md5_digest;
}
saveUpload(fileKey, newUpload);
}
function completeUploadFile() {
var uploads = getSavedUploads(),
upload = uploads[uploadKey(me)];
if (typeof upload !== 'undefined') {
upload.completedAt = new Date().toISOString();
upload.eTag = me.eTag;
historyCache.setItem('awsUploads', JSON.stringify(uploads));
}
setStatus(COMPLETE);
me.progress(1.0);
}
function removeUploadFile() {
if (typeof me.file !== 'undefined') {
removeUpload(uploadKey(me));
}
}
function getUnfinishedFileUpload() {
var savedUploads = getSavedUploads(true),
u = savedUploads[uploadKey(me)];
if (canRetryUpload(u)) {
me.uploadId = u.uploadId;
me.name = u.awsKey;
me.eTag = u.eTag;
me.firstMd5Digest = u.firstMd5Digest;
me.signParams = u.signParams;
}
}
function canRetryUpload(u) {
// Must be the same file name, file size, last_modified, file type as previous upload
if (typeof u === 'undefined') {
return false;
}
var completedAt = new Date(u.completedAt || FAR_FUTURE);
// check that the part sizes and bucket match, and if the file name of the upload
// matches if onlyRetryForSameFileName is true
return con.partSize === u.partSize
&& completedAt > HOURS_AGO
&& con.bucket === u.bucket
&& (con.onlyRetryForSameFileName ? me.name === u.awsKey : true);
}
function backOffWait(attempts) {
return (attempts === 1) ? 0 : 1000 * Math.min(
con.maxRetryBackoffSecs,
Math.pow(con.retryBackoffPower, attempts - 2)
);
}
function processPartsList() {
var evaporatingCount = 0, finished = true, anyPartHasErrored = false, stati = [], bytesLoaded = [], info;
if (me.status !== EVAPORATING) {
me.info('will not process parts list, as not currently evaporating');
return;
}
for (var i = 0; i < parts.length; i++) {
var part = parts[i];
if (part) {
if (con.computeContentMd5 && part.md5_digest === null) {
return; // MD5 Digest isn't ready yet
}
var requiresUpload = false;
stati.push(part.status);
switch (part.status) {
case EVAPORATING:
finished = false;
evaporatingCount++;
bytesLoaded.push(part.loadedBytes);
break;
case ERROR:
anyPartHasErrored = true;
requiresUpload = true;
break;
case PENDING:
requiresUpload = true;
break;
default:
break;
}
if (requiresUpload) {
finished = false;
if (evaporatingCount < con.maxConcurrentParts) {
uploadPart(i);
evaporatingCount++;
}
}
}
}
info = stati.toString() + ' // bytesLoaded: ' + bytesLoaded.toString();
l.d('processPartsList() anyPartHasErrored: ' + anyPartHasErrored,info);
if (countUploadAttempts >= (parts.length - 1) || anyPartHasErrored) {
me.info('part stati: ' + info);
}
// parts.length is always 1 greater than the actually number of parts, because AWS part numbers start at 1, not 0, so for a 3 part upload, the parts array is: [undefined, object, object, object], which has length 4.
if (finished) {
completeUpload();
}
}
function monitorTotalProgress() {
progressTotalInterval = setInterval(function () {
var totalBytesLoaded = 0;
parts.forEach(function (part) {
totalBytesLoaded += part.loadedBytes;
});
me.progress(totalBytesLoaded/me.sizeBytes);
}, con.progressIntervalMS);
}
/*
Issue #6 identified that some parts would stall silently.
The issue was only noted on Safari on OSX. A bug was filed with Apple, #16136393
This function was added as a work-around. It checks the progress of each part every 2 minutes.
If it finds a part that has made no progress in the last 2 minutes then it aborts it. It will then be detected as an error, and restarted in the same manner of any other errored part
*/
function monitorPartsProgress() {
progressPartsInterval = setInterval(function () {
l.d('monitorPartsProgress() ' + new Date());
parts.forEach(function (part, i) {
var healthy;
if (part.status !== EVAPORATING) {
l.d(i, 'not evaporating ');
return;
}
if (part.loadedBytesPrevious === null) {
l.d(i,'no previous ');
part.loadedBytesPrevious = part.loadedBytes;
return;
}
healthy = part.loadedBytesPrevious < part.loadedBytes;
if (con.simulateStalling && i === 4) {
if (Math.random() < 0.25) {
healthy = false;
}
}
l.d(i, (healthy ? 'moving. ' : 'stalled.'), part.loadedBytesPrevious, part.loadedBytes);
if (!healthy) {
setTimeout(function () {
me.info('part #' + i + ' stalled. will abort. ' + part.loadedBytesPrevious + ' ' + part.loadedBytes);
abortPart(i);
},0);
}
part.loadedBytesPrevious = part.loadedBytes;
});
},2 * 60 * 1000);
}
function monitorProgress() {
monitorTotalProgress();
monitorPartsProgress();
}
function setupRequest(requester) {
l.d('setupRequest()',requester);
if (!con.timeUrl) {
requester.dateString = new Date().toUTCString();
} else {
requester.dateString = new Date(new Date().getTime() + localTimeOffset).toUTCString();
}
requester.x_amz_headers = extend(requester.x_amz_headers, {
'x-amz-date': requester.dateString
});
requester.onGotAuth = function () {
if (hasCurrentXhr(requester)) {
l.w('onGotAuth() step', requester.step, 'is already in progress. Returning.');
return;
}
var xhr = assignCurrentXhr(requester);
var payload = requester.toSend ? requester.toSend() : null;
var url = AWS_URL + requester.path;
if (requester.query_string) {
url += requester.query_string;
}
var all_headers = {};
var status_success = requester.successStatus || 200;
extend(all_headers, requester.not_signed_headers);
extend(all_headers, requester.x_amz_headers);
if (con.simulateErrors && requester.attempts === 1 && requester.step === 'upload #3') {
l.d('simulating error by POST part #3 to invalid url');
url = 'https:///foo';
}
xhr.open(requester.method, url);
xhr.setRequestHeader('Authorization', 'AWS ' + con.aws_key + ':' + requester.auth);
for (var key in all_headers) {
if (all_headers.hasOwnProperty(key)) {
xhr.setRequestHeader(key, all_headers[key]);
}
}
if (requester.contentType) {
xhr.setRequestHeader('Content-Type', requester.contentType);
}
if (requester.md5_digest) {
xhr.setRequestHeader('Content-MD5', requester.md5_digest);
}
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (payload) {
// Test, per http://code.google.com/p/chromium/issues/detail?id=167111#c20
l.d(' ### ' + payload.size);
}
clearCurrentXhr(requester);
if (xhr.status === status_success) {
requester.on200(xhr);
} else {
requester.onErr(xhr);
}
}
};
xhr.onerror = function () {
clearCurrentXhr(requester);
requester.onErr(xhr, true);
};
if (typeof requester.onProgress === 'function') {
xhr.upload.onprogress = function (evt) {
requester.onProgress(evt);
};
}
xhr.send(payload);
};
requester.onFailedAuth = requester.onFailedAuth || function (xhr) {
me.error('Error onFailedAuth for step: ' + requester.step);
requester.onErr(xhr);
};
}
//see: http://docs.amazonwebservices.com/AmazonS3/latest/dev/RESTAuthentication.html#ConstructingTheAuthenticationHeader
function authorizedSend(authRequester) {
l.d('authorizedSend() ' + authRequester.step);
if (hasCurrentXhr(authRequester)) {
l.w('authorizedSend() step', authRequester.step, 'is already in progress. Returning.');
return;
}
if (con.awsLambda) {
return authorizedSignWithLambda(authRequester);
}
var xhr = assignCurrentXhr(authRequester),
url = con.signerUrl + '?to_sign=' + encodeURIComponent(makeStringToSign(authRequester)),
warnMsg;
var signParams = makeSignParamsObject(me.signParams);
for (var param in signParams) {
if (!signParams.hasOwnProperty(param)) { continue; }
url += ('&' + encodeURIComponent(param) + '=' + encodeURIComponent(signParams[param]));
}
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200 && xhr.response.length === 28) {
l.d('authorizedSend got signature for step: \'' + authRequester.step + '\' sig: ' + xhr.response);
authRequester.auth = xhr.response;
clearCurrentXhr(authRequester);
authRequester.onGotAuth();
} else {
warnMsg = 'failed to get authorization (readyState=4) for ' + authRequester.step + '. xhr.status: ' + xhr.status + '. xhr.response: ' + xhr.response;
l.w(warnMsg);
me.warn(warnMsg);
clearCurrentXhr(authRequester);
authRequester.onFailedAuth(xhr);
}
}
};
xhr.onerror = function () {
warnMsg = 'failed to get authorization (onerror) for ' + authRequester.step + '. xhr.status: ' + xhr.status + '. xhr.response: ' + xhr.response;
l.w(warnMsg);
me.warn(warnMsg);
authRequester.onFailedAuth(xhr);
};
xhr.open('GET', url);
var signHeaders = makeSignParamsObject(me.signHeaders);
for (var header in signHeaders) {
if (!signHeaders.hasOwnProperty(header)) { continue; }
xhr.setRequestHeader(header, signHeaders[header])
}
if (typeof me.beforeSigner === 'function') {
me.beforeSigner(xhr, url);
}
xhr.send();
}
function authorizedSignWithLambda(authRequester) {
con.awsLambda.invoke({
FunctionName: con.awsLambdaFunction,
InvocationType: 'RequestResponse',
Payload: JSON.stringify({
to_sign: makeStringToSign(authRequester),
sign_params: makeSignParamsObject(me.signParams),
sign_headers: makeSignParamsObject(me.signHeaders)
})
}, function (err, data) {
if (err) {
var warnMsg = 'failed to get authorization with lambda ' + err;
l.w(warnMsg);
me.warn(warnMsg);
authRequester.onFailedAuth(err);
return;
}
authRequester.auth = JSON.parse(data.Payload);
authRequester.onGotAuth();
});
}
function makeSignParamsObject(params) {
var out = {};
for (var param in params) {
if (!params.hasOwnProperty(param)) { continue; }
if (typeof params[param] === 'function') {
out[param] = params[param]();
} else {
out[param] = params[param];
}
}
return out;
}
function makeStringToSign(request) {
var x_amz_headers = '', to_sign, header_key_array = [];
for (var key in request.x_amz_headers) {
if (request.x_amz_headers.hasOwnProperty(key)) {
header_key_array.push(key);
}
}
header_key_array.sort();
header_key_array.forEach(function (header_key) {
x_amz_headers += (header_key + ':' + request.x_amz_headers[header_key] + '\n');
});
to_sign = request.method + '\n' +
(request.md5_digest || '') + '\n' +
(request.contentType || '') + '\n' +
'\n' +
x_amz_headers +
(con.cloudfront ? '/' + con.bucket : '') +
request.path;
return to_sign;
}
function getPath() {
var path = '/' + con.bucket + '/' + me.name;
if (con.cloudfront || AWS_URL.indexOf('cloudfront') > -1) {
path = '/' + me.name;
}
return path;
}
function getBaseXhrObject(requester) {
// The Xhr is either on the upload or on a part...
return (typeof requester.part === 'undefined') ? requester : requester.part;
}
function hasCurrentXhr(requester) {
return !!getBaseXhrObject(requester).currentXhr;
}
function assignCurrentXhr(requester) {
return getBaseXhrObject(requester).currentXhr = new XMLHttpRequest();
}
function clearCurrentXhr(requester) {
delete getBaseXhrObject(requester).currentXhr;
}
}
function extend(obj1, obj2, obj3) {
obj1 = typeof obj1 === 'undefined' ? {} : obj1;
if (typeof obj3 === 'object') {
for (var key in obj3) {
obj2[key] = obj3[key];
}
}
for (var key2 in obj2) {
obj1[key2] = obj2[key2];
}
return obj1;
}
function parseXml(body) {
var parser = new DOMParser();
return parser.parseFromString(body, "text/xml");
}
function getSavedUploads(purge) {
var result = JSON.parse(historyCache.getItem('awsUploads') || '{}');
if (purge) {
for (var key in result) {
if (result.hasOwnProperty(key)) {
var upload = result[key],
completedAt = new Date(upload.completedAt || FAR_FUTURE);
if (completedAt < HOURS_AGO) {
// The upload is recent, let's keep it
delete result[key];
}
}
}
}
return result;
}
function uploadKey(fileUpload) {
// The key tries to give a signature to a file in the absence of its path.
// "<filename>-<mimetype>-<modifieddate>-<filesize>"
return [
fileUpload.file.name,
fileUpload.file.type,
dateISOString(fileUpload.file.lastModifiedDate),
fileUpload.file.size
].join("-");
}
function saveUpload(uploadKey, upload) {
var uploads = getSavedUploads();
uploads[uploadKey] = upload;
historyCache.setItem('awsUploads', JSON.stringify(uploads));
}
function removeUpload(uploadKey) {
var uploads = getSavedUploads();
delete uploads[uploadKey];
historyCache.setItem('awsUploads', JSON.stringify(uploads));
}
function nodeValue(parent, nodeName) {
return parent.getElementsByTagName(nodeName)[0].textContent;
}
};
function dateISOString(date) {
// Try to get the modified date as an ISO String, if the date exists
return date ? date.toISOString() : '';
}
function getFilePart(file, start, end) {
var slicerFn = (file.slice ? 'slice' : (file['mozSlice'] ? 'mozSlice' : 'webkitSlice'));
// browsers' implementation of the Blob.slice function has been renamed a couple of times, and the meaning of the 2nd parameter changed. For example Gecko went from slice(start,length) -> mozSlice(start, end) -> slice(start, end). As of 12/12/12, it seems that the unified 'slice' is the best bet, hence it being first in the list. See https://developer.mozilla.org/en-US/docs/DOM/Blob for more info.
return file[slicerFn](start, end);
}
if (typeof module !== 'undefined' && module.exports) {
module.exports = Evaporate;
} else if (typeof window !== 'undefined') {
window.Evaporate = Evaporate;
}
})();
| extend1994/cdnjs | ajax/libs/evaporate/1.2.0/evaporate.js | JavaScript | mit | 54,895 |
/* Copyright (c) 2010-2013, The Linux Foundation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of The Linux Foundation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <hdmi.h>
#include <platform/timer.h>
#include <platform/gpio.h>
#include <platform/clock.h>
#include <platform/iomap.h>
#include <platform/scm-io.h>
extern void hdmi_app_clk_init(int);
extern int hdmi_msm_turn_on();
#define FB_ADDR 0x43E00000
static struct fbcon_config fb_cfg = {
.height = DTV_FB_HEIGHT,
.width = DTV_FB_WIDTH,
.stride = DTV_FB_WIDTH,
.format = DTV_FORMAT_RGB565,
.bpp = DTV_BPP,
.update_start = NULL,
.update_done = NULL,
.base = FB_ADDR;
};
struct fbcon_config *get_fbcon(void)
{
return &fb_cfg;
}
void hdmi_msm_init_phy()
{
dprintf(SPEW, "PHY INIT\n");
uint32_t offset = 0;
uint32_t len = 0;
writel(0x0C, HDMI_PHY_REG_0);
writel(0x54, HDMI_PHY_REG_1);
writel(0x7F, HDMI_PHY_REG_2);
writel(0x3F, HDMI_PHY_REG_2);
writel(0x1F, HDMI_PHY_REG_2);
writel(0x01, HDMI_PHY_REG_3);
writel(0x00, HDMI_PHY_REG_9);
writel(0x03, HDMI_PHY_REG_12);
writel(0x01, HDMI_PHY_REG_2);
writel(0x81, HDMI_PHY_REG_2);
offset = (HDMI_PHY_REG_4 - MSM_HDMI_BASE);
len = (HDMI_PHY_REG_11 - MSM_HDMI_BASE);
while (offset <= len) {
writel(0x0, MSM_HDMI_BASE + offset);
offset += 4;
}
writel(0x13, HDMI_PHY_REG_12);
}
static void hdmi_gpio_config()
{
uint32_t func;
uint32_t pull;
uint32_t drv;
uint32_t enable = 0;
uint32_t dir;
func = 1;
pull = GPIO_NO_PULL;
drv = GPIO_16MA;
dir = 1;
gpio_tlmm_config(170, func, dir, pull, drv, enable);
gpio_tlmm_config(171, func, dir, pull, drv, enable);
func = 1;
pull = GPIO_PULL_DOWN;
drv = GPIO_16MA;
gpio_tlmm_config(172, func, dir, pull, drv, enable);
}
/*
* This is the start function which initializes clocks , gpios for hdmi
* & powers on the HDMI core
*/
void hdmi_power_init()
{
// Enable HDMI clocks
hdmi_app_clk_init(1);
// Enable pm8058
pm8058_ldo_set_voltage();
pm8058_vreg_enable();
// configure HDMI Gpio
hdmi_gpio_config();
// Enable pm8091
pm8901_mpp_enable();
pm8901_vs_enable();
// Power on HDMI
hdmi_msm_turn_on();
}
static void hdmi_msm_reset_core()
{
uint32_t reg_val = 0;
hdmi_msm_set_mode(0);
// Disable clocks
hdmi_app_clk_init(0);
udelay(5);
// Enable clocks
hdmi_app_clk_init(1);
reg_val = secure_readl(SW_RESET_CORE_REG);
reg_val |= BIT(11);
secure_writel(reg_val, SW_RESET_CORE_REG);
udelay(5);
reg_val = secure_readl(SW_RESET_AHB_REG);
reg_val |= BIT(9);
secure_writel(reg_val, SW_RESET_AHB_REG);
udelay(5);
reg_val = secure_readl(SW_RESET_AHB_REG);
reg_val |= BIT(9);
secure_writel(reg_val, SW_RESET_AHB_REG);
udelay(20);
reg_val = secure_readl(SW_RESET_CORE_REG);
reg_val &= ~(BIT(11));
secure_writel(reg_val, SW_RESET_CORE_REG);
udelay(5);
reg_val = secure_readl(SW_RESET_AHB_REG);
reg_val &= ~(BIT(9));
secure_writel(reg_val, SW_RESET_AHB_REG);
udelay(5);
reg_val = secure_readl(SW_RESET_AHB_REG);
reg_val &= ~(BIT(9));
secure_writel(reg_val, SW_RESET_AHB_REG);
udelay(5);
}
int hdmi_dtv_on()
{
uint32_t val, pll_mode, ns_val, pll_config;
// Configure PLL2 for tv src clk
pll_mode |= BIT(1);
secure_writel(pll_mode, MM_PLL2_MODE_REG);
udelay(10);
pll_mode = secure_readl(MM_PLL2_MODE_REG);
pll_mode &= ~BIT(0);
secure_writel(pll_mode, MM_PLL2_MODE_REG);
pll_mode &= ~BIT(2);
secure_writel(pll_mode, MM_PLL2_MODE_REG);
secure_writel(0x2C, MM_PLL2_L_VAL_REG);
secure_writel(0x0, MM_PLL2_M_VAL_REG);
secure_writel(0x0, MM_PLL2_N_VAL_REG);
udelay(10);
val = 0xA6248F;
secure_writel(val, MM_PLL2_CONFIG_REG);
// set M N D
ns_val = secure_readl(TV_NS_REG);
ns_val |= BIT(7);
secure_writel(ns_val, TV_NS_REG);
secure_writel(0xff, TV_MD_REG);
val = secure_readl(TV_CC_REG);
val &= ~(BM(7, 6));
val |= CC(6, 0);
secure_writel(val, TV_CC_REG);
ns_val &= ~BIT(7);
secure_writel(ns_val, TV_NS_REG);
// confiure hdmi_ref clk to run @ 148.5 MHz
val = secure_readl(MISC_CC2_REG);
val &= ~(BIT(28) | BM(21, 18));
ns_val = NS_MM(23, 16, 0, 0, 15, 14, 2, 2, 0, 3);
val |= (BIT(28) | BVAL(21, 18, (ns_val >> 14) & 0x3));
secure_writel(val, MISC_CC2_REG);
pll_mode |= BIT(2);
secure_writel(pll_mode, MM_PLL2_MODE_REG);
pll_mode |= BIT(0);
secure_writel(pll_mode, MM_PLL2_MODE_REG);
udelay(50);
// Enable TV src clk
val = secure_readl(TV_NS_REG);
val &= ~(BM(23, 16) | BM(15, 14) | BM(2, 0));
ns_val = NS_MM(23, 16, 0, 0, 15, 14, 2, 2, 0, 3);
val |= (ns_val & (BM(23, 16) | BM(15, 14) | BM(2, 0)));
secure_writel(val, TV_NS_REG);
// Enable hdmi clk
val = secure_readl(TV_CC_REG);
val |= BIT(12);
secure_writel(val, TV_CC_REG);
// Root en of tv src clk
val = secure_readl(TV_CC_REG);
val |= BIT(2);
secure_writel(val, TV_CC_REG);
// De-Assert hdmi clk
val = secure_readl(SW_RESET_CORE_REG);
val |= BIT(1);
secure_writel(val, SW_RESET_CORE_REG);
udelay(10);
val = secure_readl(SW_RESET_CORE_REG);
val &= ~(BIT(1));
secure_writel(val, SW_RESET_CORE_REG);
udelay(10);
// enable mdp dtv clk
val = secure_readl(TV_CC_REG);
val |= BIT(0);
secure_writel(val, TV_CC_REG);
udelay(10);
return 0;
}
| Heart-travel/lk | platform/msm8x60/hdmi_core.c | C | mit | 6,791 |
<?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\Bundle\TwigBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* TwigExtension configuration structure.
*
* @author Jeremy Mikola <jmikola@gmail.com>
*/
class Configuration implements ConfigurationInterface
{
/**
* Generates the configuration tree builder.
*
* @return TreeBuilder The tree builder
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('twig');
$rootNode
->children()
->scalarNode('exception_controller')->defaultValue('twig.controller.exception:showAction')->end()
->end()
;
$this->addFormSection($rootNode);
$this->addFormThemesSection($rootNode);
$this->addGlobalsSection($rootNode);
$this->addTwigOptions($rootNode);
return $treeBuilder;
}
private function addFormSection(ArrayNodeDefinition $rootNode)
{
$rootNode
->validate()
->ifTrue(function ($v) {
return count($v['form']['resources']) > 0;
})
->then(function ($v) {
$v['form_themes'] = array_values(array_unique(array_merge($v['form']['resources'], $v['form_themes'])));
return $v;
})
->end()
->children()
->arrayNode('form')
->info('Deprecated since 2.6, to be removed in 3.0. Use twig.form_themes instead')
->addDefaultsIfNotSet()
->fixXmlConfig('resource')
->children()
->arrayNode('resources')
->addDefaultChildrenIfNoneSet()
->prototype('scalar')->defaultValue('form_div_layout.html.twig')->end()
->example(array('MyBundle::form.html.twig'))
->validate()
->ifTrue(function ($v) { return !in_array('form_div_layout.html.twig', $v); })
->then(function ($v) {
return array_merge(array('form_div_layout.html.twig'), $v);
})
->end()
->end()
->end()
->end()
->end()
;
}
private function addFormThemesSection(ArrayNodeDefinition $rootNode)
{
$rootNode
->fixXmlConfig('form_theme')
->children()
->arrayNode('form_themes')
->addDefaultChildrenIfNoneSet()
->prototype('scalar')->defaultValue('form_div_layout.html.twig')->end()
->example(array('MyBundle::form.html.twig'))
->validate()
->ifTrue(function ($v) { return !in_array('form_div_layout.html.twig', $v); })
->then(function ($v) {
return array_merge(array('form_div_layout.html.twig'), $v);
})
->end()
->end()
->end()
;
}
private function addGlobalsSection(ArrayNodeDefinition $rootNode)
{
$rootNode
->fixXmlConfig('global')
->children()
->arrayNode('globals')
->normalizeKeys(false)
->useAttributeAsKey('key')
->example(array('foo' => '"@bar"', 'pi' => 3.14))
->prototype('array')
->beforeNormalization()
->ifTrue(function ($v) { return is_string($v) && 0 === strpos($v, '@'); })
->then(function ($v) {
if (0 === strpos($v, '@@')) {
return substr($v, 1);
}
return array('id' => substr($v, 1), 'type' => 'service');
})
->end()
->beforeNormalization()
->ifTrue(function ($v) {
if (is_array($v)) {
$keys = array_keys($v);
sort($keys);
return $keys !== array('id', 'type') && $keys !== array('value');
}
return true;
})
->then(function ($v) { return array('value' => $v); })
->end()
->children()
->scalarNode('id')->end()
->scalarNode('type')
->validate()
->ifNotInArray(array('service'))
->thenInvalid('The %s type is not supported')
->end()
->end()
->variableNode('value')->end()
->end()
->end()
->end()
->end()
;
}
private function addTwigOptions(ArrayNodeDefinition $rootNode)
{
$rootNode
->fixXmlConfig('path')
->children()
->variableNode('autoescape')
->defaultValue(array('Symfony\Bundle\TwigBundle\TwigDefaultEscapingStrategy', 'guess'))
->end()
->scalarNode('autoescape_service')->defaultNull()->end()
->scalarNode('autoescape_service_method')->defaultNull()->end()
->scalarNode('base_template_class')->example('Twig_Template')->end()
->scalarNode('cache')->defaultValue('%kernel.cache_dir%/twig')->end()
->scalarNode('charset')->defaultValue('%kernel.charset%')->end()
->scalarNode('debug')->defaultValue('%kernel.debug%')->end()
->scalarNode('strict_variables')->end()
->scalarNode('auto_reload')->end()
->scalarNode('optimizations')->end()
->arrayNode('paths')
->normalizeKeys(false)
->useAttributeAsKey('paths')
->beforeNormalization()
->always()
->then(function ($paths) {
$normalized = array();
foreach ($paths as $path => $namespace) {
if (is_array($namespace)) {
// xml
$path = $namespace['value'];
$namespace = $namespace['namespace'];
}
// path within the default namespace
if (ctype_digit((string) $path)) {
$path = $namespace;
$namespace = null;
}
$normalized[$path] = $namespace;
}
return $normalized;
})
->end()
->prototype('variable')->end()
->end()
->end()
;
}
}
| zi9o/Daufin2 | vendor/symfony/symfony/src/Symfony/Bundle/TwigBundle/DependencyInjection/Configuration.php | PHP | mit | 7,954 |
/*! https://mths.be/punycode v1.4.1 by @mathias */
;(function(root) {
/** Detect free variables */
var freeExports = typeof exports == 'object' && exports &&
!exports.nodeType && exports;
var freeModule = typeof module == 'object' && module &&
!module.nodeType && module;
var freeGlobal = typeof global == 'object' && global;
if (
freeGlobal.global === freeGlobal ||
freeGlobal.window === freeGlobal ||
freeGlobal.self === freeGlobal
) {
root = freeGlobal;
}
/**
* The `punycode` object.
* @name punycode
* @type Object
*/
var punycode,
/** Highest positive signed 32-bit float value */
maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
/** Bootstring parameters */
base = 36,
tMin = 1,
tMax = 26,
skew = 38,
damp = 700,
initialBias = 72,
initialN = 128, // 0x80
delimiter = '-', // '\x2D'
/** Regular expressions */
regexPunycode = /^xn--/,
regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
/** Error messages */
errors = {
'overflow': 'Overflow: input needs wider integers to process',
'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
'invalid-input': 'Invalid input'
},
/** Convenience shortcuts */
baseMinusTMin = base - tMin,
floor = Math.floor,
stringFromCharCode = String.fromCharCode,
/** Temporary variable */
key;
/*--------------------------------------------------------------------------*/
/**
* A generic error utility function.
* @private
* @param {String} type The error type.
* @returns {Error} Throws a `RangeError` with the applicable error message.
*/
function error(type) {
throw new RangeError(errors[type]);
}
/**
* A generic `Array#map` utility function.
* @private
* @param {Array} array The array to iterate over.
* @param {Function} callback The function that gets called for every array
* item.
* @returns {Array} A new array of values returned by the callback function.
*/
function map(array, fn) {
var length = array.length;
var result = [];
while (length--) {
result[length] = fn(array[length]);
}
return result;
}
/**
* A simple `Array#map`-like wrapper to work with domain name strings or email
* addresses.
* @private
* @param {String} domain The domain name or email address.
* @param {Function} callback The function that gets called for every
* character.
* @returns {Array} A new string of characters returned by the callback
* function.
*/
function mapDomain(string, fn) {
var parts = string.split('@');
var result = '';
if (parts.length > 1) {
// In email addresses, only the domain name should be punycoded. Leave
// the local part (i.e. everything up to `@`) intact.
result = parts[0] + '@';
string = parts[1];
}
// Avoid `split(regex)` for IE8 compatibility. See #17.
string = string.replace(regexSeparators, '\x2E');
var labels = string.split('.');
var encoded = map(labels, fn).join('.');
return result + encoded;
}
/**
* Creates an array containing the numeric code points of each Unicode
* character in the string. While JavaScript uses UCS-2 internally,
* this function will convert a pair of surrogate halves (each of which
* UCS-2 exposes as separate characters) into a single code point,
* matching UTF-16.
* @see `punycode.ucs2.encode`
* @see <https://mathiasbynens.be/notes/javascript-encoding>
* @memberOf punycode.ucs2
* @name decode
* @param {String} string The Unicode input string (UCS-2).
* @returns {Array} The new array of code points.
*/
function ucs2decode(string) {
var output = [],
counter = 0,
length = string.length,
value,
extra;
while (counter < length) {
value = string.charCodeAt(counter++);
if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
// high surrogate, and there is a next character
extra = string.charCodeAt(counter++);
if ((extra & 0xFC00) == 0xDC00) { // low surrogate
output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
} else {
// unmatched surrogate; only append this code unit, in case the next
// code unit is the high surrogate of a surrogate pair
output.push(value);
counter--;
}
} else {
output.push(value);
}
}
return output;
}
/**
* Creates a string based on an array of numeric code points.
* @see `punycode.ucs2.decode`
* @memberOf punycode.ucs2
* @name encode
* @param {Array} codePoints The array of numeric code points.
* @returns {String} The new Unicode string (UCS-2).
*/
function ucs2encode(array) {
return map(array, function(value) {
var output = '';
if (value > 0xFFFF) {
value -= 0x10000;
output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
value = 0xDC00 | value & 0x3FF;
}
output += stringFromCharCode(value);
return output;
}).join('');
}
/**
* Converts a basic code point into a digit/integer.
* @see `digitToBasic()`
* @private
* @param {Number} codePoint The basic numeric code point value.
* @returns {Number} The numeric value of a basic code point (for use in
* representing integers) in the range `0` to `base - 1`, or `base` if
* the code point does not represent a value.
*/
function basicToDigit(codePoint) {
if (codePoint - 48 < 10) {
return codePoint - 22;
}
if (codePoint - 65 < 26) {
return codePoint - 65;
}
if (codePoint - 97 < 26) {
return codePoint - 97;
}
return base;
}
/**
* Converts a digit/integer into a basic code point.
* @see `basicToDigit()`
* @private
* @param {Number} digit The numeric value of a basic code point.
* @returns {Number} The basic code point whose value (when used for
* representing integers) is `digit`, which needs to be in the range
* `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
* used; else, the lowercase form is used. The behavior is undefined
* if `flag` is non-zero and `digit` has no uppercase form.
*/
function digitToBasic(digit, flag) {
// 0..25 map to ASCII a..z or A..Z
// 26..35 map to ASCII 0..9
return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
}
/**
* Bias adaptation function as per section 3.4 of RFC 3492.
* https://tools.ietf.org/html/rfc3492#section-3.4
* @private
*/
function adapt(delta, numPoints, firstTime) {
var k = 0;
delta = firstTime ? floor(delta / damp) : delta >> 1;
delta += floor(delta / numPoints);
for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
delta = floor(delta / baseMinusTMin);
}
return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
}
/**
* Converts a Punycode string of ASCII-only symbols to a string of Unicode
* symbols.
* @memberOf punycode
* @param {String} input The Punycode string of ASCII-only symbols.
* @returns {String} The resulting string of Unicode symbols.
*/
function decode(input) {
// Don't use UCS-2
var output = [],
inputLength = input.length,
out,
i = 0,
n = initialN,
bias = initialBias,
basic,
j,
index,
oldi,
w,
k,
digit,
t,
/** Cached calculation results */
baseMinusT;
// Handle the basic code points: let `basic` be the number of input code
// points before the last delimiter, or `0` if there is none, then copy
// the first basic code points to the output.
basic = input.lastIndexOf(delimiter);
if (basic < 0) {
basic = 0;
}
for (j = 0; j < basic; ++j) {
// if it's not a basic code point
if (input.charCodeAt(j) >= 0x80) {
error('not-basic');
}
output.push(input.charCodeAt(j));
}
// Main decoding loop: start just after the last delimiter if any basic code
// points were copied; start at the beginning otherwise.
for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
// `index` is the index of the next character to be consumed.
// Decode a generalized variable-length integer into `delta`,
// which gets added to `i`. The overflow checking is easier
// if we increase `i` as we go, then subtract off its starting
// value at the end to obtain `delta`.
for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
if (index >= inputLength) {
error('invalid-input');
}
digit = basicToDigit(input.charCodeAt(index++));
if (digit >= base || digit > floor((maxInt - i) / w)) {
error('overflow');
}
i += digit * w;
t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
if (digit < t) {
break;
}
baseMinusT = base - t;
if (w > floor(maxInt / baseMinusT)) {
error('overflow');
}
w *= baseMinusT;
}
out = output.length + 1;
bias = adapt(i - oldi, out, oldi == 0);
// `i` was supposed to wrap around from `out` to `0`,
// incrementing `n` each time, so we'll fix that now:
if (floor(i / out) > maxInt - n) {
error('overflow');
}
n += floor(i / out);
i %= out;
// Insert `n` at position `i` of the output
output.splice(i++, 0, n);
}
return ucs2encode(output);
}
/**
* Converts a string of Unicode symbols (e.g. a domain name label) to a
* Punycode string of ASCII-only symbols.
* @memberOf punycode
* @param {String} input The string of Unicode symbols.
* @returns {String} The resulting Punycode string of ASCII-only symbols.
*/
function encode(input) {
var n,
delta,
handledCPCount,
basicLength,
bias,
j,
m,
q,
k,
t,
currentValue,
output = [],
/** `inputLength` will hold the number of code points in `input`. */
inputLength,
/** Cached calculation results */
handledCPCountPlusOne,
baseMinusT,
qMinusT;
// Convert the input in UCS-2 to Unicode
input = ucs2decode(input);
// Cache the length
inputLength = input.length;
// Initialize the state
n = initialN;
delta = 0;
bias = initialBias;
// Handle the basic code points
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < 0x80) {
output.push(stringFromCharCode(currentValue));
}
}
handledCPCount = basicLength = output.length;
// `handledCPCount` is the number of code points that have been handled;
// `basicLength` is the number of basic code points.
// Finish the basic string - if it is not empty - with a delimiter
if (basicLength) {
output.push(delimiter);
}
// Main encoding loop:
while (handledCPCount < inputLength) {
// All non-basic code points < n have been handled already. Find the next
// larger one:
for (m = maxInt, j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue >= n && currentValue < m) {
m = currentValue;
}
}
// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
// but guard against overflow
handledCPCountPlusOne = handledCPCount + 1;
if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
error('overflow');
}
delta += (m - n) * handledCPCountPlusOne;
n = m;
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < n && ++delta > maxInt) {
error('overflow');
}
if (currentValue == n) {
// Represent delta as a generalized variable-length integer
for (q = delta, k = base; /* no condition */; k += base) {
t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
if (q < t) {
break;
}
qMinusT = q - t;
baseMinusT = base - t;
output.push(
stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
);
q = floor(qMinusT / baseMinusT);
}
output.push(stringFromCharCode(digitToBasic(q, 0)));
bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
delta = 0;
++handledCPCount;
}
}
++delta;
++n;
}
return output.join('');
}
/**
* Converts a Punycode string representing a domain name or an email address
* to Unicode. Only the Punycoded parts of the input will be converted, i.e.
* it doesn't matter if you call it on a string that has already been
* converted to Unicode.
* @memberOf punycode
* @param {String} input The Punycoded domain name or email address to
* convert to Unicode.
* @returns {String} The Unicode representation of the given Punycode
* string.
*/
function toUnicode(input) {
return mapDomain(input, function(string) {
return regexPunycode.test(string)
? decode(string.slice(4).toLowerCase())
: string;
});
}
/**
* Converts a Unicode string representing a domain name or an email address to
* Punycode. Only the non-ASCII parts of the domain name will be converted,
* i.e. it doesn't matter if you call it with a domain that's already in
* ASCII.
* @memberOf punycode
* @param {String} input The domain name or email address to convert, as a
* Unicode string.
* @returns {String} The Punycode representation of the given domain name or
* email address.
*/
function toASCII(input) {
return mapDomain(input, function(string) {
return regexNonASCII.test(string)
? 'xn--' + encode(string)
: string;
});
}
/*--------------------------------------------------------------------------*/
/** Define the public API */
punycode = {
/**
* A string representing the current Punycode.js version number.
* @memberOf punycode
* @type String
*/
'version': '1.4.1',
/**
* An object of methods to convert from JavaScript's internal character
* representation (UCS-2) to Unicode code points, and back.
* @see <https://mathiasbynens.be/notes/javascript-encoding>
* @memberOf punycode
* @type Object
*/
'ucs2': {
'decode': ucs2decode,
'encode': ucs2encode
},
'decode': decode,
'encode': encode,
'toASCII': toASCII,
'toUnicode': toUnicode
};
/** Expose `punycode` */
// Some AMD build optimizers, like r.js, check for specific condition patterns
// like the following:
if (
typeof define == 'function' &&
typeof define.amd == 'object' &&
define.amd
) {
define('punycode', function() {
return punycode;
});
} else if (freeExports && freeModule) {
if (module.exports == freeExports) {
// in Node.js, io.js, or RingoJS v0.8.0+
freeModule.exports = punycode;
} else {
// in Narwhal or RingoJS v0.7.0-
for (key in punycode) {
punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
}
}
} else {
// in Rhino or a web browser
root.punycode = punycode;
}
}(this));
| molnplus/molnplus.github.io | node_modules/punycode/punycode.js | JavaScript | mit | 14,670 |
/* Native method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* Creates an array that is the composition of partially applied arguments,
* placeholders, and provided arguments into a single array of arguments.
*
* @private
* @param {Array|Object} args The provided arguments.
* @param {Array} partials The arguments to prepend to those provided.
* @param {Array} holders The `partials` placeholder indexes.
* @returns {Array} Returns the new array of composed arguments.
*/
function composeArgs(args, partials, holders) {
var holdersLength = holders.length,
argsIndex = -1,
argsLength = nativeMax(args.length - holdersLength, 0),
leftIndex = -1,
leftLength = partials.length,
result = Array(leftLength + argsLength);
while (++leftIndex < leftLength) {
result[leftIndex] = partials[leftIndex];
}
while (++argsIndex < holdersLength) {
result[holders[argsIndex]] = args[argsIndex];
}
while (argsLength--) {
result[leftIndex++] = args[argsIndex++];
}
return result;
}
module.exports = composeArgs;
| Maqnai2234/Blog-ThemeHTML | node_modules/babel-preset-es2015/node_modules/babel-plugin-transform-regenerator/node_modules/babel-traverse/node_modules/lodash/internal/composeArgs.js | JavaScript | mit | 1,119 |
module.exports = function (args, opts) {
if (!opts) opts = {};
var flags = { bools : {}, strings : {} };
[].concat(opts['boolean']).filter(Boolean).forEach(function (key) {
flags.bools[key] = true;
});
var aliases = {};
Object.keys(opts.alias || {}).forEach(function (key) {
aliases[key] = [].concat(opts.alias[key]);
aliases[key].forEach(function (x) {
aliases[x] = [key].concat(aliases[key].filter(function (y) {
return x !== y;
}));
});
});
[].concat(opts.string).filter(Boolean).forEach(function (key) {
flags.strings[key] = true;
if (aliases[key]) {
flags.strings[aliases[key]] = true;
}
});
var defaults = opts['default'] || {};
var argv = { _ : [] };
Object.keys(flags.bools).forEach(function (key) {
setArg(key, defaults[key] === undefined ? false : defaults[key]);
});
var notFlags = [];
if (args.indexOf('--') !== -1) {
notFlags = args.slice(args.indexOf('--')+1);
args = args.slice(0, args.indexOf('--'));
}
function setArg (key, val) {
var value = !flags.strings[key] && isNumber(val)
? Number(val) : val
;
setKey(argv, key.split('.'), value);
(aliases[key] || []).forEach(function (x) {
setKey(argv, x.split('.'), value);
});
}
for (var i = 0; i < args.length; i++) {
var arg = args[i];
if (/^--.+=/.test(arg)) {
// Using [\s\S] instead of . because js doesn't support the
// 'dotall' regex modifier. See:
// http://stackoverflow.com/a/1068308/13216
var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
setArg(m[1], m[2]);
}
else if (/^--no-.+/.test(arg)) {
var key = arg.match(/^--no-(.+)/)[1];
setArg(key, false);
}
else if (/^--.+/.test(arg)) {
var key = arg.match(/^--(.+)/)[1];
var next = args[i + 1];
if (next !== undefined && !/^-/.test(next)
&& !flags.bools[key]
&& (aliases[key] ? !flags.bools[aliases[key]] : true)) {
setArg(key, next);
i++;
}
else if (/^(true|false)$/.test(next)) {
setArg(key, next === 'true');
i++;
}
else {
setArg(key, flags.strings[key] ? '' : true);
}
}
else if (/^-[^-]+/.test(arg)) {
var letters = arg.slice(1,-1).split('');
var broken = false;
for (var j = 0; j < letters.length; j++) {
var next = arg.slice(j+2);
if (next === '-') {
setArg(letters[j], next)
continue;
}
if (/[A-Za-z]/.test(letters[j])
&& /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
setArg(letters[j], next);
broken = true;
break;
}
if (letters[j+1] && letters[j+1].match(/\W/)) {
setArg(letters[j], arg.slice(j+2));
broken = true;
break;
}
else {
setArg(letters[j], flags.strings[letters[j]] ? '' : true);
}
}
var key = arg.slice(-1)[0];
if (!broken && key !== '-') {
if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1])
&& !flags.bools[key]
&& (aliases[key] ? !flags.bools[aliases[key]] : true)) {
setArg(key, args[i+1]);
i++;
}
else if (args[i+1] && /true|false/.test(args[i+1])) {
setArg(key, args[i+1] === 'true');
i++;
}
else {
setArg(key, flags.strings[key] ? '' : true);
}
}
}
else {
argv._.push(
flags.strings['_'] || !isNumber(arg) ? arg : Number(arg)
);
}
}
Object.keys(defaults).forEach(function (key) {
if (!hasKey(argv, key.split('.'))) {
setKey(argv, key.split('.'), defaults[key]);
(aliases[key] || []).forEach(function (x) {
setKey(argv, x.split('.'), defaults[key]);
});
}
});
notFlags.forEach(function(key) {
argv._.push(key);
});
return argv;
};
function hasKey (obj, keys) {
var o = obj;
keys.slice(0,-1).forEach(function (key) {
o = (o[key] || {});
});
var key = keys[keys.length - 1];
return key in o;
}
function setKey (obj, keys, value) {
var o = obj;
keys.slice(0,-1).forEach(function (key) {
if (o[key] === undefined) o[key] = {};
o = o[key];
});
var key = keys[keys.length - 1];
if (o[key] === undefined || typeof o[key] === 'boolean') {
o[key] = value;
}
else if (Array.isArray(o[key])) {
o[key].push(value);
}
else {
o[key] = [ o[key], value ];
}
}
function isNumber (x) {
if (typeof x === 'number') return true;
if (/^0x[0-9a-f]+$/i.test(x)) return true;
return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
}
| eugene-goldberg/DataManager_0.3 | node_modules/karma/node_modules/optimist/node_modules/minimist/index.js | JavaScript | mit | 5,567 |
webshims.validityMessages.ar = {
"typeMismatch": {
"email": "أدخِل رجاءً البريد الإلكتروني.",
"url": "أدخِل رجاءً عنوان الموقع."
},
"badInput": {
"number": "قيمة غير صحيحة",
"date": "قيمة غير صحيحة",
"time": "قيمة غير صحيحة",
"range": "قيمة غير صحيحة",
"datetime-local": "قيمة غير صحيحة"
},
"tooLong": "قيمة غير صحيحة",
"patternMismatch": "اتبع رجاءً التنسيق المطلوب: {%title}.",
"valueMissing": {
"defaultMessage": "رجاءً املأ هذا الحقل.",
"checkbox": "رجاءً علّم هذا المربع إن أردت المتابعة.",
"select": "رجاءً اختر عنصرًا من اللائحة.",
"radio": "رجاءً اختر أحد هذه الخيارات."
},
"rangeUnderflow": {
"defaultMessage": "يجب أن تكون القيمة أكبر من أو تساوي {%min}.",
"date": "يجب أن تكون القيمة أكبر من أو تساوي {%min}.",
"time": "يجب أن تكون القيمة أكبر من أو تساوي {%min}.",
"datetime-local": "يجب أن تكون القيمة أكبر من أو تساوي {%min}."
},
"rangeOverflow": {
"defaultMessage": "يجب أن تكون القيمة أقل من أو تساوي {%max}.",
"date": "يجب أن تكون القيمة أقل من أو تساوي {%max}.",
"time": "يجب أن تكون القيمة أقل من أو تساوي {%max}.",
"datetime-local": "يجب أن تكون القيمة أقل من أو تساوي {%max}."
},
"stepMismatch": "قيمة غير صحيحة"
};
webshims.formcfg.ar = {
numberFormat: {
".": ".",
",": ","
},
numberSigns: '.',
dateSigns: '/',
timeSigns: ":. ",
dFormat: "/",
patterns: {
d: 'dd/mm/yy'
},
date: {
closeText: 'إغلاق',
prevText: '<السابق',
nextText: 'التالي>',
currentText: 'اليوم',
monthNames: ['كانون الثاني', 'شباط', 'آذار', 'نيسان', 'مايو', 'حزيران', 'تموز', 'آب', 'أيلول', 'تشرين الأول', 'تشرين الثاني', 'كانون الأول'],
monthNamesShort: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'],
dayNames: ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'],
dayNamesShort: ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'],
dayNamesMin: ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'],
weekHeader: 'أسبوع',
firstDay: 6,
isRTL: true,
showMonthAfterYear: false,
yearSuffix: ''
}
};
| idleberg/cdnjs | ajax/libs/webshim/1.14.3-RC1/dev/shims/i18n/formcfg-ar.js | JavaScript | mit | 2,706 |
webshims.validityMessages.it = {
"typeMismatch": {
"email": "Inserire un indirizzo e-mail",
"url": "Inserire un URL"
},
"badInput": {
"number": "Valore non valido.",
"date": "Valore non valido.",
"time": "Valore non valido.",
"range": "Valore non valido.",
"datetime-local": "Valore non valido."
},
"tooLong": "Valore non valido.",
"patternMismatch": "Inserire un valore nel formato richiesto: {%title}",
"valueMissing": {
"defaultMessage": "Compilare questo campo",
"checkbox": "Selezionare questa casella per procedere",
"select": "Selezionare un elemento dall'elenco",
"radio": "Selezionare una delle opzioni disponibili"
},
"rangeUnderflow": {
"defaultMessage": "Il valore deve essere superiore o uguale a {%min}.",
"date": "Il valore deve essere superiore o uguale a {%min}.",
"time": "Il valore deve essere superiore o uguale a {%min}.",
"datetime-local": "Il valore deve essere superiore o uguale a {%min}."
},
"rangeOverflow": {
"defaultMessage": "Il valore deve essere inferiore o uguale a {%max}.",
"date": "Il valore deve essere inferiore o uguale a {%max}.",
"time": "Il valore deve essere inferiore o uguale a {%max}.",
"datetime-local": "Il valore deve essere inferiore o uguale a {%max}."
},
"stepMismatch": "Valore non valido."
};
webshims.formcfg.it = {
numberFormat: {
".": ".",
",": ","
},
numberSigns: '.',
dateSigns: '/',
timeSigns: ":. ",
dFormat: "/",
patterns: {
d: "dd/mm/yy"
},
date: {
closeText: 'Chiudi',
prevText: '<Prec',
nextText: 'Succ>',
currentText: 'Oggi',
monthNames: ['Gennaio','Febbraio','Marzo','Aprile','Maggio','Giugno',
'Luglio','Agosto','Settembre','Ottobre','Novembre','Dicembre'],
monthNamesShort: ['Gen','Feb','Mar','Apr','Mag','Giu',
'Lug','Ago','Set','Ott','Nov','Dic'],
dayNames: ['Domenica','Lunedì','Martedì','Mercoledì','Giovedì','Venerdì','Sabato'],
dayNamesShort: ['Dom','Lun','Mar','Mer','Gio','Ven','Sab'],
dayNamesMin: ['Do','Lu','Ma','Me','Gi','Ve','Sa'],
weekHeader: 'Sm',
firstDay: 1,
isRTL: false,
showMonthAfterYear: false,
yearSuffix: ''
}
}; | kenwheeler/cdnjs | ajax/libs/webshim/1.15.2/dev/shims/i18n/formcfg-it.js | JavaScript | mit | 2,121 |
module Paperclip
# Handles thumbnailing images that are uploaded.
class Thumbnail
attr_accessor :file, :current_geometry, :target_geometry, :format, :whiny_thumbnails, :convert_options
# Creates a Thumbnail object set to work on the +file+ given. It
# will attempt to transform the image into one defined by +target_geometry+
# which is a "WxH"-style string. +format+ will be inferred from the +file+
# unless specified. Thumbnail creation will raise no errors unless
# +whiny_thumbnails+ is true (which it is, by default. If +convert_options+ is
# set, the options will be appended to the convert command upon image conversion
def initialize file, target_geometry, format = nil, convert_options = nil, whiny_thumbnails = true
@file = file
@crop = target_geometry[-1,1] == '#'
@target_geometry = Geometry.parse target_geometry
@current_geometry = Geometry.from_file file
@convert_options = convert_options
@whiny_thumbnails = whiny_thumbnails
@current_format = File.extname(@file.path)
@basename = File.basename(@file.path, @current_format)
@format = format
end
# Creates a thumbnail, as specified in +initialize+, +make+s it, and returns the
# resulting Tempfile.
def self.make file, dimensions, format = nil, convert_options = nil, whiny_thumbnails = true
new(file, dimensions, format, convert_options, whiny_thumbnails).make
end
# Returns true if the +target_geometry+ is meant to crop.
def crop?
@crop
end
# Returns true if the image is meant to make use of additional convert options.
def convert_options?
not @convert_options.blank?
end
# Performs the conversion of the +file+ into a thumbnail. Returns the Tempfile
# that contains the new image.
def make
src = @file
dst = Tempfile.new([@basename, @format].compact.join("."))
dst.binmode
command = <<-end_command
"#{ File.expand_path(src.path) }[0]"
#{ transformation_command }
"#{ File.expand_path(dst.path) }"
end_command
begin
success = Paperclip.run("convert", command.gsub(/\s+/, " "))
rescue PaperclipCommandLineError
raise PaperclipError, "There was an error processing the thumbnail for #{@basename}" if @whiny_thumbnails
end
dst
end
# Returns the command ImageMagick's +convert+ needs to transform the image
# into the thumbnail.
def transformation_command
scale, crop = @current_geometry.transformation_to(@target_geometry, crop?)
trans = "-resize \"#{scale}\""
trans << " -crop \"#{crop}\" +repage" if crop
trans << " #{convert_options}" if convert_options?
trans
end
end
# Due to how ImageMagick handles its image format conversion and how Tempfile
# handles its naming scheme, it is necessary to override how Tempfile makes
# its names so as to allow for file extensions. Idea taken from the comments
# on this blog post:
# http://marsorange.com/archives/of-mogrify-ruby-tempfile-dynamic-class-definitions
class Tempfile < ::Tempfile
# Replaces Tempfile's +make_tmpname+ with one that honors file extensions.
def make_tmpname(basename, n)
extension = File.extname(basename)
sprintf("%s,%d,%d%s", File.basename(basename, extension), $$, n, extension)
end
end
end
| rathish-universum/railscasts-episodes | episode-134/store/vendor/plugins/paperclip/lib/paperclip/thumbnail.rb | Ruby | mit | 3,440 |
/*
* Meshki v1.4.2
* Copyright 2016, Mohammad reza Hajianpour <hajianpour.mr@gmail.com>
* https://borderliner.github.io/Meshki/
* Free to use under the MIT license.
* https://opensource.org/licenses/MIT
*/
function ready(a){document.onreadystatechange=function(){"complete"==document.readyState&&a()}}function is_rtl(){return"rtl"==window.getComputedStyle(document.body,null).getPropertyValue("direction")}ready(function(){document.getElementsByClassName("sidenav")[0]&&(overlayDiv=document.createElement("div"),overlayDiv.className="overlay",overlayDiv.onclick=function(){meshki.closeNav()},document.body.appendChild(overlayDiv))});var meshki={openNav:function(){var a=document.getElementsByClassName("sidenav")[0],b=document.getElementsByClassName("content")[0],c=a.className.split(" ").indexOf("push")>-1,d=document.getElementsByClassName("overlay")[0];a.style.width="250px",window.innerWidth>768&&c&&(document.body.style.overflowX="hidden",is_rtl()?b.style.marginRight="250px":b.style.marginLeft="250px"),d.style.opacity=.4,d.style.visibility="visible"},closeNav:function(){var a=document.getElementsByClassName("sidenav")[0],b=document.getElementsByClassName("content")[0],c=document.getElementsByClassName("overlay")[0],d=a.className.split(" ").indexOf("push")>-1;a.style.width="0",window.innerWidth>768&&d&&(b.style.margin="0"),c.style.opacity=0,c.style.visibility="hidden"}};
| jonobr1/cdnjs | ajax/libs/meshki/1.4.2/meshki.min.js | JavaScript | mit | 1,384 |
<?php
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Support\Collection;
use Illuminate\Support\Debug\Dumper;
use Illuminate\Contracts\Support\Htmlable;
if (!function_exists('append_config')) {
/**
* Assign high numeric IDs to a config item to force appending.
*
* @param array $array
* @return array
*/
function append_config(array $array)
{
$start = 9999;
foreach ($array as $key => $value) {
if (is_numeric($key)) {
$start++;
$array[$start] = Arr::pull($array, $key);
}
}
return $array;
}
}
if (!function_exists('array_add')) {
/**
* Add an element to an array using "dot" notation if it doesn't exist.
*
* @param array $array
* @param string $key
* @param mixed $value
* @return array
*/
function array_add($array, $key, $value)
{
return Arr::add($array, $key, $value);
}
}
if (!function_exists('array_build')) {
/**
* Build a new array using a callback.
*
* @param array $array
* @param callable $callback
* @return array
*/
function array_build($array, callable $callback)
{
return Arr::build($array, $callback);
}
}
if (!function_exists('array_collapse')) {
/**
* Collapse an array of arrays into a single array.
*
* @param array|\ArrayAccess $array
* @return array
*/
function array_collapse($array)
{
return Arr::collapse($array);
}
}
if (!function_exists('array_divide')) {
/**
* Divide an array into two arrays. One with keys and the other with values.
*
* @param array $array
* @return array
*/
function array_divide($array)
{
return Arr::divide($array);
}
}
if (!function_exists('array_dot')) {
/**
* Flatten a multi-dimensional associative array with dots.
*
* @param array $array
* @param string $prepend
* @return array
*/
function array_dot($array, $prepend = '')
{
return Arr::dot($array, $prepend);
}
}
if (!function_exists('array_except')) {
/**
* Get all of the given array except for a specified array of items.
*
* @param array $array
* @param array|string $keys
* @return array
*/
function array_except($array, $keys)
{
return Arr::except($array, $keys);
}
}
if (!function_exists('array_fetch')) {
/**
* Fetch a flattened array of a nested array element.
*
* @param array $array
* @param string $key
* @return array
*
* @deprecated since version 5.1. Use array_pluck instead.
*/
function array_fetch($array, $key)
{
return Arr::fetch($array, $key);
}
}
if (!function_exists('array_first')) {
/**
* Return the first element in an array passing a given truth test.
*
* @param array $array
* @param callable $callback
* @param mixed $default
* @return mixed
*/
function array_first($array, callable $callback, $default = null)
{
return Arr::first($array, $callback, $default);
}
}
if (!function_exists('array_last')) {
/**
* Return the last element in an array passing a given truth test.
*
* @param array $array
* @param callable $callback
* @param mixed $default
* @return mixed
*/
function array_last($array, $callback, $default = null)
{
return Arr::last($array, $callback, $default);
}
}
if (!function_exists('array_flatten')) {
/**
* Flatten a multi-dimensional array into a single level.
*
* @param array $array
* @return array
*/
function array_flatten($array)
{
return Arr::flatten($array);
}
}
if (!function_exists('array_forget')) {
/**
* Remove one or many array items from a given array using "dot" notation.
*
* @param array $array
* @param array|string $keys
* @return void
*/
function array_forget(&$array, $keys)
{
return Arr::forget($array, $keys);
}
}
if (!function_exists('array_get')) {
/**
* Get an item from an array using "dot" notation.
*
* @param array $array
* @param string $key
* @param mixed $default
* @return mixed
*/
function array_get($array, $key, $default = null)
{
return Arr::get($array, $key, $default);
}
}
if (!function_exists('array_has')) {
/**
* Check if an item exists in an array using "dot" notation.
*
* @param array $array
* @param string $key
* @return bool
*/
function array_has($array, $key)
{
return Arr::has($array, $key);
}
}
if (!function_exists('array_only')) {
/**
* Get a subset of the items from the given array.
*
* @param array $array
* @param array|string $keys
* @return array
*/
function array_only($array, $keys)
{
return Arr::only($array, $keys);
}
}
if (!function_exists('array_pluck')) {
/**
* Pluck an array of values from an array.
*
* @param array $array
* @param string $value
* @param string $key
* @return array
*/
function array_pluck($array, $value, $key = null)
{
return Arr::pluck($array, $value, $key);
}
}
if (!function_exists('array_pull')) {
/**
* Get a value from the array, and remove it.
*
* @param array $array
* @param string $key
* @param mixed $default
* @return mixed
*/
function array_pull(&$array, $key, $default = null)
{
return Arr::pull($array, $key, $default);
}
}
if (!function_exists('array_set')) {
/**
* Set an array item to a given value using "dot" notation.
*
* If no key is given to the method, the entire array will be replaced.
*
* @param array $array
* @param string $key
* @param mixed $value
* @return array
*/
function array_set(&$array, $key, $value)
{
return Arr::set($array, $key, $value);
}
}
if (!function_exists('array_sort')) {
/**
* Sort the array using the given callback.
*
* @param array $array
* @param callable $callback
* @return array
*/
function array_sort($array, callable $callback)
{
return Arr::sort($array, $callback);
}
}
if (!function_exists('array_sort_recursive')) {
/**
* Recursively sort an array by keys and values.
*
* @param array $array
* @return array
*/
function array_sort_recursive($array)
{
return Arr::sortRecursive($array);
}
}
if (!function_exists('array_where')) {
/**
* Filter the array using the given callback.
*
* @param array $array
* @param callable $callback
* @return array
*/
function array_where($array, callable $callback)
{
return Arr::where($array, $callback);
}
}
if (!function_exists('camel_case')) {
/**
* Convert a value to camel case.
*
* @param string $value
* @return string
*/
function camel_case($value)
{
return Str::camel($value);
}
}
if (!function_exists('class_basename')) {
/**
* Get the class "basename" of the given object / class.
*
* @param string|object $class
* @return string
*/
function class_basename($class)
{
$class = is_object($class) ? get_class($class) : $class;
return basename(str_replace('\\', '/', $class));
}
}
if (!function_exists('class_uses_recursive')) {
/**
* Returns all traits used by a class, its subclasses and trait of their traits.
*
* @param string $class
* @return array
*/
function class_uses_recursive($class)
{
$results = [];
foreach (array_merge([$class => $class], class_parents($class)) as $class) {
$results += trait_uses_recursive($class);
}
return array_unique($results);
}
}
if (!function_exists('collect')) {
/**
* Create a collection from the given value.
*
* @param mixed $value
* @return \Illuminate\Support\Collection
*/
function collect($value = null)
{
return new Collection($value);
}
}
if (!function_exists('data_get')) {
/**
* Get an item from an array or object using "dot" notation.
*
* @param mixed $target
* @param string|array $key
* @param mixed $default
* @return mixed
*/
function data_get($target, $key, $default = null)
{
if (is_null($key)) {
return $target;
}
$key = is_array($key) ? $key : explode('.', $key);
foreach ($key as $segment) {
if (is_array($target)) {
if (!array_key_exists($segment, $target)) {
return value($default);
}
$target = $target[$segment];
} elseif ($target instanceof ArrayAccess) {
if (!isset($target[$segment])) {
return value($default);
}
$target = $target[$segment];
} elseif (is_object($target)) {
if (!isset($target->{$segment})) {
return value($default);
}
$target = $target->{$segment};
} else {
return value($default);
}
}
return $target;
}
}
if (!function_exists('dd')) {
/**
* Dump the passed variables and end the script.
*
* @param mixed
* @return void
*/
function dd()
{
array_map(function ($x) {
(new Dumper)->dump($x);
}, func_get_args());
die(1);
}
}
if (!function_exists('e')) {
/**
* Escape HTML entities in a string.
*
* @param \Illuminate\Support\Htmlable|string $value
* @return string
*/
function e($value)
{
if ($value instanceof Htmlable) {
return $value->toHtml();
}
return htmlentities($value, ENT_QUOTES, 'UTF-8', false);
}
}
if (!function_exists('ends_with')) {
/**
* Determine if a given string ends with a given substring.
*
* @param string $haystack
* @param string|array $needles
* @return bool
*/
function ends_with($haystack, $needles)
{
return Str::endsWith($haystack, $needles);
}
}
if (!function_exists('head')) {
/**
* Get the first element of an array. Useful for method chaining.
*
* @param array $array
* @return mixed
*/
function head($array)
{
return reset($array);
}
}
if (!function_exists('last')) {
/**
* Get the last element from an array.
*
* @param array $array
* @return mixed
*/
function last($array)
{
return end($array);
}
}
if (!function_exists('object_get')) {
/**
* Get an item from an object using "dot" notation.
*
* @param object $object
* @param string $key
* @param mixed $default
* @return mixed
*/
function object_get($object, $key, $default = null)
{
if (is_null($key) || trim($key) == '') {
return $object;
}
foreach (explode('.', $key) as $segment) {
if (!is_object($object) || !isset($object->{$segment})) {
return value($default);
}
$object = $object->{$segment};
}
return $object;
}
}
if (!function_exists('preg_replace_sub')) {
/**
* Replace a given pattern with each value in the array in sequentially.
*
* @param string $pattern
* @param array $replacements
* @param string $subject
* @return string
*/
function preg_replace_sub($pattern, &$replacements, $subject)
{
return preg_replace_callback($pattern, function ($match) use (&$replacements) {
foreach ($replacements as $key => $value) {
return array_shift($replacements);
}
}, $subject);
}
}
if (!function_exists('snake_case')) {
/**
* Convert a string to snake case.
*
* @param string $value
* @param string $delimiter
* @return string
*/
function snake_case($value, $delimiter = '_')
{
return Str::snake($value, $delimiter);
}
}
if (!function_exists('starts_with')) {
/**
* Determine if a given string starts with a given substring.
*
* @param string $haystack
* @param string|array $needles
* @return bool
*/
function starts_with($haystack, $needles)
{
return Str::startsWith($haystack, $needles);
}
}
if (!function_exists('str_contains')) {
/**
* Determine if a given string contains a given substring.
*
* @param string $haystack
* @param string|array $needles
* @return bool
*/
function str_contains($haystack, $needles)
{
return Str::contains($haystack, $needles);
}
}
if (!function_exists('str_finish')) {
/**
* Cap a string with a single instance of a given value.
*
* @param string $value
* @param string $cap
* @return string
*/
function str_finish($value, $cap)
{
return Str::finish($value, $cap);
}
}
if (!function_exists('str_is')) {
/**
* Determine if a given string matches a given pattern.
*
* @param string $pattern
* @param string $value
* @return bool
*/
function str_is($pattern, $value)
{
return Str::is($pattern, $value);
}
}
if (!function_exists('str_limit')) {
/**
* Limit the number of characters in a string.
*
* @param string $value
* @param int $limit
* @param string $end
* @return string
*/
function str_limit($value, $limit = 100, $end = '...')
{
return Str::limit($value, $limit, $end);
}
}
if (!function_exists('str_plural')) {
/**
* Get the plural form of an English word.
*
* @param string $value
* @param int $count
* @return string
*/
function str_plural($value, $count = 2)
{
return Str::plural($value, $count);
}
}
if (!function_exists('str_random')) {
/**
* Generate a more truly "random" alpha-numeric string.
*
* @param int $length
* @return string
*
* @throws \RuntimeException
*/
function str_random($length = 16)
{
return Str::random($length);
}
}
if (!function_exists('str_replace_array')) {
/**
* Replace a given value in the string sequentially with an array.
*
* @param string $search
* @param array $replace
* @param string $subject
* @return string
*/
function str_replace_array($search, array $replace, $subject)
{
foreach ($replace as $value) {
$subject = preg_replace('/'.$search.'/', $value, $subject, 1);
}
return $subject;
}
}
if (!function_exists('str_singular')) {
/**
* Get the singular form of an English word.
*
* @param string $value
* @return string
*/
function str_singular($value)
{
return Str::singular($value);
}
}
if (!function_exists('str_slug')) {
/**
* Generate a URL friendly "slug" from a given string.
*
* @param string $title
* @param string $separator
* @return string
*/
function str_slug($title, $separator = '-')
{
return Str::slug($title, $separator);
}
}
if (!function_exists('studly_case')) {
/**
* Convert a value to studly caps case.
*
* @param string $value
* @return string
*/
function studly_case($value)
{
return Str::studly($value);
}
}
if (!function_exists('title_case')) {
/**
* Convert a value to title case.
*
* @param string $value
* @return string
*/
function title_case($value)
{
return Str::title($value);
}
}
if (!function_exists('trait_uses_recursive')) {
/**
* Returns all traits used by a trait and its traits.
*
* @param string $trait
* @return array
*/
function trait_uses_recursive($trait)
{
$traits = class_uses($trait);
foreach ($traits as $trait) {
$traits += trait_uses_recursive($trait);
}
return $traits;
}
}
if (!function_exists('value')) {
/**
* Return the default value of the given value.
*
* @param mixed $value
* @return mixed
*/
function value($value)
{
return $value instanceof Closure ? $value() : $value;
}
}
if (!function_exists('with')) {
/**
* Return the given object. Useful for chaining.
*
* @param mixed $object
* @return mixed
*/
function with($object)
{
return $object;
}
}
| absalan/Test | vendor/laravel/framework/src/Illuminate/Support/helpers.php | PHP | mit | 17,271 |
/*************************************************
* Perl-Compatible Regular Expressions *
*************************************************/
/* PCRE is a library of functions to support regular expressions whose syntax
and semantics are as close as possible to those of the Perl 5 language.
Written by Philip Hazel
Copyright (c) 1997-2010 University of Cambridge
-----------------------------------------------------------------------------
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the University of Cambridge nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------------
*/
/* This module contains an internal function that is used to match an extended
class. It is used by both pcre_exec() and pcre_def_exec(). */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "pcre_internal.h"
/*************************************************
* Match character against an XCLASS *
*************************************************/
/* This function is called to match a character against an extended class that
might contain values > 255 and/or Unicode properties.
Arguments:
c the character
data points to the flag byte of the XCLASS data
Returns: TRUE if character matches, else FALSE
*/
BOOL
_pcre_xclass(int c, const uschar *data)
{
int t;
BOOL negated = (*data & XCL_NOT) != 0;
/* Character values < 256 are matched against a bitmap, if one is present. If
not, we still carry on, because there may be ranges that start below 256 in the
additional data. */
if (c < 256)
{
if ((*data & XCL_MAP) != 0 && (data[1 + c/8] & (1 << (c&7))) != 0)
return !negated; /* char found */
}
/* First skip the bit map if present. Then match against the list of Unicode
properties or large chars or ranges that end with a large char. We won't ever
encounter XCL_PROP or XCL_NOTPROP when UCP support is not compiled. */
if ((*data++ & XCL_MAP) != 0) data += 32;
while ((t = *data++) != XCL_END)
{
int x, y;
if (t == XCL_SINGLE)
{
GETCHARINC(x, data);
if (c == x) return !negated;
}
else if (t == XCL_RANGE)
{
GETCHARINC(x, data);
GETCHARINC(y, data);
if (c >= x && c <= y) return !negated;
}
#ifdef SUPPORT_UCP
else /* XCL_PROP & XCL_NOTPROP */
{
const ucd_record *prop = GET_UCD(c);
switch(*data)
{
case PT_ANY:
if (t == XCL_PROP) return !negated;
break;
case PT_LAMP:
if ((prop->chartype == ucp_Lu || prop->chartype == ucp_Ll ||
prop->chartype == ucp_Lt) == (t == XCL_PROP)) return !negated;
break;
case PT_GC:
if ((data[1] == _pcre_ucp_gentype[prop->chartype]) == (t == XCL_PROP))
return !negated;
break;
case PT_PC:
if ((data[1] == prop->chartype) == (t == XCL_PROP)) return !negated;
break;
case PT_SC:
if ((data[1] == prop->script) == (t == XCL_PROP)) return !negated;
break;
case PT_ALNUM:
if ((_pcre_ucp_gentype[prop->chartype] == ucp_L ||
_pcre_ucp_gentype[prop->chartype] == ucp_N) == (t == XCL_PROP))
return !negated;
break;
case PT_SPACE: /* Perl space */
if ((_pcre_ucp_gentype[prop->chartype] == ucp_Z ||
c == CHAR_HT || c == CHAR_NL || c == CHAR_FF || c == CHAR_CR)
== (t == XCL_PROP))
return !negated;
break;
case PT_PXSPACE: /* POSIX space */
if ((_pcre_ucp_gentype[prop->chartype] == ucp_Z ||
c == CHAR_HT || c == CHAR_NL || c == CHAR_VT ||
c == CHAR_FF || c == CHAR_CR) == (t == XCL_PROP))
return !negated;
break;
case PT_WORD:
if ((_pcre_ucp_gentype[prop->chartype] == ucp_L ||
_pcre_ucp_gentype[prop->chartype] == ucp_N || c == CHAR_UNDERSCORE)
== (t == XCL_PROP))
return !negated;
break;
/* This should never occur, but compilers may mutter if there is no
default. */
default:
return FALSE;
}
data += 2;
}
#endif /* SUPPORT_UCP */
}
return negated; /* char did not match */
}
/* End of pcre_xclass.c */
| utsav2601/cmpe295A | lib/pcre/pcre_xclass.c | C | mit | 5,566 |
<?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\VarDumper\Dumper\ContextProvider;
use Symfony\Component\HttpKernel\Debug\FileLinkFormatter;
use Symfony\Component\VarDumper\Cloner\VarCloner;
use Symfony\Component\VarDumper\Dumper\HtmlDumper;
use Symfony\Component\VarDumper\VarDumper;
use Twig\Template;
/**
* Tries to provide context from sources (class name, file, line, code excerpt, ...).
*
* @author Nicolas Grekas <p@tchwork.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
final class SourceContextProvider implements ContextProviderInterface
{
private $limit;
private $charset;
private $projectDir;
private $fileLinkFormatter;
public function __construct(string $charset = null, string $projectDir = null, FileLinkFormatter $fileLinkFormatter = null, int $limit = 9)
{
$this->charset = $charset;
$this->projectDir = $projectDir;
$this->fileLinkFormatter = $fileLinkFormatter;
$this->limit = $limit;
}
public function getContext(): ?array
{
$trace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT | DEBUG_BACKTRACE_IGNORE_ARGS, $this->limit);
$file = $trace[1]['file'];
$line = $trace[1]['line'];
$name = false;
$fileExcerpt = false;
for ($i = 2; $i < $this->limit; ++$i) {
if (isset($trace[$i]['class'], $trace[$i]['function'])
&& 'dump' === $trace[$i]['function']
&& VarDumper::class === $trace[$i]['class']
) {
$file = $trace[$i]['file'];
$line = $trace[$i]['line'];
while (++$i < $this->limit) {
if (isset($trace[$i]['function'], $trace[$i]['file']) && empty($trace[$i]['class']) && 0 !== strpos($trace[$i]['function'], 'call_user_func')) {
$file = $trace[$i]['file'];
$line = $trace[$i]['line'];
break;
} elseif (isset($trace[$i]['object']) && $trace[$i]['object'] instanceof Template) {
$template = $trace[$i]['object'];
$name = $template->getTemplateName();
$src = method_exists($template, 'getSourceContext') ? $template->getSourceContext()->getCode() : (method_exists($template, 'getSource') ? $template->getSource() : false);
$info = $template->getDebugInfo();
if (isset($info[$trace[$i - 1]['line']])) {
$line = $info[$trace[$i - 1]['line']];
$file = method_exists($template, 'getSourceContext') ? $template->getSourceContext()->getPath() : null;
if ($src) {
$src = explode("\n", $src);
$fileExcerpt = [];
for ($i = max($line - 3, 1), $max = min($line + 3, \count($src)); $i <= $max; ++$i) {
$fileExcerpt[] = '<li'.($i === $line ? ' class="selected"' : '').'><code>'.$this->htmlEncode($src[$i - 1]).'</code></li>';
}
$fileExcerpt = '<ol start="'.max($line - 3, 1).'">'.implode("\n", $fileExcerpt).'</ol>';
}
}
break;
}
}
break;
}
}
if (false === $name) {
$name = str_replace('\\', '/', $file);
$name = substr($name, strrpos($name, '/') + 1);
}
$context = ['name' => $name, 'file' => $file, 'line' => $line];
$context['file_excerpt'] = $fileExcerpt;
if (null !== $this->projectDir) {
$context['project_dir'] = $this->projectDir;
if (0 === strpos($file, $this->projectDir)) {
$context['file_relative'] = ltrim(substr($file, \strlen($this->projectDir)), \DIRECTORY_SEPARATOR);
}
}
if ($this->fileLinkFormatter && $fileLink = $this->fileLinkFormatter->format($context['file'], $context['line'])) {
$context['file_link'] = $fileLink;
}
return $context;
}
private function htmlEncode(string $s): string
{
$html = '';
$dumper = new HtmlDumper(function ($line) use (&$html) { $html .= $line; }, $this->charset);
$dumper->setDumpHeader('');
$dumper->setDumpBoundaries('', '');
$cloner = new VarCloner();
$dumper->dump($cloner->cloneVar($s));
return substr(strip_tags($html), 1, -1);
}
}
| arjenm/symfony | src/Symfony/Component/VarDumper/Dumper/ContextProvider/SourceContextProvider.php | PHP | mit | 4,871 |
#!/usr/bin/python
# coding=utf-8
##########################################################################
import os
from test import CollectorTestCase
from test import get_collector_config
from test import unittest
from mock import patch
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
from diamond.collector import Collector
from cpuacct_cgroup import CpuAcctCgroupCollector
class TestCpuAcctCgroupCollector(CollectorTestCase):
def setUp(self):
config = get_collector_config('CpuAcctCgroupCollector', {
'interval': 10
})
self.collector = CpuAcctCgroupCollector(config, None)
def test_import(self):
self.assertTrue(CpuAcctCgroupCollector)
@patch('__builtin__.open')
@patch.object(Collector, 'publish')
def test_should_open_all_cpuacct_stat(self, publish_mock, open_mock):
return
self.collector.config['path'] = self.getFixtureDirPath()
open_mock.side_effect = lambda x: StringIO('')
self.collector.collect()
# All the fixtures we should be opening
paths = [
'lxc/testcontainer/cpuacct.stat',
'lxc/cpuacct.stat',
'cpuacct.stat',
]
for path in paths:
open_mock.assert_any_call(os.path.join(
self.getFixtureDirPath(), path))
@patch.object(Collector, 'publish')
def test_should_work_with_real_data(self, publish_mock):
self.collector.config['path'] = self.getFixtureDirPath()
self.collector.collect()
self.assertPublishedMany(publish_mock, {
'lxc.testcontainer.user': 1318,
'lxc.testcontainer.system': 332,
'lxc.user': 36891,
'lxc.system': 88927,
'system.user': 3781253,
'system.system': 4784004,
})
if __name__ == "__main__":
unittest.main()
| python-diamond/Diamond | src/collectors/cpuacct_cgroup/test/testcpuacct_cgroup.py | Python | mit | 1,908 |
/*
TimelineJS - ver. 2.36.0 - 2015-05-12
Copyright (c) 2012-2013 Northwestern University
a project of the Northwestern University Knight Lab, originally created by Zach Wise
https://github.com/NUKnightLab/TimelineJS
This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
if(typeof VMM!="undefined"){VMM.Language={lang:"hu",api:{wikipedia:"hu"},date:{month:["január","február","március","április","május","június","július","augusztus","szeptember","október","november","december"],month_abbr:["jan.","febr.","márc.","ápr.","máj.","jún.","júl.","aug.","szept.","okt.","nov.","dec."],day:["vasárnap","hétfő","kedd","szerda","csütörtök","péntek","szombat"],day_abbr:["vas.","hétfő","kedd","szer.","csüt.","pén.","szom."]},dateformats:{year:"yyyy",month_short:"mmm",month:"yyyy. mmmm",full_short:"mmm d.",full:"yyyy. mmmm d.",time_short:"HH:MM:SS",time_no_seconds_short:"HH:MM",time_no_seconds_small_date:"HH:MM '<br/><small>'yyyy. mmmm d.'</small>'",full_long:"yyyy. mmm d.',' HH:MM",full_long_small_date:"HH:MM '<br/><small>yyyy. mmm d.'</small>'"},messages:{loading_timeline:"Az idővonal betöltése... ",return_to_title:"Vissza a címhez",expand_timeline:"Nagyítás",contract_timeline:"Kicsinyítés",wikipedia:"A Wikipédiából, a szabad enciklopédiából",loading_content:"Tartalom betöltése",loading:"Betöltés",swipe_nav:"Swipe to Navigate"}}} | maxklenk/cdnjs | ajax/libs/timelinejs/2.36.0/js/locale/hu.js | JavaScript | mit | 1,542 |
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\Common\Persistence;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Persistence\Mapping\ClassMetadata;
/**
* PersistentObject base class that implements getter/setter methods for all mapped fields and associations
* by overriding __call.
*
* This class is a forward compatible implementation of the PersistentObject trait.
*
* Limitations:
*
* 1. All persistent objects have to be associated with a single ObjectManager, multiple
* ObjectManagers are not supported. You can set the ObjectManager with `PersistentObject#setObjectManager()`.
* 2. Setters and getters only work if a ClassMetadata instance was injected into the PersistentObject.
* This is either done on `postLoad` of an object or by accessing the global object manager.
* 3. There are no hooks for setters/getters. Just implement the method yourself instead of relying on __call().
* 4. Slower than handcoded implementations: An average of 7 method calls per access to a field and 11 for an association.
* 5. Only the inverse side associations get autoset on the owning side as well. Setting objects on the owning side
* will not set the inverse side associations.
*
* @example
*
* PersistentObject::setObjectManager($em);
*
* class Foo extends PersistentObject
* {
* private $id;
* }
*
* $foo = new Foo();
* $foo->getId(); // method exists through __call
*
* @author Benjamin Eberlei <kontakt@beberlei.de>
*/
abstract class PersistentObject implements ObjectManagerAware
{
/**
* @var ObjectManager|null
*/
private static $objectManager = null;
/**
* @var ClassMetadata|null
*/
private $cm = null;
/**
* Sets the object manager responsible for all persistent object base classes.
*
* @param ObjectManager|null $objectManager
*
* @return void
*/
static public function setObjectManager(ObjectManager $objectManager = null)
{
self::$objectManager = $objectManager;
}
/**
* @return ObjectManager|null
*/
static public function getObjectManager()
{
return self::$objectManager;
}
/**
* Injects the Doctrine Object Manager.
*
* @param ObjectManager $objectManager
* @param ClassMetadata $classMetadata
*
* @return void
*
* @throws \RuntimeException
*/
public function injectObjectManager(ObjectManager $objectManager, ClassMetadata $classMetadata)
{
if ($objectManager !== self::$objectManager) {
throw new \RuntimeException("Trying to use PersistentObject with different ObjectManager instances. " .
"Was PersistentObject::setObjectManager() called?");
}
$this->cm = $classMetadata;
}
/**
* Sets a persistent fields value.
*
* @param string $field
* @param array $args
*
* @return void
*
* @throws \BadMethodCallException When no persistent field exists by that name.
* @throws \InvalidArgumentException When the wrong target object type is passed to an association.
*/
private function set($field, $args)
{
$this->initializeDoctrine();
if ($this->cm->hasField($field) && !$this->cm->isIdentifier($field)) {
$this->$field = $args[0];
} else if ($this->cm->hasAssociation($field) && $this->cm->isSingleValuedAssociation($field)) {
$targetClass = $this->cm->getAssociationTargetClass($field);
if (!($args[0] instanceof $targetClass) && $args[0] !== null) {
throw new \InvalidArgumentException("Expected persistent object of type '".$targetClass."'");
}
$this->$field = $args[0];
$this->completeOwningSide($field, $targetClass, $args[0]);
} else {
throw new \BadMethodCallException("no field with name '".$field."' exists on '".$this->cm->getName()."'");
}
}
/**
* Gets a persistent field value.
*
* @param string $field
*
* @return mixed
*
* @throws \BadMethodCallException When no persistent field exists by that name.
*/
private function get($field)
{
$this->initializeDoctrine();
if ( $this->cm->hasField($field) || $this->cm->hasAssociation($field) ) {
return $this->$field;
} else {
throw new \BadMethodCallException("no field with name '".$field."' exists on '".$this->cm->getName()."'");
}
}
/**
* If this is an inverse side association, completes the owning side.
*
* @param string $field
* @param ClassMetadata $targetClass
* @param object $targetObject
*
* @return void
*/
private function completeOwningSide($field, $targetClass, $targetObject)
{
// add this object on the owning side as well, for obvious infinite recursion
// reasons this is only done when called on the inverse side.
if ($this->cm->isAssociationInverseSide($field)) {
$mappedByField = $this->cm->getAssociationMappedByTargetField($field);
$targetMetadata = self::$objectManager->getClassMetadata($targetClass);
$setter = ($targetMetadata->isCollectionValuedAssociation($mappedByField) ? "add" : "set").$mappedByField;
$targetObject->$setter($this);
}
}
/**
* Adds an object to a collection.
*
* @param string $field
* @param array $args
*
* @return void
*
* @throws \BadMethodCallException
* @throws \InvalidArgumentException
*/
private function add($field, $args)
{
$this->initializeDoctrine();
if ($this->cm->hasAssociation($field) && $this->cm->isCollectionValuedAssociation($field)) {
$targetClass = $this->cm->getAssociationTargetClass($field);
if (!($args[0] instanceof $targetClass)) {
throw new \InvalidArgumentException("Expected persistent object of type '".$targetClass."'");
}
if (!($this->$field instanceof Collection)) {
$this->$field = new ArrayCollection($this->$field ?: []);
}
$this->$field->add($args[0]);
$this->completeOwningSide($field, $targetClass, $args[0]);
} else {
throw new \BadMethodCallException("There is no method add".$field."() on ".$this->cm->getName());
}
}
/**
* Initializes Doctrine Metadata for this class.
*
* @return void
*
* @throws \RuntimeException
*/
private function initializeDoctrine()
{
if ($this->cm !== null) {
return;
}
if (!self::$objectManager) {
throw new \RuntimeException("No runtime object manager set. Call PersistentObject#setObjectManager().");
}
$this->cm = self::$objectManager->getClassMetadata(get_class($this));
}
/**
* Magic methods.
*
* @param string $method
* @param array $args
*
* @return mixed
*
* @throws \BadMethodCallException
*/
public function __call($method, $args)
{
$command = substr($method, 0, 3);
$field = lcfirst(substr($method, 3));
if ($command == "set") {
$this->set($field, $args);
} else if ($command == "get") {
return $this->get($field);
} else if ($command == "add") {
$this->add($field, $args);
} else {
throw new \BadMethodCallException("There is no method ".$method." on ".$this->cm->getName());
}
}
}
| PivotDev/pivot_custom_upstream | vendor/doctrine/common/lib/Doctrine/Common/Persistence/PersistentObject.php | PHP | mit | 8,691 |
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("MyClassLibrary")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MyClassLibrary")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("cd678800-8dfc-4bb1-911a-7234f492ea29")]
// 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")]
| snowcrazed/Paket | integrationtests/scenarios/i001427-content-true/before/MyClassLibrary/MyClassLibrary/Properties/AssemblyInfo.cs | C# | mit | 1,404 |
<?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\Extension\Core\DataTransformer;
use Symfony\Component\Form\Exception\TransformationFailedException;
/**
* @author Bernhard Schussek <bschussek@gmail.com>
*/
class DateTimeToRfc3339Transformer extends BaseDateTimeTransformer
{
/**
* {@inheritDoc}
*/
public function transform($dateTime)
{
if (null === $dateTime) {
return '';
}
if (!$dateTime instanceof \DateTime) {
throw new TransformationFailedException('Expected a \DateTime.');
}
if ($this->inputTimezone !== $this->outputTimezone) {
$dateTime = clone $dateTime;
$dateTime->setTimezone(new \DateTimeZone($this->outputTimezone));
}
return preg_replace('/\+00:00$/', 'Z', $dateTime->format('c'));
}
/**
* {@inheritDoc}
*/
public function reverseTransform($rfc3339)
{
if (!is_string($rfc3339)) {
throw new TransformationFailedException('Expected a string.');
}
if ('' === $rfc3339) {
return null;
}
try {
$dateTime = new \DateTime($rfc3339);
} catch (\Exception $e) {
throw new TransformationFailedException($e->getMessage(), $e->getCode(), $e);
}
if ($this->outputTimezone !== $dateTime->getTimezone()->getName()) {
try {
$dateTime->setTimezone(new \DateTimeZone($this->inputTimezone));
} catch (\Exception $e) {
throw new TransformationFailedException($e->getMessage(), $e->getCode(), $e);
}
}
if (preg_match('/(\d{4})-(\d{2})-(\d{2})/', $rfc3339, $matches)) {
if (!checkdate($matches[2], $matches[3], $matches[1])) {
throw new TransformationFailedException(sprintf(
'The date "%s-%s-%s" is not a valid date.',
$matches[1],
$matches[2],
$matches[3]
));
}
}
return $dateTime;
}
}
| Kitanoo/Symfony2 | vendor/symfony/symfony/src/Symfony/Component/Form/Extension/Core/DataTransformer/DateTimeToRfc3339Transformer.php | PHP | mit | 2,320 |
'use strict';
module.exports = function (grunt) {
grunt.initConfig({
jshint: {
options: {
jshintrc: '.jshintrc'
},
files: ['Gruntfile.js', 'bin/*', 'lib/**/*.js', 'test/*.js']
},
simplemocha: {
options: {
reporter: 'spec',
timeout: '5000'
},
full: { src: ['test/*.js'] },
short: {
options: {
reporter: 'dot'
},
src: ['<%= simplemocha.full.src %>']
}
},
exec: {
coverage: {
command: 'node node_modules/istanbul/lib/cli.js cover --dir ./coverage node_modules/mocha/bin/_mocha -- -R dot test/*.js'
},
'test-files': {
command: 'node download-test-assets.js'
}
},
watch: {
files: ['<%= jshint.files %>'],
tasks: ['jshint', 'simplemocha:short']
}
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-simple-mocha');
grunt.loadNpmTasks('grunt-exec');
grunt.registerTask('test', ['jshint', 'simplemocha:full']);
grunt.registerTask('coverage', 'exec:coverage');
grunt.registerTask('test-files', 'exec:test-files');
grunt.registerTask('default', 'test');
};
| row3/commune3 | node_modules/bower/node_modules/decompress-zip/Gruntfile.js | JavaScript | mit | 1,435 |
/*
* A battery of tests for sucessful round-trip between writes and reads
*/
var mod_ctype = require('../../../ctio.js');
var ASSERT = require('assert');
/*
* What the heck, let's just test every value for 8-bits.
*/
function test8() {
var data = new Buffer(1);
var i;
for (i = 0; i < 256; i++) {
mod_ctype.wuint8(i, 'big', data, 0);
ASSERT.equal(i, mod_ctype.ruint8(data, 'big', 0));
mod_ctype.wuint8(i, 'little', data, 0);
ASSERT.equal(i, mod_ctype.ruint8(data, 'little', 0));
}
ASSERT.ok(true);
}
/*
* Test a random sample of 256 values in the 16-bit unsigned range
*/
function test16() {
var data = new Buffer(2);
var i = 0;
for (i = 0; i < 256; i++) {
var value = Math.round(Math.random() * Math.pow(2, 16));
mod_ctype.wuint16(value, 'big', data, 0);
ASSERT.equal(value, mod_ctype.ruint16(data, 'big', 0));
mod_ctype.wuint16(value, 'little', data, 0);
ASSERT.equal(value, mod_ctype.ruint16(data, 'little', 0));
}
}
/*
* Test a random sample of 256 values in the 32-bit unsigned range
*/
function test32() {
var data = new Buffer(4);
var i = 0;
for (i = 0; i < 256; i++) {
var value = Math.round(Math.random() * Math.pow(2, 32));
mod_ctype.wuint32(value, 'big', data, 0);
ASSERT.equal(value, mod_ctype.ruint32(data, 'big', 0));
mod_ctype.wuint32(value, 'little', data, 0);
ASSERT.equal(value, mod_ctype.ruint32(data, 'little', 0));
}
}
/*
* Test a random sample of 256 values in the 64-bit unsigned range
*/
function test64() {
var data = new Buffer(8);
var i = 0;
for (i = 0; i < 256; i++) {
var low = Math.round(Math.random() * Math.pow(2, 32));
var high = Math.round(Math.random() * Math.pow(2, 32));
mod_ctype.wuint64([high, low], 'big', data, 0);
var result = mod_ctype.ruint64(data, 'big', 0);
ASSERT.equal(high, result[0]);
ASSERT.equal(low, result[1]);
mod_ctype.wuint64([high, low], 'little', data, 0);
result = mod_ctype.ruint64(data, 'little', 0);
ASSERT.equal(high, result[0]);
ASSERT.equal(low, result[1]);
}
}
exports.test8 = test8;
exports.test16 = test16;
exports.test32 = test32;
exports.test64 = test64;
| juanrules/juan-pernia-wordpress-theme | node_modules/grunt-contrib-less/node_modules/less/node_modules/request/node_modules/http-signature/node_modules/ctype/tst/ctio/uint/tst.roundtrip.js | JavaScript | mit | 2,112 |
window.FlashCanvasOptions = window.FlashCanvasOptions || {};
webshims.$.extend(FlashCanvasOptions, {
swfPath: webshims.cfg.basePath + 'FlashCanvas/'
});
/*
* FlashCanvas
*
* Copyright (c) 2009 Tim Cameron Ryan
* Copyright (c) 2009-2013 FlashCanvas Project
* Released under the MIT/X License
*/
window.ActiveXObject&&!window.CanvasRenderingContext2D&&function(i,j,z){function D(a){this.code=a;this.message=R[a]}function S(a){this.width=a}function v(a){this.id=a.C++}function k(a){this.G=a;this.id=a.C++}function m(a,b){this.canvas=a;this.B=b;this.d=b.id.slice(8);this.D();this.C=0;this.f=this.u="";var c=this;setInterval(function(){o[c.d]===0&&c.e()},30)}function A(){if(j.readyState==="complete"){j.detachEvent(E,A);for(var a=j.getElementsByTagName(r),b=0,c=a.length;b<c;++b)B.initElement(a[b])}}
function F(){var a=event.srcElement,b=a.parentNode;a.blur();b.focus()}function G(){var a=event.propertyName;if(a==="width"||a==="height"){var b=event.srcElement,c=b[a],d=parseInt(c,10);if(isNaN(d)||d<0)d=a==="width"?300:150;c===d?(b.style[a]=d+"px",b.getContext("2d").I(b.width,b.height)):b[a]=d}}function H(){i.detachEvent(I,H);for(var a in s){var b=s[a],c=b.firstChild,d;for(d in c)typeof c[d]==="function"&&(c[d]=l);for(d in b)typeof b[d]==="function"&&(b[d]=l);c.detachEvent(J,F);b.detachEvent(K,G)}i[L]=
l;i[M]=l;i[N]=l;i[C]=l;i[O]=l}function T(){var a=j.getElementsByTagName("script"),a=a[a.length-1];return j.documentMode>=8?a.src:a.getAttribute("src",4)}function t(a){return(""+a).replace(/&/g,"&").replace(/</g,"<")}function U(a){return a.toLowerCase()}function h(a){throw new D(a);}function P(a){var b=parseInt(a.width,10),c=parseInt(a.height,10);if(isNaN(b)||b<0)b=300;if(isNaN(c)||c<0)c=150;a.width=b;a.height=c}var l=null,r="canvas",L="CanvasRenderingContext2D",M="CanvasGradient",N="CanvasPattern",
C="FlashCanvas",O="G_vmlCanvasManager",J="onfocus",K="onpropertychange",E="onreadystatechange",I="onunload",w=((i[C+"Options"]||{}).swfPath||T().replace(/[^\/]+$/,""))+"flashcanvas.swf",e=new function(a){for(var b=0,c=a.length;b<c;b++)this[a[b]]=b}("toDataURL,save,restore,scale,rotate,translate,transform,setTransform,globalAlpha,globalCompositeOperation,strokeStyle,fillStyle,createLinearGradient,createRadialGradient,createPattern,lineWidth,lineCap,lineJoin,miterLimit,shadowOffsetX,shadowOffsetY,shadowBlur,shadowColor,clearRect,fillRect,strokeRect,beginPath,closePath,moveTo,lineTo,quadraticCurveTo,bezierCurveTo,arcTo,rect,arc,fill,stroke,clip,isPointInPath,font,textAlign,textBaseline,fillText,strokeText,measureText,drawImage,createImageData,getImageData,putImageData,addColorStop,direction,resize".split(",")),
u={},p={},o={},x={},s={},y={};m.prototype={save:function(){this.b();this.c();this.n();this.m();this.z();this.w();this.F.push([this.g,this.h,this.A,this.v,this.k,this.i,this.j,this.l,this.q,this.r,this.o,this.p,this.f,this.s,this.t]);this.a.push(e.save)},restore:function(){var a=this.F;if(a.length)a=a.pop(),this.globalAlpha=a[0],this.globalCompositeOperation=a[1],this.strokeStyle=a[2],this.fillStyle=a[3],this.lineWidth=a[4],this.lineCap=a[5],this.lineJoin=a[6],this.miterLimit=a[7],this.shadowOffsetX=
a[8],this.shadowOffsetY=a[9],this.shadowBlur=a[10],this.shadowColor=a[11],this.font=a[12],this.textAlign=a[13],this.textBaseline=a[14];this.a.push(e.restore)},scale:function(a,b){this.a.push(e.scale,a,b)},rotate:function(a){this.a.push(e.rotate,a)},translate:function(a,b){this.a.push(e.translate,a,b)},transform:function(a,b,c,d,f,g){this.a.push(e.transform,a,b,c,d,f,g)},setTransform:function(a,b,c,d,f,g){this.a.push(e.setTransform,a,b,c,d,f,g)},b:function(){var a=this.a;if(this.g!==this.globalAlpha)this.g=
this.globalAlpha,a.push(e.globalAlpha,this.g);if(this.h!==this.globalCompositeOperation)this.h=this.globalCompositeOperation,a.push(e.globalCompositeOperation,this.h)},n:function(){if(this.A!==this.strokeStyle){var a=this.A=this.strokeStyle;if(typeof a!=="string")if(a instanceof k||a instanceof v)a=a.id;else return;this.a.push(e.strokeStyle,a)}},m:function(){if(this.v!==this.fillStyle){var a=this.v=this.fillStyle;if(typeof a!=="string")if(a instanceof k||a instanceof v)a=a.id;else return;this.a.push(e.fillStyle,
a)}},createLinearGradient:function(a,b,c,d){(!isFinite(a)||!isFinite(b)||!isFinite(c)||!isFinite(d))&&h(9);this.a.push(e.createLinearGradient,a,b,c,d);return new k(this)},createRadialGradient:function(a,b,c,d,f,g){(!isFinite(a)||!isFinite(b)||!isFinite(c)||!isFinite(d)||!isFinite(f)||!isFinite(g))&&h(9);(c<0||g<0)&&h(1);this.a.push(e.createRadialGradient,a,b,c,d,f,g);return new k(this)},createPattern:function(a,b){a||h(17);var c=a.tagName,d,f=this.d;if(c)if(c=c.toLowerCase(),c==="img")d=a.getAttribute("src",
2);else if(c===r||c==="video")return;else h(17);else a.src?d=a.src:h(17);b==="repeat"||b==="no-repeat"||b==="repeat-x"||b==="repeat-y"||b===""||b===l||h(12);this.a.push(e.createPattern,t(d),b);!p[f][d]&&u[f]&&(this.e(),++o[f],p[f][d]=!0);return new v(this)},z:function(){var a=this.a;if(this.k!==this.lineWidth)this.k=this.lineWidth,a.push(e.lineWidth,this.k);if(this.i!==this.lineCap)this.i=this.lineCap,a.push(e.lineCap,this.i);if(this.j!==this.lineJoin)this.j=this.lineJoin,a.push(e.lineJoin,this.j);
if(this.l!==this.miterLimit)this.l=this.miterLimit,a.push(e.miterLimit,this.l)},c:function(){var a=this.a;if(this.q!==this.shadowOffsetX)this.q=this.shadowOffsetX,a.push(e.shadowOffsetX,this.q);if(this.r!==this.shadowOffsetY)this.r=this.shadowOffsetY,a.push(e.shadowOffsetY,this.r);if(this.o!==this.shadowBlur)this.o=this.shadowBlur,a.push(e.shadowBlur,this.o);if(this.p!==this.shadowColor)this.p=this.shadowColor,a.push(e.shadowColor,this.p)},clearRect:function(a,b,c,d){this.a.push(e.clearRect,a,b,c,
d)},fillRect:function(a,b,c,d){this.b();this.c();this.m();this.a.push(e.fillRect,a,b,c,d)},strokeRect:function(a,b,c,d){this.b();this.c();this.n();this.z();this.a.push(e.strokeRect,a,b,c,d)},beginPath:function(){this.a.push(e.beginPath)},closePath:function(){this.a.push(e.closePath)},moveTo:function(a,b){this.a.push(e.moveTo,a,b)},lineTo:function(a,b){this.a.push(e.lineTo,a,b)},quadraticCurveTo:function(a,b,c,d){this.a.push(e.quadraticCurveTo,a,b,c,d)},bezierCurveTo:function(a,b,c,d,f,g){this.a.push(e.bezierCurveTo,
a,b,c,d,f,g)},arcTo:function(a,b,c,d,f){f<0&&isFinite(f)&&h(1);this.a.push(e.arcTo,a,b,c,d,f)},rect:function(a,b,c,d){this.a.push(e.rect,a,b,c,d)},arc:function(a,b,c,d,f,g){c<0&&isFinite(c)&&h(1);this.a.push(e.arc,a,b,c,d,f,g?1:0)},fill:function(){this.b();this.c();this.m();this.a.push(e.fill)},stroke:function(){this.b();this.c();this.n();this.z();this.a.push(e.stroke)},clip:function(){this.a.push(e.clip)},w:function(){var a=this.a;if(this.f!==this.font)try{var b=y[this.d];b.style.font=this.f=this.font;
var c=b.currentStyle;a.push(e.font,[c.fontStyle,c.fontWeight,b.offsetHeight,c.fontFamily].join(" "))}catch(d){}if(this.s!==this.textAlign)this.s=this.textAlign,a.push(e.textAlign,this.s);if(this.t!==this.textBaseline)this.t=this.textBaseline,a.push(e.textBaseline,this.t);if(this.u!==this.canvas.currentStyle.direction)this.u=this.canvas.currentStyle.direction,a.push(e.direction,this.u)},fillText:function(a,b,c,d){this.b();this.m();this.c();this.w();this.a.push(e.fillText,t(a),b,c,d===z?Infinity:d)},
strokeText:function(a,b,c,d){this.b();this.n();this.c();this.w();this.a.push(e.strokeText,t(a),b,c,d===z?Infinity:d)},measureText:function(a){var b=y[this.d];try{b.style.font=this.font}catch(c){}b.innerText=(""+a).replace(/[ \n\f\r]/g,"\t");return new S(b.offsetWidth)},drawImage:function(a,b,c,d,f,g,i,j,l){a||h(17);var k=a.tagName,n,q=arguments.length,m=this.d;if(k)if(k=k.toLowerCase(),k==="img")n=a.getAttribute("src",2);else if(k===r||k==="video")return;else h(17);else a.src?n=a.src:h(17);this.b();
this.c();n=t(n);if(q===3)this.a.push(e.drawImage,q,n,b,c);else if(q===5)this.a.push(e.drawImage,q,n,b,c,d,f);else if(q===9)(d===0||f===0)&&h(1),this.a.push(e.drawImage,q,n,b,c,d,f,g,i,j,l);else return;!p[m][n]&&u[m]&&(this.e(),++o[m],p[m][n]=!0)},loadImage:function(a,b,c){var d=a.tagName,f,g=this.d;if(d)d.toLowerCase()==="img"&&(f=a.getAttribute("src",2));else if(a.src)f=a.src;if(f&&!p[g][f]){if(b||c)x[g][f]=[a,b,c];this.a.push(e.drawImage,1,t(f));u[g]&&(this.e(),++o[g],p[g][f]=!0)}},D:function(){this.globalAlpha=
this.g=1;this.globalCompositeOperation=this.h="source-over";this.fillStyle=this.v=this.strokeStyle=this.A="#000000";this.lineWidth=this.k=1;this.lineCap=this.i="butt";this.lineJoin=this.j="miter";this.miterLimit=this.l=10;this.shadowBlur=this.o=this.shadowOffsetY=this.r=this.shadowOffsetX=this.q=0;this.shadowColor=this.p="rgba(0, 0, 0, 0.0)";this.font=this.f="10px sans-serif";this.textAlign=this.s="start";this.textBaseline=this.t="alphabetic";this.a=[];this.F=[]},H:function(){var a=this.a;this.a=
[];return a},e:function(){var a=this.H();if(a.length>0)return eval(this.B.CallFunction('<invoke name="executeCommand" returntype="javascript"><arguments><string>'+a.join("�")+"</string></arguments></invoke>"))},I:function(a,b){this.e();this.D();if(a>0)this.B.width=a;if(b>0)this.B.height=b;this.a.push(e.resize,a,b)}};k.prototype={addColorStop:function(a,b){(isNaN(a)||a<0||a>1)&&h(1);this.G.a.push(e.addColorStop,this.id,a,b)}};D.prototype=Error();var R={1:"INDEX_SIZE_ERR",9:"NOT_SUPPORTED_ERR",11:"INVALID_STATE_ERR",
12:"SYNTAX_ERR",17:"TYPE_MISMATCH_ERR",18:"SECURITY_ERR"},B={initElement:function(a){if(a.getContext)return a;var b=Math.random().toString(36).slice(2)||"0",c="external"+b;u[b]=!1;p[b]={};o[b]=1;x[b]={};P(a);a.innerHTML='<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="'+location.protocol+'//fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="100%" height="100%" id="'+c+'"><param name="allowScriptAccess" value="always"><param name="flashvars" value="id='+
c+'"><param name="wmode" value="transparent"></object><span style="margin:0;padding:0;border:0;display:inline-block;position:static;height:1em;overflow:visible;white-space:nowrap"></span>';s[b]=a;var d=a.firstChild;y[b]=a.lastChild;var f=j.body.contains;if(f(a))d.movie=w;else var g=setInterval(function(){if(f(a))clearInterval(g),d.movie=w},0);if(j.compatMode==="BackCompat"||!i.XMLHttpRequest)y[b].style.overflow="hidden";var h=new m(a,d);a.getContext=function(a){return a==="2d"?h:l};a.toDataURL=function(a,
b){(""+a).replace(/[A-Z]+/g,U)==="image/jpeg"?h.a.push(e.toDataURL,a,typeof b==="number"?b:""):h.a.push(e.toDataURL,a);return h.e()};d.attachEvent(J,F);return a},saveImage:function(a,b){a.firstChild.saveImage(b)},setOptions:function(){},trigger:function(a,b){s[a].fireEvent("on"+b)},unlock:function(a,b,c){var d,e,g;o[a]&&--o[a];if(b===z){d=s[a];b=d.firstChild;P(d);e=d.width;c=d.height;d.style.width=e+"px";d.style.height=c+"px";if(e>0)b.width=e;if(c>0)b.height=c;b.resize(e,c);d.attachEvent(K,G);u[a]=
!0;typeof d.onload==="function"&&setTimeout(function(){d.onload()},0)}else if(g=x[a][b])e=g[0],c=g[1+c],delete x[a][b],typeof c==="function"&&c.call(e)}};j.createElement(r);j.createStyleSheet().cssText=r+"{display:inline-block;overflow:hidden;width:300px;height:150px}";j.readyState==="complete"?A():j.attachEvent(E,A);i.attachEvent(I,H);if(w.indexOf(location.protocol+"//"+location.host+"/")===0){var Q=new ActiveXObject("Microsoft.XMLHTTP");Q.open("GET",w,!1);Q.send(l)}i[L]=m;i[M]=k;i[N]=v;i[C]=B;i[O]=
{init:function(){},init_:function(){},initElement:B.initElement};keep=[m.measureText,m.loadImage]}(window,document);
(function(document){
webshims.addReady(function(context, elem){
if(context == document){
if(window.G_vmlCanvasManager && G_vmlCanvasManager.init_ ){
G_vmlCanvasManager.init_(document);
}
}
webshims.$('canvas', context).add(elem.filter('canvas')).each(function(){
var hasContext = this.getContext;
if(!hasContext && window.G_vmlCanvasManager){
G_vmlCanvasManager.initElement(this);
}
});
});
webshims.isReady('canvas', true);
})(document);
| zimbatm/cdnjs | ajax/libs/webshim/1.14.4-RC3/dev/shims/FlashCanvas/flashcanvas.js | JavaScript | mit | 11,910 |
webshims.validityMessages.cs = {
"typeMismatch": {
"defaultMessage": "Prosím vložte platnou hodnotu.",
"email": "Prosím vložte emailovou adresu.",
"url": "Prosím vložte URL."
},
"badInput": {
"defaultMessage": "Prosím vložte platnou hodnotu.",
"number": "Prosím vložte číslo.",
"date": "Prosím vložte datum.",
"time": "Prosím vložte čas.",
"range": "Neplatná vstupní hodnota.",
"month": "Prosím vložte platnou hodnotu.",
"datetime-local": "Prosím vložte datum a čas."
},
"rangeUnderflow": {
"defaultMessage": "Hodnota musí být větší nebo rovna {%min}.",
"date": "Datum musí být od {%min}.",
"time": "Čas musí být od {%min}.",
"datetime-local": "Datum a čas musí být od {%min}.",
"month": "Měsíc musí být od {%min}.",
},
"rangeOverflow": {
"defaultMessage": "Hodnota musí být větší nebo rovna {%mas}.",
"date": "Datum musí být od {%mas}.",
"time": "Čas musí být od {%mas}.",
"datetime-local": "Datum a čas musí být od {%mas}.",
"month": "Měsíc musí být od {%mas}.",
},
"stepMismatch": "Neplatná vstupní hodnota.",
"tooLong": "Maximálně můžete vložit {%maxlength} znaků. Zadali jste {%valueLen}.",
"patternMismatch": "Neplatná vstupní hodnota. {%title}",
"valueMissing": {
"defaultMessage": "Prosím vyplňte toto pole",
"checkbox": "Prosím zaškrtněte toto políčko, pokud chcete pokračovat.",
"select": "Prosím zvolte možnost.",
"radio": "Prosím zvolte možnost."
}
};
webshims.formcfg.cs = {
"numberFormat": {
".": ",",
",": " "
},
"numberSigns": ".-",
"dateSigns": ".",
"timeSigns": ":. ",
"dFormat": ".",
"patterns": {
"d": "dd.mm.yy"
},
"month": {
"currentText": "Tento měsíc"
},
"week": {
"currentText": "Tento týden"
},
"time": {
"currentText": "Nyní"
},
"date": {
"closeText": "Hotovo",
"clear": "Smazat",
"prevText": "Předchozí",
"nextText": "Další",
"currentText": "Dnešek",
"monthNames": [
"Leden",
"Únor",
"Březen",
"Duben",
"Květen",
"Červen",
"Červenec",
"Srpen",
"Září",
"Říjen",
"Listopad",
"Prosinec"
],
"monthNamesShort": [
"Led",//??
"Ún",
"Bře",
"Dub",
"Kvě",
"Čer",
"Čec",
"Srp",
"Zář",
"Říj",
"Lis",
"Pro"
],
"dayNames": [
"Neděle",
"Pondělí",
"Úterý",
"Středa",
"Čtvrtek",
"Pátek",
"Sobota"
],
"dayNamesShort": ["NE", "PO", "ÚT", "ST", "ČT", "PÁ", "SO"],
"dayNamesMin": ["NE", "PO", "ÚT", "ST", "ČT", "PÁ", "SO"],
"weekHeader": "Týden",
"firstDay": 1,
"isRTL": false,
"showMonthAfterYear": false,
"yearSuffix": ""
}
};
| abbychau/cdnjs | ajax/libs/webshim/1.12.4/dev/shims/i18n/formcfg-cs.js | JavaScript | mit | 2,677 |
// Copyright 2006 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Known Issues:
//
// * Patterns are not implemented.
// * Radial gradient are not implemented. The VML version of these look very
// different from the canvas one.
// * Clipping paths are not implemented.
// * Coordsize. The width and height attribute have higher priority than the
// width and height style values which isn't correct.
// * Painting mode isn't implemented.
// * Canvas width/height should is using content-box by default. IE in
// Quirks mode will draw the canvas using border-box. Either change your
// doctype to HTML5
// (http://www.whatwg.org/specs/web-apps/current-work/#the-doctype)
// or use Box Sizing Behavior from WebFX
// (http://webfx.eae.net/dhtml/boxsizing/boxsizing.html)
// * Non uniform scaling does not correctly scale strokes.
// * Optimize. There is always room for speed improvements.
// Only add this code if we do not already have a canvas implementation
if (!document.createElement('canvas').getContext) {
(function() {
// alias some functions to make (compiled) code shorter
var m = Math;
var mr = m.round;
var ms = m.sin;
var mc = m.cos;
var abs = m.abs;
var sqrt = m.sqrt;
// this is used for sub pixel precision
var Z = 10;
var Z2 = Z / 2;
/**
* This funtion is assigned to the <canvas> elements as element.getContext().
* @this {HTMLElement}
* @return {CanvasRenderingContext2D_}
*/
function getContext() {
return this.context_ ||
(this.context_ = new CanvasRenderingContext2D_(this));
}
var slice = Array.prototype.slice;
/**
* Binds a function to an object. The returned function will always use the
* passed in {@code obj} as {@code this}.
*
* Example:
*
* g = bind(f, obj, a, b)
* g(c, d) // will do f.call(obj, a, b, c, d)
*
* @param {Function} f The function to bind the object to
* @param {Object} obj The object that should act as this when the function
* is called
* @param {*} var_args Rest arguments that will be used as the initial
* arguments when the function is called
* @return {Function} A new function that has bound this
*/
function bind(f, obj, var_args) {
var a = slice.call(arguments, 2);
return function() {
return f.apply(obj, a.concat(slice.call(arguments)));
};
}
var G_vmlCanvasManager_ = {
init: function(opt_doc) {
if (/MSIE/.test(navigator.userAgent) && !window.opera) {
var doc = opt_doc || document;
// Create a dummy element so that IE will allow canvas elements to be
// recognized.
doc.createElement('canvas');
doc.attachEvent('onreadystatechange', bind(this.init_, this, doc));
}
},
init_: function(doc) {
// create xmlns
if (!doc.namespaces['g_vml_']) {
doc.namespaces.add('g_vml_', 'urn:schemas-microsoft-com:vml',
'#default#VML');
}
if (!doc.namespaces['g_o_']) {
doc.namespaces.add('g_o_', 'urn:schemas-microsoft-com:office:office',
'#default#VML');
}
// Setup default CSS. Only add one style sheet per document
if (!doc.styleSheets['ex_canvas_']) {
var ss = doc.createStyleSheet();
ss.owningElement.id = 'ex_canvas_';
ss.cssText = 'canvas{display:inline-block;overflow:hidden;' +
// default size is 300x150 in Gecko and Opera
'text-align:left;width:300px;height:150px}' +
'g_vml_\\:*{behavior:url(#default#VML)}' +
'g_o_\\:*{behavior:url(#default#VML)}';
}
// find all canvas elements
var els = doc.getElementsByTagName('canvas');
for (var i = 0; i < els.length; i++) {
this.initElement(els[i]);
}
},
/**
* Public initializes a canvas element so that it can be used as canvas
* element from now on. This is called automatically before the page is
* loaded but if you are creating elements using createElement you need to
* make sure this is called on the element.
* @param {HTMLElement} el The canvas element to initialize.
* @return {HTMLElement} the element that was created.
*/
initElement: function(el) {
if (!el.getContext) {
el.getContext = getContext;
// Remove fallback content. There is no way to hide text nodes so we
// just remove all childNodes. We could hide all elements and remove
// text nodes but who really cares about the fallback content.
el.innerHTML = '';
// do not use inline function because that will leak memory
el.attachEvent('onpropertychange', onPropertyChange);
el.attachEvent('onresize', onResize);
var attrs = el.attributes;
if (attrs.width && attrs.width.specified) {
// TODO: use runtimeStyle and coordsize
// el.getContext().setWidth_(attrs.width.nodeValue);
el.style.width = attrs.width.nodeValue + 'px';
} else {
el.width = el.clientWidth;
}
if (attrs.height && attrs.height.specified) {
// TODO: use runtimeStyle and coordsize
// el.getContext().setHeight_(attrs.height.nodeValue);
el.style.height = attrs.height.nodeValue + 'px';
} else {
el.height = el.clientHeight;
}
//el.getContext().setCoordsize_()
}
return el;
}
};
function onPropertyChange(e) {
var el = e.srcElement;
switch (e.propertyName) {
case 'width':
el.style.width = el.attributes.width.nodeValue + 'px';
el.getContext().clearRect();
break;
case 'height':
el.style.height = el.attributes.height.nodeValue + 'px';
el.getContext().clearRect();
break;
}
}
function onResize(e) {
var el = e.srcElement;
if (el.firstChild) {
el.firstChild.style.width = el.clientWidth + 'px';
el.firstChild.style.height = el.clientHeight + 'px';
}
}
G_vmlCanvasManager_.init();
// precompute "00" to "FF"
var dec2hex = [];
for (var i = 0; i < 16; i++) {
for (var j = 0; j < 16; j++) {
dec2hex[i * 16 + j] = i.toString(16) + j.toString(16);
}
}
function createMatrixIdentity() {
return [
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]
];
}
function matrixMultiply(m1, m2) {
var result = createMatrixIdentity();
for (var x = 0; x < 3; x++) {
for (var y = 0; y < 3; y++) {
var sum = 0;
for (var z = 0; z < 3; z++) {
sum += m1[x][z] * m2[z][y];
}
result[x][y] = sum;
}
}
return result;
}
function copyState(o1, o2) {
o2.fillStyle = o1.fillStyle;
o2.lineCap = o1.lineCap;
o2.lineJoin = o1.lineJoin;
o2.lineWidth = o1.lineWidth;
o2.miterLimit = o1.miterLimit;
o2.shadowBlur = o1.shadowBlur;
o2.shadowColor = o1.shadowColor;
o2.shadowOffsetX = o1.shadowOffsetX;
o2.shadowOffsetY = o1.shadowOffsetY;
o2.strokeStyle = o1.strokeStyle;
o2.globalAlpha = o1.globalAlpha;
o2.arcScaleX_ = o1.arcScaleX_;
o2.arcScaleY_ = o1.arcScaleY_;
o2.lineScale_ = o1.lineScale_;
}
function processStyle(styleString) {
var str, alpha = 1;
styleString = String(styleString);
if (styleString.substring(0, 3) == 'rgb') {
var start = styleString.indexOf('(', 3);
var end = styleString.indexOf(')', start + 1);
var guts = styleString.substring(start + 1, end).split(',');
str = '#';
for (var i = 0; i < 3; i++) {
str += dec2hex[Number(guts[i])];
}
if (guts.length == 4 && styleString.substr(3, 1) == 'a') {
alpha = guts[3];
}
} else {
str = styleString;
}
return {color: str, alpha: alpha};
}
function processLineCap(lineCap) {
switch (lineCap) {
case 'butt':
return 'flat';
case 'round':
return 'round';
case 'square':
default:
return 'square';
}
}
/**
* This class implements CanvasRenderingContext2D interface as described by
* the WHATWG.
* @param {HTMLElement} surfaceElement The element that the 2D context should
* be associated with
*/
function CanvasRenderingContext2D_(surfaceElement) {
this.m_ = createMatrixIdentity();
this.mStack_ = [];
this.aStack_ = [];
this.currentPath_ = [];
// Canvas context properties
this.strokeStyle = '#000';
this.fillStyle = '#000';
this.lineWidth = 1;
this.lineJoin = 'miter';
this.lineCap = 'butt';
this.miterLimit = Z * 1;
this.globalAlpha = 1;
this.canvas = surfaceElement;
var el = surfaceElement.ownerDocument.createElement('div');
el.style.width = surfaceElement.clientWidth + 'px';
el.style.height = surfaceElement.clientHeight + 'px';
el.style.overflow = 'hidden';
el.style.position = 'absolute';
surfaceElement.appendChild(el);
this.element_ = el;
this.arcScaleX_ = 1;
this.arcScaleY_ = 1;
this.lineScale_ = 1;
}
var contextPrototype = CanvasRenderingContext2D_.prototype;
contextPrototype.clearRect = function() {
this.element_.innerHTML = '';
};
contextPrototype.beginPath = function() {
// TODO: Branch current matrix so that save/restore has no effect
// as per safari docs.
this.currentPath_ = [];
};
contextPrototype.moveTo = function(aX, aY) {
var p = this.getCoords_(aX, aY);
this.currentPath_.push({type: 'moveTo', x: p.x, y: p.y});
this.currentX_ = p.x;
this.currentY_ = p.y;
};
contextPrototype.lineTo = function(aX, aY) {
var p = this.getCoords_(aX, aY);
this.currentPath_.push({type: 'lineTo', x: p.x, y: p.y});
this.currentX_ = p.x;
this.currentY_ = p.y;
};
contextPrototype.bezierCurveTo = function(aCP1x, aCP1y,
aCP2x, aCP2y,
aX, aY) {
var p = this.getCoords_(aX, aY);
var cp1 = this.getCoords_(aCP1x, aCP1y);
var cp2 = this.getCoords_(aCP2x, aCP2y);
bezierCurveTo(this, cp1, cp2, p);
};
// Helper function that takes the already fixed cordinates.
function bezierCurveTo(self, cp1, cp2, p) {
self.currentPath_.push({
type: 'bezierCurveTo',
cp1x: cp1.x,
cp1y: cp1.y,
cp2x: cp2.x,
cp2y: cp2.y,
x: p.x,
y: p.y
});
self.currentX_ = p.x;
self.currentY_ = p.y;
}
contextPrototype.quadraticCurveTo = function(aCPx, aCPy, aX, aY) {
// the following is lifted almost directly from
// http://developer.mozilla.org/en/docs/Canvas_tutorial:Drawing_shapes
var cp = this.getCoords_(aCPx, aCPy);
var p = this.getCoords_(aX, aY);
var cp1 = {
x: this.currentX_ + 2.0 / 3.0 * (cp.x - this.currentX_),
y: this.currentY_ + 2.0 / 3.0 * (cp.y - this.currentY_)
};
var cp2 = {
x: cp1.x + (p.x - this.currentX_) / 3.0,
y: cp1.y + (p.y - this.currentY_) / 3.0
};
bezierCurveTo(this, cp1, cp2, p);
};
contextPrototype.arc = function(aX, aY, aRadius,
aStartAngle, aEndAngle, aClockwise) {
aRadius *= Z;
var arcType = aClockwise ? 'at' : 'wa';
var xStart = aX + mc(aStartAngle) * aRadius - Z2;
var yStart = aY + ms(aStartAngle) * aRadius - Z2;
var xEnd = aX + mc(aEndAngle) * aRadius - Z2;
var yEnd = aY + ms(aEndAngle) * aRadius - Z2;
// IE won't render arches drawn counter clockwise if xStart == xEnd.
if (xStart == xEnd && !aClockwise) {
xStart += 0.125; // Offset xStart by 1/80 of a pixel. Use something
// that can be represented in binary
}
var p = this.getCoords_(aX, aY);
var pStart = this.getCoords_(xStart, yStart);
var pEnd = this.getCoords_(xEnd, yEnd);
this.currentPath_.push({type: arcType,
x: p.x,
y: p.y,
radius: aRadius,
xStart: pStart.x,
yStart: pStart.y,
xEnd: pEnd.x,
yEnd: pEnd.y});
};
contextPrototype.rect = function(aX, aY, aWidth, aHeight) {
this.moveTo(aX, aY);
this.lineTo(aX + aWidth, aY);
this.lineTo(aX + aWidth, aY + aHeight);
this.lineTo(aX, aY + aHeight);
this.closePath();
};
contextPrototype.strokeRect = function(aX, aY, aWidth, aHeight) {
var oldPath = this.currentPath_;
this.beginPath();
this.moveTo(aX, aY);
this.lineTo(aX + aWidth, aY);
this.lineTo(aX + aWidth, aY + aHeight);
this.lineTo(aX, aY + aHeight);
this.closePath();
this.stroke();
this.currentPath_ = oldPath;
};
contextPrototype.fillRect = function(aX, aY, aWidth, aHeight) {
var oldPath = this.currentPath_;
this.beginPath();
this.moveTo(aX, aY);
this.lineTo(aX + aWidth, aY);
this.lineTo(aX + aWidth, aY + aHeight);
this.lineTo(aX, aY + aHeight);
this.closePath();
this.fill();
this.currentPath_ = oldPath;
};
contextPrototype.createLinearGradient = function(aX0, aY0, aX1, aY1) {
var gradient = new CanvasGradient_('gradient');
gradient.x0_ = aX0;
gradient.y0_ = aY0;
gradient.x1_ = aX1;
gradient.y1_ = aY1;
return gradient;
};
contextPrototype.createRadialGradient = function(aX0, aY0, aR0,
aX1, aY1, aR1) {
var gradient = new CanvasGradient_('gradientradial');
gradient.x0_ = aX0;
gradient.y0_ = aY0;
gradient.r0_ = aR0;
gradient.x1_ = aX1;
gradient.y1_ = aY1;
gradient.r1_ = aR1;
return gradient;
};
contextPrototype.drawImage = function(image, var_args) {
var dx, dy, dw, dh, sx, sy, sw, sh;
// to find the original width we overide the width and height
var oldRuntimeWidth = image.runtimeStyle.width;
var oldRuntimeHeight = image.runtimeStyle.height;
image.runtimeStyle.width = 'auto';
image.runtimeStyle.height = 'auto';
// get the original size
var w = image.width;
var h = image.height;
// and remove overides
image.runtimeStyle.width = oldRuntimeWidth;
image.runtimeStyle.height = oldRuntimeHeight;
if (arguments.length == 3) {
dx = arguments[1];
dy = arguments[2];
sx = sy = 0;
sw = dw = w;
sh = dh = h;
} else if (arguments.length == 5) {
dx = arguments[1];
dy = arguments[2];
dw = arguments[3];
dh = arguments[4];
sx = sy = 0;
sw = w;
sh = h;
} else if (arguments.length == 9) {
sx = arguments[1];
sy = arguments[2];
sw = arguments[3];
sh = arguments[4];
dx = arguments[5];
dy = arguments[6];
dw = arguments[7];
dh = arguments[8];
} else {
throw Error('Invalid number of arguments');
}
var d = this.getCoords_(dx, dy);
var w2 = sw / 2;
var h2 = sh / 2;
var vmlStr = [];
var W = 10;
var H = 10;
// For some reason that I've now forgotten, using divs didn't work
vmlStr.push(' <g_vml_:group',
' coordsize="', Z * W, ',', Z * H, '"',
' coordorigin="0,0"' ,
' style="width:', W, 'px;height:', H, 'px;position:absolute;');
// If filters are necessary (rotation exists), create them
// filters are bog-slow, so only create them if abbsolutely necessary
// The following check doesn't account for skews (which don't exist
// in the canvas spec (yet) anyway.
if (this.m_[0][0] != 1 || this.m_[0][1]) {
var filter = [];
// Note the 12/21 reversal
filter.push('M11=', this.m_[0][0], ',',
'M12=', this.m_[1][0], ',',
'M21=', this.m_[0][1], ',',
'M22=', this.m_[1][1], ',',
'Dx=', mr(d.x / Z), ',',
'Dy=', mr(d.y / Z), '');
// Bounding box calculation (need to minimize displayed area so that
// filters don't waste time on unused pixels.
var max = d;
var c2 = this.getCoords_(dx + dw, dy);
var c3 = this.getCoords_(dx, dy + dh);
var c4 = this.getCoords_(dx + dw, dy + dh);
max.x = m.max(max.x, c2.x, c3.x, c4.x);
max.y = m.max(max.y, c2.y, c3.y, c4.y);
vmlStr.push('padding:0 ', mr(max.x / Z), 'px ', mr(max.y / Z),
'px 0;filter:progid:DXImageTransform.Microsoft.Matrix(',
filter.join(''), ", sizingmethod='clip');")
} else {
vmlStr.push('top:', mr(d.y / Z), 'px;left:', mr(d.x / Z), 'px;');
}
vmlStr.push(' ">' ,
'<g_vml_:image src="', image.src, '"',
' style="width:', Z * dw, 'px;',
' height:', Z * dh, 'px;"',
' cropleft="', sx / w, '"',
' croptop="', sy / h, '"',
' cropright="', (w - sx - sw) / w, '"',
' cropbottom="', (h - sy - sh) / h, '"',
' />',
'</g_vml_:group>');
this.element_.insertAdjacentHTML('BeforeEnd',
vmlStr.join(''));
};
contextPrototype.stroke = function(aFill) {
var lineStr = [];
var lineOpen = false;
var a = processStyle(aFill ? this.fillStyle : this.strokeStyle);
var color = a.color;
var opacity = a.alpha * this.globalAlpha;
var W = 10;
var H = 10;
lineStr.push('<g_vml_:shape',
' filled="', !!aFill, '"',
' style="position:absolute;width:', W, 'px;height:', H, 'px;"',
' coordorigin="0 0" coordsize="', Z * W, ' ', Z * H, '"',
' stroked="', !aFill, '"',
' path="');
var newSeq = false;
var min = {x: null, y: null};
var max = {x: null, y: null};
for (var i = 0; i < this.currentPath_.length; i++) {
var p = this.currentPath_[i];
var c;
switch (p.type) {
case 'moveTo':
c = p;
lineStr.push(' m ', mr(p.x), ',', mr(p.y));
break;
case 'lineTo':
lineStr.push(' l ', mr(p.x), ',', mr(p.y));
break;
case 'close':
lineStr.push(' x ');
p = null;
break;
case 'bezierCurveTo':
lineStr.push(' c ',
mr(p.cp1x), ',', mr(p.cp1y), ',',
mr(p.cp2x), ',', mr(p.cp2y), ',',
mr(p.x), ',', mr(p.y));
break;
case 'at':
case 'wa':
lineStr.push(' ', p.type, ' ',
mr(p.x - this.arcScaleX_ * p.radius), ',',
mr(p.y - this.arcScaleY_ * p.radius), ' ',
mr(p.x + this.arcScaleX_ * p.radius), ',',
mr(p.y + this.arcScaleY_ * p.radius), ' ',
mr(p.xStart), ',', mr(p.yStart), ' ',
mr(p.xEnd), ',', mr(p.yEnd));
break;
}
// TODO: Following is broken for curves due to
// move to proper paths.
// Figure out dimensions so we can do gradient fills
// properly
if (p) {
if (min.x == null || p.x < min.x) {
min.x = p.x;
}
if (max.x == null || p.x > max.x) {
max.x = p.x;
}
if (min.y == null || p.y < min.y) {
min.y = p.y;
}
if (max.y == null || p.y > max.y) {
max.y = p.y;
}
}
}
lineStr.push(' ">');
if (!aFill) {
var lineWidth = this.lineScale_ * this.lineWidth;
// VML cannot correctly render a line if the width is less than 1px.
// In that case, we dilute the color to make the line look thinner.
if (lineWidth < 1) {
opacity *= lineWidth;
}
lineStr.push(
'<g_vml_:stroke',
' opacity="', opacity, '"',
' joinstyle="', this.lineJoin, '"',
' miterlimit="', this.miterLimit, '"',
' endcap="', processLineCap(this.lineCap), '"',
' weight="', lineWidth, 'px"',
' color="', color, '" />'
);
} else if (typeof this.fillStyle == 'object') {
var fillStyle = this.fillStyle;
var angle = 0;
var focus = {x: 0, y: 0};
// additional offset
var shift = 0;
// scale factor for offset
var expansion = 1;
if (fillStyle.type_ == 'gradient') {
var x0 = fillStyle.x0_ / this.arcScaleX_;
var y0 = fillStyle.y0_ / this.arcScaleY_;
var x1 = fillStyle.x1_ / this.arcScaleX_;
var y1 = fillStyle.y1_ / this.arcScaleY_;
var p0 = this.getCoords_(x0, y0);
var p1 = this.getCoords_(x1, y1);
var dx = p1.x - p0.x;
var dy = p1.y - p0.y;
angle = Math.atan2(dx, dy) * 180 / Math.PI;
// The angle should be a non-negative number.
if (angle < 0) {
angle += 360;
}
// Very small angles produce an unexpected result because they are
// converted to a scientific notation string.
if (angle < 1e-6) {
angle = 0;
}
} else {
var p0 = this.getCoords_(fillStyle.x0_, fillStyle.y0_);
var width = max.x - min.x;
var height = max.y - min.y;
focus = {
x: (p0.x - min.x) / width,
y: (p0.y - min.y) / height
};
width /= this.arcScaleX_ * Z;
height /= this.arcScaleY_ * Z;
var dimension = m.max(width, height);
shift = 2 * fillStyle.r0_ / dimension;
expansion = 2 * fillStyle.r1_ / dimension - shift;
}
// We need to sort the color stops in ascending order by offset,
// otherwise IE won't interpret it correctly.
var stops = fillStyle.colors_;
stops.sort(function(cs1, cs2) {
return cs1.offset - cs2.offset;
});
var length = stops.length;
var color1 = stops[0].color;
var color2 = stops[length - 1].color;
var opacity1 = stops[0].alpha * this.globalAlpha;
var opacity2 = stops[length - 1].alpha * this.globalAlpha;
var colors = [];
for (var i = 0; i < length; i++) {
var stop = stops[i];
colors.push(stop.offset * expansion + shift + ' ' + stop.color);
}
// When colors attribute is used, the meanings of opacity and o:opacity2
// are reversed.
lineStr.push('<g_vml_:fill type="', fillStyle.type_, '"',
' method="none" focus="100%"',
' color="', color1, '"',
' color2="', color2, '"',
' colors="', colors.join(','), '"',
' opacity="', opacity2, '"',
' g_o_:opacity2="', opacity1, '"',
' angle="', angle, '"',
' focusposition="', focus.x, ',', focus.y, '" />');
} else {
lineStr.push('<g_vml_:fill color="', color, '" opacity="', opacity,
'" />');
}
lineStr.push('</g_vml_:shape>');
this.element_.insertAdjacentHTML('beforeEnd', lineStr.join(''));
};
contextPrototype.fill = function() {
this.stroke(true);
}
contextPrototype.closePath = function() {
this.currentPath_.push({type: 'close'});
};
/**
* @private
*/
contextPrototype.getCoords_ = function(aX, aY) {
var m = this.m_;
return {
x: Z * (aX * m[0][0] + aY * m[1][0] + m[2][0]) - Z2,
y: Z * (aX * m[0][1] + aY * m[1][1] + m[2][1]) - Z2
}
};
contextPrototype.save = function() {
var o = {};
copyState(this, o);
this.aStack_.push(o);
this.mStack_.push(this.m_);
this.m_ = matrixMultiply(createMatrixIdentity(), this.m_);
};
contextPrototype.restore = function() {
copyState(this.aStack_.pop(), this);
this.m_ = this.mStack_.pop();
};
function matrixIsFinite(m) {
for (var j = 0; j < 3; j++) {
for (var k = 0; k < 2; k++) {
if (!isFinite(m[j][k]) || isNaN(m[j][k])) {
return false;
}
}
}
return true;
}
function setM(ctx, m, updateLineScale) {
if (!matrixIsFinite(m)) {
return;
}
ctx.m_ = m;
if (updateLineScale) {
// Get the line scale.
// Determinant of this.m_ means how much the area is enlarged by the
// transformation. So its square root can be used as a scale factor
// for width.
var det = m[0][0] * m[1][1] - m[0][1] * m[1][0];
ctx.lineScale_ = sqrt(abs(det));
}
}
contextPrototype.translate = function(aX, aY) {
var m1 = [
[1, 0, 0],
[0, 1, 0],
[aX, aY, 1]
];
setM(this, matrixMultiply(m1, this.m_), false);
};
contextPrototype.rotate = function(aRot) {
var c = mc(aRot);
var s = ms(aRot);
var m1 = [
[c, s, 0],
[-s, c, 0],
[0, 0, 1]
];
setM(this, matrixMultiply(m1, this.m_), false);
};
contextPrototype.scale = function(aX, aY) {
this.arcScaleX_ *= aX;
this.arcScaleY_ *= aY;
var m1 = [
[aX, 0, 0],
[0, aY, 0],
[0, 0, 1]
];
setM(this, matrixMultiply(m1, this.m_), true);
};
contextPrototype.transform = function(m11, m12, m21, m22, dx, dy) {
var m1 = [
[m11, m12, 0],
[m21, m22, 0],
[dx, dy, 1]
];
setM(this, matrixMultiply(m1, this.m_), true);
};
contextPrototype.setTransform = function(m11, m12, m21, m22, dx, dy) {
var m = [
[m11, m12, 0],
[m21, m22, 0],
[dx, dy, 1]
];
setM(this, m, true);
};
/******** STUBS ********/
contextPrototype.clip = function() {
// TODO: Implement
};
contextPrototype.arcTo = function() {
// TODO: Implement
};
contextPrototype.createPattern = function() {
return new CanvasPattern_;
};
// Gradient / Pattern Stubs
function CanvasGradient_(aType) {
this.type_ = aType;
this.x0_ = 0;
this.y0_ = 0;
this.r0_ = 0;
this.x1_ = 0;
this.y1_ = 0;
this.r1_ = 0;
this.colors_ = [];
}
CanvasGradient_.prototype.addColorStop = function(aOffset, aColor) {
aColor = processStyle(aColor);
this.colors_.push({offset: aOffset,
color: aColor.color,
alpha: aColor.alpha});
};
function CanvasPattern_() {}
// set up externs
G_vmlCanvasManager = G_vmlCanvasManager_;
CanvasRenderingContext2D = CanvasRenderingContext2D_;
CanvasGradient = CanvasGradient_;
CanvasPattern = CanvasPattern_;
})();
(function(document){
webshims.addReady(function(context, elem){
if(context == document){
if(window.G_vmlCanvasManager && G_vmlCanvasManager.init_ ){
G_vmlCanvasManager.init_(document);
}
}
webshims.$('canvas', context).add(elem.filter('canvas')).each(function(){
var hasContext = this.getContext;
if(!hasContext && window.G_vmlCanvasManager){
G_vmlCanvasManager.initElement(this);
}
});
});
webshims.isReady('canvas', true);
})(document);
} // if
| kiwi89/cdnjs | ajax/libs/webshim/1.14.2/dev/shims/excanvas.js | JavaScript | mit | 27,503 |
/**
* Require the given path.
*
* @param {String} path
* @return {Object} exports
* @api public
*/
function require(path, parent, orig) {
var resolved = require.resolve(path);
// lookup failed
if (null == resolved) {
orig = orig || path;
parent = parent || 'root';
var err = new Error('Failed to require "' + orig + '" from "' + parent + '"');
err.path = orig;
err.parent = parent;
err.require = true;
throw err;
}
var module = require.modules[resolved];
// perform real require()
// by invoking the module's
// registered function
if (!module.exports) {
module.exports = {};
module.client = module.component = true;
module.call(this, module.exports, require.relative(resolved), module);
}
return module.exports;
}
/**
* Registered modules.
*/
require.modules = {};
/**
* Registered aliases.
*/
require.aliases = {};
/**
* Resolve `path`.
*
* Lookup:
*
* - PATH/index.js
* - PATH.js
* - PATH
*
* @param {String} path
* @return {String} path or null
* @api private
*/
require.resolve = function(path) {
if (path.charAt(0) === '/') path = path.slice(1);
var index = path + '/index.js';
var paths = [
path,
path + '.js',
path + '.json',
path + '/index.js',
path + '/index.json'
];
for (var i = 0; i < paths.length; i++) {
var path = paths[i];
if (require.modules.hasOwnProperty(path)) return path;
}
if (require.aliases.hasOwnProperty(index)) {
return require.aliases[index];
}
};
/**
* Normalize `path` relative to the current path.
*
* @param {String} curr
* @param {String} path
* @return {String}
* @api private
*/
require.normalize = function(curr, path) {
var segs = [];
if ('.' != path.charAt(0)) return path;
curr = curr.split('/');
path = path.split('/');
for (var i = 0; i < path.length; ++i) {
if ('..' == path[i]) {
curr.pop();
} else if ('.' != path[i] && '' != path[i]) {
segs.push(path[i]);
}
}
return curr.concat(segs).join('/');
};
/**
* Register module at `path` with callback `definition`.
*
* @param {String} path
* @param {Function} definition
* @api private
*/
require.register = function(path, definition) {
require.modules[path] = definition;
};
/**
* Alias a module definition.
*
* @param {String} from
* @param {String} to
* @api private
*/
require.alias = function(from, to) {
if (!require.modules.hasOwnProperty(from)) {
throw new Error('Failed to alias "' + from + '", it does not exist');
}
require.aliases[to] = from;
};
/**
* Return a require function relative to the `parent` path.
*
* @param {String} parent
* @return {Function}
* @api private
*/
require.relative = function(parent) {
var p = require.normalize(parent, '..');
/**
* lastIndexOf helper.
*/
function lastIndexOf(arr, obj) {
var i = arr.length;
while (i--) {
if (arr[i] === obj) return i;
}
return -1;
}
/**
* The relative require() itself.
*/
function localRequire(path) {
var resolved = localRequire.resolve(path);
return require(resolved, parent, path);
}
/**
* Resolve relative to the parent.
*/
localRequire.resolve = function(path) {
var c = path.charAt(0);
if ('/' == c) return path.slice(1);
if ('.' == c) return require.normalize(p, path);
// resolve deps by returning
// the dep in the nearest "deps"
// directory
var segs = parent.split('/');
var i = lastIndexOf(segs, 'deps') + 1;
if (!i) i = 0;
path = segs.slice(0, i + 1).join('/') + '/deps/' + path;
return path;
};
/**
* Check if module is defined at `path`.
*/
localRequire.exists = function(path) {
return require.modules.hasOwnProperty(localRequire.resolve(path));
};
return localRequire;
};
require.register("isarray/index.js", function(exports, require, module){
module.exports = Array.isArray || function (arr) {
return Object.prototype.toString.call(arr) == '[object Array]';
};
});
require.alias("isarray/index.js", "isarray/index.js");
| chi-sea-lions-2015/house-rules-frontend | node_modules/gulp-imagemin/node_modules/imagemin/node_modules/imagemin-pngquant/node_modules/pngquant-bin/node_modules/bin-build/node_modules/download/node_modules/decompress-targz/node_modules/tar-stream/node_modules/readable-stream/node_modules/isarray/build/build.js | JavaScript | mit | 4,089 |
<?php
/**
* WordPress Customize Manager classes
*
* @package WordPress
* @subpackage Customize
* @since 3.4.0
*/
/**
* Customize Manager class.
*
* Bootstraps the Customize experience on the server-side.
*
* Sets up the theme-switching process if a theme other than the active one is
* being previewed and customized.
*
* Serves as a factory for Customize Controls and Settings, and
* instantiates default Customize Controls and Settings.
*
* @since 3.4.0
*/
final class WP_Customize_Manager {
/**
* An instance of the theme being previewed.
*
* @since 3.4.0
* @access protected
* @var WP_Theme
*/
protected $theme;
/**
* The directory name of the previously active theme (within the theme_root).
*
* @since 3.4.0
* @access protected
* @var string
*/
protected $original_stylesheet;
/**
* Whether this is a Customizer pageload.
*
* @since 3.4.0
* @access protected
* @var bool
*/
protected $previewing = false;
/**
* Methods and properties dealing with managing widgets in the Customizer.
*
* @since 3.9.0
* @access public
* @var WP_Customize_Widgets
*/
public $widgets;
/**
* Methods and properties dealing with managing nav menus in the Customizer.
*
* @since 4.3.0
* @access public
* @var WP_Customize_Nav_Menus
*/
public $nav_menus;
/**
* Methods and properties dealing with selective refresh in the Customizer preview.
*
* @since 4.5.0
* @access public
* @var WP_Customize_Selective_Refresh
*/
public $selective_refresh;
/**
* Registered instances of WP_Customize_Setting.
*
* @since 3.4.0
* @access protected
* @var array
*/
protected $settings = array();
/**
* Sorted top-level instances of WP_Customize_Panel and WP_Customize_Section.
*
* @since 4.0.0
* @access protected
* @var array
*/
protected $containers = array();
/**
* Registered instances of WP_Customize_Panel.
*
* @since 4.0.0
* @access protected
* @var array
*/
protected $panels = array();
/**
* List of core components.
*
* @since 4.5.0
* @access protected
* @var array
*/
protected $components = array( 'widgets', 'nav_menus' );
/**
* Registered instances of WP_Customize_Section.
*
* @since 3.4.0
* @access protected
* @var array
*/
protected $sections = array();
/**
* Registered instances of WP_Customize_Control.
*
* @since 3.4.0
* @access protected
* @var array
*/
protected $controls = array();
/**
* Panel types that may be rendered from JS templates.
*
* @since 4.3.0
* @access protected
* @var array
*/
protected $registered_panel_types = array();
/**
* Section types that may be rendered from JS templates.
*
* @since 4.3.0
* @access protected
* @var array
*/
protected $registered_section_types = array();
/**
* Control types that may be rendered from JS templates.
*
* @since 4.1.0
* @access protected
* @var array
*/
protected $registered_control_types = array();
/**
* Initial URL being previewed.
*
* @since 4.4.0
* @access protected
* @var string
*/
protected $preview_url;
/**
* URL to link the user to when closing the Customizer.
*
* @since 4.4.0
* @access protected
* @var string
*/
protected $return_url;
/**
* Mapping of 'panel', 'section', 'control' to the ID which should be autofocused.
*
* @since 4.4.0
* @access protected
* @var array
*/
protected $autofocus = array();
/**
* Messenger channel.
*
* @since 4.7.0
* @access protected
* @var string
*/
protected $messenger_channel;
/**
* Unsanitized values for Customize Settings parsed from $_POST['customized'].
*
* @var array
*/
private $_post_values;
/**
* Changeset UUID.
*
* @since 4.7.0
* @access private
* @var string
*/
private $_changeset_uuid;
/**
* Changeset post ID.
*
* @since 4.7.0
* @access private
* @var int|false
*/
private $_changeset_post_id;
/**
* Changeset data loaded from a customize_changeset post.
*
* @since 4.7.0
* @access private
* @var array
*/
private $_changeset_data;
/**
* Constructor.
*
* @since 3.4.0
* @since 4.7.0 Added $args param.
*
* @param array $args {
* Args.
*
* @type string $changeset_uuid Changeset UUID, the post_name for the customize_changeset post containing the customized state. Defaults to new UUID.
* @type string $theme Theme to be previewed (for theme switch). Defaults to customize_theme or theme query params.
* @type string $messenger_channel Messenger channel. Defaults to customize_messenger_channel query param.
* }
*/
public function __construct( $args = array() ) {
$args = array_merge(
array_fill_keys( array( 'changeset_uuid', 'theme', 'messenger_channel' ), null ),
$args
);
// Note that the UUID format will be validated in the setup_theme() method.
if ( ! isset( $args['changeset_uuid'] ) ) {
$args['changeset_uuid'] = wp_generate_uuid4();
}
// The theme and messenger_channel should be supplied via $args, but they are also looked at in the $_REQUEST global here for back-compat.
if ( ! isset( $args['theme'] ) ) {
if ( isset( $_REQUEST['customize_theme'] ) ) {
$args['theme'] = wp_unslash( $_REQUEST['customize_theme'] );
} elseif ( isset( $_REQUEST['theme'] ) ) { // Deprecated.
$args['theme'] = wp_unslash( $_REQUEST['theme'] );
}
}
if ( ! isset( $args['messenger_channel'] ) && isset( $_REQUEST['customize_messenger_channel'] ) ) {
$args['messenger_channel'] = sanitize_key( wp_unslash( $_REQUEST['customize_messenger_channel'] ) );
}
$this->original_stylesheet = get_stylesheet();
$this->theme = wp_get_theme( 0 === validate_file( $args['theme'] ) ? $args['theme'] : null );
$this->messenger_channel = $args['messenger_channel'];
$this->_changeset_uuid = $args['changeset_uuid'];
require_once( ABSPATH . WPINC . '/class-wp-customize-setting.php' );
require_once( ABSPATH . WPINC . '/class-wp-customize-panel.php' );
require_once( ABSPATH . WPINC . '/class-wp-customize-section.php' );
require_once( ABSPATH . WPINC . '/class-wp-customize-control.php' );
require_once( ABSPATH . WPINC . '/customize/class-wp-customize-color-control.php' );
require_once( ABSPATH . WPINC . '/customize/class-wp-customize-media-control.php' );
require_once( ABSPATH . WPINC . '/customize/class-wp-customize-upload-control.php' );
require_once( ABSPATH . WPINC . '/customize/class-wp-customize-image-control.php' );
require_once( ABSPATH . WPINC . '/customize/class-wp-customize-background-image-control.php' );
require_once( ABSPATH . WPINC . '/customize/class-wp-customize-background-position-control.php' );
require_once( ABSPATH . WPINC . '/customize/class-wp-customize-cropped-image-control.php' );
require_once( ABSPATH . WPINC . '/customize/class-wp-customize-site-icon-control.php' );
require_once( ABSPATH . WPINC . '/customize/class-wp-customize-header-image-control.php' );
require_once( ABSPATH . WPINC . '/customize/class-wp-customize-theme-control.php' );
require_once( ABSPATH . WPINC . '/customize/class-wp-widget-area-customize-control.php' );
require_once( ABSPATH . WPINC . '/customize/class-wp-widget-form-customize-control.php' );
require_once( ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-control.php' );
require_once( ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-item-control.php' );
require_once( ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-location-control.php' );
require_once( ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-name-control.php' );
require_once( ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-auto-add-control.php' );
require_once( ABSPATH . WPINC . '/customize/class-wp-customize-new-menu-control.php' );
require_once( ABSPATH . WPINC . '/customize/class-wp-customize-nav-menus-panel.php' );
require_once( ABSPATH . WPINC . '/customize/class-wp-customize-themes-section.php' );
require_once( ABSPATH . WPINC . '/customize/class-wp-customize-sidebar-section.php' );
require_once( ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-section.php' );
require_once( ABSPATH . WPINC . '/customize/class-wp-customize-new-menu-section.php' );
require_once( ABSPATH . WPINC . '/customize/class-wp-customize-custom-css-setting.php' );
require_once( ABSPATH . WPINC . '/customize/class-wp-customize-filter-setting.php' );
require_once( ABSPATH . WPINC . '/customize/class-wp-customize-header-image-setting.php' );
require_once( ABSPATH . WPINC . '/customize/class-wp-customize-background-image-setting.php' );
require_once( ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-item-setting.php' );
require_once( ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-setting.php' );
/**
* Filters the core Customizer components to load.
*
* This allows Core components to be excluded from being instantiated by
* filtering them out of the array. Note that this filter generally runs
* during the {@see 'plugins_loaded'} action, so it cannot be added
* in a theme.
*
* @since 4.4.0
*
* @see WP_Customize_Manager::__construct()
*
* @param array $components List of core components to load.
* @param WP_Customize_Manager $this WP_Customize_Manager instance.
*/
$components = apply_filters( 'customize_loaded_components', $this->components, $this );
require_once( ABSPATH . WPINC . '/customize/class-wp-customize-selective-refresh.php' );
$this->selective_refresh = new WP_Customize_Selective_Refresh( $this );
if ( in_array( 'widgets', $components, true ) ) {
require_once( ABSPATH . WPINC . '/class-wp-customize-widgets.php' );
$this->widgets = new WP_Customize_Widgets( $this );
}
if ( in_array( 'nav_menus', $components, true ) ) {
require_once( ABSPATH . WPINC . '/class-wp-customize-nav-menus.php' );
$this->nav_menus = new WP_Customize_Nav_Menus( $this );
}
add_action( 'setup_theme', array( $this, 'setup_theme' ) );
add_action( 'wp_loaded', array( $this, 'wp_loaded' ) );
// Do not spawn cron (especially the alternate cron) while running the Customizer.
remove_action( 'init', 'wp_cron' );
// Do not run update checks when rendering the controls.
remove_action( 'admin_init', '_maybe_update_core' );
remove_action( 'admin_init', '_maybe_update_plugins' );
remove_action( 'admin_init', '_maybe_update_themes' );
add_action( 'wp_ajax_customize_save', array( $this, 'save' ) );
add_action( 'wp_ajax_customize_refresh_nonces', array( $this, 'refresh_nonces' ) );
add_action( 'customize_register', array( $this, 'register_controls' ) );
add_action( 'customize_register', array( $this, 'register_dynamic_settings' ), 11 ); // allow code to create settings first
add_action( 'customize_controls_init', array( $this, 'prepare_controls' ) );
add_action( 'customize_controls_enqueue_scripts', array( $this, 'enqueue_control_scripts' ) );
// Render Panel, Section, and Control templates.
add_action( 'customize_controls_print_footer_scripts', array( $this, 'render_panel_templates' ), 1 );
add_action( 'customize_controls_print_footer_scripts', array( $this, 'render_section_templates' ), 1 );
add_action( 'customize_controls_print_footer_scripts', array( $this, 'render_control_templates' ), 1 );
// Export header video settings with the partial response.
add_filter( 'customize_render_partials_response', array( $this, 'export_header_video_settings' ), 10, 3 );
// Export the settings to JS via the _wpCustomizeSettings variable.
add_action( 'customize_controls_print_footer_scripts', array( $this, 'customize_pane_settings' ), 1000 );
}
/**
* Return true if it's an Ajax request.
*
* @since 3.4.0
* @since 4.2.0 Added `$action` param.
* @access public
*
* @param string|null $action Whether the supplied Ajax action is being run.
* @return bool True if it's an Ajax request, false otherwise.
*/
public function doing_ajax( $action = null ) {
if ( ! wp_doing_ajax() ) {
return false;
}
if ( ! $action ) {
return true;
} else {
/*
* Note: we can't just use doing_action( "wp_ajax_{$action}" ) because we need
* to check before admin-ajax.php gets to that point.
*/
return isset( $_REQUEST['action'] ) && wp_unslash( $_REQUEST['action'] ) === $action;
}
}
/**
* Custom wp_die wrapper. Returns either the standard message for UI
* or the Ajax message.
*
* @since 3.4.0
*
* @param mixed $ajax_message Ajax return
* @param mixed $message UI message
*/
protected function wp_die( $ajax_message, $message = null ) {
if ( $this->doing_ajax() ) {
wp_die( $ajax_message );
}
if ( ! $message ) {
$message = __( 'Cheatin’ uh?' );
}
if ( $this->messenger_channel ) {
ob_start();
wp_enqueue_scripts();
wp_print_scripts( array( 'customize-base' ) );
$settings = array(
'messengerArgs' => array(
'channel' => $this->messenger_channel,
'url' => wp_customize_url(),
),
'error' => $ajax_message,
);
?>
<script>
( function( api, settings ) {
var preview = new api.Messenger( settings.messengerArgs );
preview.send( 'iframe-loading-error', settings.error );
} )( wp.customize, <?php echo wp_json_encode( $settings ) ?> );
</script>
<?php
$message .= ob_get_clean();
}
wp_die( $message );
}
/**
* Return the Ajax wp_die() handler if it's a customized request.
*
* @since 3.4.0
* @deprecated 4.7.0
*
* @return callable Die handler.
*/
public function wp_die_handler() {
_deprecated_function( __METHOD__, '4.7.0' );
if ( $this->doing_ajax() || isset( $_POST['customized'] ) ) {
return '_ajax_wp_die_handler';
}
return '_default_wp_die_handler';
}
/**
* Start preview and customize theme.
*
* Check if customize query variable exist. Init filters to filter the current theme.
*
* @since 3.4.0
*
* @global string $pagenow
*/
public function setup_theme() {
global $pagenow;
// Check permissions for customize.php access since this method is called before customize.php can run any code,
if ( 'customize.php' === $pagenow && ! current_user_can( 'customize' ) ) {
if ( ! is_user_logged_in() ) {
auth_redirect();
} else {
wp_die(
'<h1>' . __( 'Cheatin’ uh?' ) . '</h1>' .
'<p>' . __( 'Sorry, you are not allowed to customize this site.' ) . '</p>',
403
);
}
return;
}
if ( ! preg_match( '/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/', $this->_changeset_uuid ) ) {
$this->wp_die( -1, __( 'Invalid changeset UUID' ) );
}
/*
* Clear incoming post data if the user lacks a CSRF token (nonce). Note that the customizer
* application will inject the customize_preview_nonce query parameter into all Ajax requests.
* For similar behavior elsewhere in WordPress, see rest_cookie_check_errors() which logs out
* a user when a valid nonce isn't present.
*/
$has_post_data_nonce = (
check_ajax_referer( 'preview-customize_' . $this->get_stylesheet(), 'nonce', false )
||
check_ajax_referer( 'save-customize_' . $this->get_stylesheet(), 'nonce', false )
||
check_ajax_referer( 'preview-customize_' . $this->get_stylesheet(), 'customize_preview_nonce', false )
);
if ( ! current_user_can( 'customize' ) || ! $has_post_data_nonce ) {
unset( $_POST['customized'] );
unset( $_REQUEST['customized'] );
}
/*
* If unauthenticated then require a valid changeset UUID to load the preview.
* In this way, the UUID serves as a secret key. If the messenger channel is present,
* then send unauthenticated code to prompt re-auth.
*/
if ( ! current_user_can( 'customize' ) && ! $this->changeset_post_id() ) {
$this->wp_die( $this->messenger_channel ? 0 : -1, __( 'Non-existent changeset UUID.' ) );
}
if ( ! headers_sent() ) {
send_origin_headers();
}
// Hide the admin bar if we're embedded in the customizer iframe.
if ( $this->messenger_channel ) {
show_admin_bar( false );
}
if ( $this->is_theme_active() ) {
// Once the theme is loaded, we'll validate it.
add_action( 'after_setup_theme', array( $this, 'after_setup_theme' ) );
} else {
// If the requested theme is not the active theme and the user doesn't have the
// switch_themes cap, bail.
if ( ! current_user_can( 'switch_themes' ) ) {
$this->wp_die( -1, __( 'Sorry, you are not allowed to edit theme options on this site.' ) );
}
// If the theme has errors while loading, bail.
if ( $this->theme()->errors() ) {
$this->wp_die( -1, $this->theme()->errors()->get_error_message() );
}
// If the theme isn't allowed per multisite settings, bail.
if ( ! $this->theme()->is_allowed() ) {
$this->wp_die( -1, __( 'The requested theme does not exist.' ) );
}
}
/*
* Import theme starter content for fresh installs when landing in the customizer.
* Import starter content at after_setup_theme:100 so that any
* add_theme_support( 'starter-content' ) calls will have been made.
*/
if ( get_option( 'fresh_site' ) && 'customize.php' === $pagenow ) {
add_action( 'after_setup_theme', array( $this, 'import_theme_starter_content' ), 100 );
}
$this->start_previewing_theme();
}
/**
* Callback to validate a theme once it is loaded
*
* @since 3.4.0
*/
public function after_setup_theme() {
$doing_ajax_or_is_customized = ( $this->doing_ajax() || isset( $_POST['customized'] ) );
if ( ! $doing_ajax_or_is_customized && ! validate_current_theme() ) {
wp_redirect( 'themes.php?broken=true' );
exit;
}
}
/**
* If the theme to be previewed isn't the active theme, add filter callbacks
* to swap it out at runtime.
*
* @since 3.4.0
*/
public function start_previewing_theme() {
// Bail if we're already previewing.
if ( $this->is_preview() ) {
return;
}
$this->previewing = true;
if ( ! $this->is_theme_active() ) {
add_filter( 'template', array( $this, 'get_template' ) );
add_filter( 'stylesheet', array( $this, 'get_stylesheet' ) );
add_filter( 'pre_option_current_theme', array( $this, 'current_theme' ) );
// @link: https://core.trac.wordpress.org/ticket/20027
add_filter( 'pre_option_stylesheet', array( $this, 'get_stylesheet' ) );
add_filter( 'pre_option_template', array( $this, 'get_template' ) );
// Handle custom theme roots.
add_filter( 'pre_option_stylesheet_root', array( $this, 'get_stylesheet_root' ) );
add_filter( 'pre_option_template_root', array( $this, 'get_template_root' ) );
}
/**
* Fires once the Customizer theme preview has started.
*
* @since 3.4.0
*
* @param WP_Customize_Manager $this WP_Customize_Manager instance.
*/
do_action( 'start_previewing_theme', $this );
}
/**
* Stop previewing the selected theme.
*
* Removes filters to change the current theme.
*
* @since 3.4.0
*/
public function stop_previewing_theme() {
if ( ! $this->is_preview() ) {
return;
}
$this->previewing = false;
if ( ! $this->is_theme_active() ) {
remove_filter( 'template', array( $this, 'get_template' ) );
remove_filter( 'stylesheet', array( $this, 'get_stylesheet' ) );
remove_filter( 'pre_option_current_theme', array( $this, 'current_theme' ) );
// @link: https://core.trac.wordpress.org/ticket/20027
remove_filter( 'pre_option_stylesheet', array( $this, 'get_stylesheet' ) );
remove_filter( 'pre_option_template', array( $this, 'get_template' ) );
// Handle custom theme roots.
remove_filter( 'pre_option_stylesheet_root', array( $this, 'get_stylesheet_root' ) );
remove_filter( 'pre_option_template_root', array( $this, 'get_template_root' ) );
}
/**
* Fires once the Customizer theme preview has stopped.
*
* @since 3.4.0
*
* @param WP_Customize_Manager $this WP_Customize_Manager instance.
*/
do_action( 'stop_previewing_theme', $this );
}
/**
* Get the changeset UUID.
*
* @since 4.7.0
* @access public
*
* @return string UUID.
*/
public function changeset_uuid() {
return $this->_changeset_uuid;
}
/**
* Get the theme being customized.
*
* @since 3.4.0
*
* @return WP_Theme
*/
public function theme() {
if ( ! $this->theme ) {
$this->theme = wp_get_theme();
}
return $this->theme;
}
/**
* Get the registered settings.
*
* @since 3.4.0
*
* @return array
*/
public function settings() {
return $this->settings;
}
/**
* Get the registered controls.
*
* @since 3.4.0
*
* @return array
*/
public function controls() {
return $this->controls;
}
/**
* Get the registered containers.
*
* @since 4.0.0
*
* @return array
*/
public function containers() {
return $this->containers;
}
/**
* Get the registered sections.
*
* @since 3.4.0
*
* @return array
*/
public function sections() {
return $this->sections;
}
/**
* Get the registered panels.
*
* @since 4.0.0
* @access public
*
* @return array Panels.
*/
public function panels() {
return $this->panels;
}
/**
* Checks if the current theme is active.
*
* @since 3.4.0
*
* @return bool
*/
public function is_theme_active() {
return $this->get_stylesheet() == $this->original_stylesheet;
}
/**
* Register styles/scripts and initialize the preview of each setting
*
* @since 3.4.0
*/
public function wp_loaded() {
/**
* Fires once WordPress has loaded, allowing scripts and styles to be initialized.
*
* @since 3.4.0
*
* @param WP_Customize_Manager $this WP_Customize_Manager instance.
*/
do_action( 'customize_register', $this );
/*
* Note that settings must be previewed here even outside the customizer preview
* and also in the customizer pane itself. This is to enable loading an existing
* changeset into the customizer. Previewing the settings only has to be prevented
* in the case of a customize_save action because then update_option()
* may short-circuit because it will detect that there are no changes to
* make.
*/
if ( ! $this->doing_ajax( 'customize_save' ) ) {
foreach ( $this->settings as $setting ) {
$setting->preview();
}
}
if ( $this->is_preview() && ! is_admin() ) {
$this->customize_preview_init();
}
}
/**
* Prevents Ajax requests from following redirects when previewing a theme
* by issuing a 200 response instead of a 30x.
*
* Instead, the JS will sniff out the location header.
*
* @since 3.4.0
* @deprecated 4.7.0
*
* @param int $status Status.
* @return int
*/
public function wp_redirect_status( $status ) {
_deprecated_function( __FUNCTION__, '4.7.0' );
if ( $this->is_preview() && ! is_admin() ) {
return 200;
}
return $status;
}
/**
* Find the changeset post ID for a given changeset UUID.
*
* @since 4.7.0
* @access public
*
* @param string $uuid Changeset UUID.
* @return int|null Returns post ID on success and null on failure.
*/
public function find_changeset_post_id( $uuid ) {
$cache_group = 'customize_changeset_post';
$changeset_post_id = wp_cache_get( $uuid, $cache_group );
if ( $changeset_post_id && 'customize_changeset' === get_post_type( $changeset_post_id ) ) {
return $changeset_post_id;
}
$changeset_post_query = new WP_Query( array(
'post_type' => 'customize_changeset',
'post_status' => get_post_stati(),
'name' => $uuid,
'posts_per_page' => 1,
'no_found_rows' => true,
'cache_results' => true,
'update_post_meta_cache' => false,
'update_post_term_cache' => false,
'lazy_load_term_meta' => false,
) );
if ( ! empty( $changeset_post_query->posts ) ) {
// Note: 'fields'=>'ids' is not being used in order to cache the post object as it will be needed.
$changeset_post_id = $changeset_post_query->posts[0]->ID;
wp_cache_set( $this->_changeset_uuid, $changeset_post_id, $cache_group );
return $changeset_post_id;
}
return null;
}
/**
* Get the changeset post id for the loaded changeset.
*
* @since 4.7.0
* @access public
*
* @return int|null Post ID on success or null if there is no post yet saved.
*/
public function changeset_post_id() {
if ( ! isset( $this->_changeset_post_id ) ) {
$post_id = $this->find_changeset_post_id( $this->_changeset_uuid );
if ( ! $post_id ) {
$post_id = false;
}
$this->_changeset_post_id = $post_id;
}
if ( false === $this->_changeset_post_id ) {
return null;
}
return $this->_changeset_post_id;
}
/**
* Get the data stored in a changeset post.
*
* @since 4.7.0
* @access protected
*
* @param int $post_id Changeset post ID.
* @return array|WP_Error Changeset data or WP_Error on error.
*/
protected function get_changeset_post_data( $post_id ) {
if ( ! $post_id ) {
return new WP_Error( 'empty_post_id' );
}
$changeset_post = get_post( $post_id );
if ( ! $changeset_post ) {
return new WP_Error( 'missing_post' );
}
if ( 'customize_changeset' !== $changeset_post->post_type ) {
return new WP_Error( 'wrong_post_type' );
}
$changeset_data = json_decode( $changeset_post->post_content, true );
if ( function_exists( 'json_last_error' ) && json_last_error() ) {
return new WP_Error( 'json_parse_error', '', json_last_error() );
}
if ( ! is_array( $changeset_data ) ) {
return new WP_Error( 'expected_array' );
}
return $changeset_data;
}
/**
* Get changeset data.
*
* @since 4.7.0
* @access public
*
* @return array Changeset data.
*/
public function changeset_data() {
if ( isset( $this->_changeset_data ) ) {
return $this->_changeset_data;
}
$changeset_post_id = $this->changeset_post_id();
if ( ! $changeset_post_id ) {
$this->_changeset_data = array();
} else {
$data = $this->get_changeset_post_data( $changeset_post_id );
if ( ! is_wp_error( $data ) ) {
$this->_changeset_data = $data;
} else {
$this->_changeset_data = array();
}
}
return $this->_changeset_data;
}
/**
* Starter content setting IDs.
*
* @since 4.7.0
* @access private
* @var array
*/
protected $pending_starter_content_settings_ids = array();
/**
* Import theme starter content into the customized state.
*
* @since 4.7.0
* @access public
*
* @param array $starter_content Starter content. Defaults to `get_theme_starter_content()`.
*/
function import_theme_starter_content( $starter_content = array() ) {
if ( empty( $starter_content ) ) {
$starter_content = get_theme_starter_content();
}
$changeset_data = array();
if ( $this->changeset_post_id() ) {
$changeset_data = $this->get_changeset_post_data( $this->changeset_post_id() );
}
$sidebars_widgets = isset( $starter_content['widgets'] ) && ! empty( $this->widgets ) ? $starter_content['widgets'] : array();
$attachments = isset( $starter_content['attachments'] ) && ! empty( $this->nav_menus ) ? $starter_content['attachments'] : array();
$posts = isset( $starter_content['posts'] ) && ! empty( $this->nav_menus ) ? $starter_content['posts'] : array();
$options = isset( $starter_content['options'] ) ? $starter_content['options'] : array();
$nav_menus = isset( $starter_content['nav_menus'] ) && ! empty( $this->nav_menus ) ? $starter_content['nav_menus'] : array();
$theme_mods = isset( $starter_content['theme_mods'] ) ? $starter_content['theme_mods'] : array();
// Widgets.
$max_widget_numbers = array();
foreach ( $sidebars_widgets as $sidebar_id => $widgets ) {
$sidebar_widget_ids = array();
foreach ( $widgets as $widget ) {
list( $id_base, $instance ) = $widget;
if ( ! isset( $max_widget_numbers[ $id_base ] ) ) {
// When $settings is an array-like object, get an intrinsic array for use with array_keys().
$settings = get_option( "widget_{$id_base}", array() );
if ( $settings instanceof ArrayObject || $settings instanceof ArrayIterator ) {
$settings = $settings->getArrayCopy();
}
// Find the max widget number for this type.
$widget_numbers = array_keys( $settings );
if ( count( $widget_numbers ) > 0 ) {
$widget_numbers[] = 1;
$max_widget_numbers[ $id_base ] = call_user_func_array( 'max', $widget_numbers );
} else {
$max_widget_numbers[ $id_base ] = 1;
}
}
$max_widget_numbers[ $id_base ] += 1;
$widget_id = sprintf( '%s-%d', $id_base, $max_widget_numbers[ $id_base ] );
$setting_id = sprintf( 'widget_%s[%d]', $id_base, $max_widget_numbers[ $id_base ] );
$setting_value = $this->widgets->sanitize_widget_js_instance( $instance );
if ( empty( $changeset_data[ $setting_id ] ) || ! empty( $changeset_data[ $setting_id ]['starter_content'] ) ) {
$this->set_post_value( $setting_id, $setting_value );
$this->pending_starter_content_settings_ids[] = $setting_id;
}
$sidebar_widget_ids[] = $widget_id;
}
$setting_id = sprintf( 'sidebars_widgets[%s]', $sidebar_id );
if ( empty( $changeset_data[ $setting_id ] ) || ! empty( $changeset_data[ $setting_id ]['starter_content'] ) ) {
$this->set_post_value( $setting_id, $sidebar_widget_ids );
$this->pending_starter_content_settings_ids[] = $setting_id;
}
}
$starter_content_auto_draft_post_ids = array();
if ( ! empty( $changeset_data['nav_menus_created_posts']['value'] ) ) {
$starter_content_auto_draft_post_ids = array_merge( $starter_content_auto_draft_post_ids, $changeset_data['nav_menus_created_posts']['value'] );
}
// Make an index of all the posts needed and what their slugs are.
$needed_posts = array();
$attachments = $this->prepare_starter_content_attachments( $attachments );
foreach ( $attachments as $attachment ) {
$key = 'attachment:' . $attachment['post_name'];
$needed_posts[ $key ] = true;
}
foreach ( array_keys( $posts ) as $post_symbol ) {
if ( empty( $posts[ $post_symbol ]['post_name'] ) && empty( $posts[ $post_symbol ]['post_title'] ) ) {
unset( $posts[ $post_symbol ] );
continue;
}
if ( empty( $posts[ $post_symbol ]['post_name'] ) ) {
$posts[ $post_symbol ]['post_name'] = sanitize_title( $posts[ $post_symbol ]['post_title'] );
}
if ( empty( $posts[ $post_symbol ]['post_type'] ) ) {
$posts[ $post_symbol ]['post_type'] = 'post';
}
$needed_posts[ $posts[ $post_symbol ]['post_type'] . ':' . $posts[ $post_symbol ]['post_name'] ] = true;
}
$all_post_slugs = array_merge(
wp_list_pluck( $attachments, 'post_name' ),
wp_list_pluck( $posts, 'post_name' )
);
/*
* Obtain all post types referenced in starter content to use in query.
* This is needed because 'any' will not account for post types not yet registered.
*/
$post_types = array_filter( array_merge( array( 'attachment' ), wp_list_pluck( $posts, 'post_type' ) ) );
// Re-use auto-draft starter content posts referenced in the current customized state.
$existing_starter_content_posts = array();
if ( ! empty( $starter_content_auto_draft_post_ids ) ) {
$existing_posts_query = new WP_Query( array(
'post__in' => $starter_content_auto_draft_post_ids,
'post_status' => 'auto-draft',
'post_type' => $post_types,
'posts_per_page' => -1,
) );
foreach ( $existing_posts_query->posts as $existing_post ) {
$post_name = $existing_post->post_name;
if ( empty( $post_name ) ) {
$post_name = get_post_meta( $existing_post->ID, '_customize_draft_post_name', true );
}
$existing_starter_content_posts[ $existing_post->post_type . ':' . $post_name ] = $existing_post;
}
}
// Re-use non-auto-draft posts.
if ( ! empty( $all_post_slugs ) ) {
$existing_posts_query = new WP_Query( array(
'post_name__in' => $all_post_slugs,
'post_status' => array_diff( get_post_stati(), array( 'auto-draft' ) ),
'post_type' => 'any',
'posts_per_page' => -1,
) );
foreach ( $existing_posts_query->posts as $existing_post ) {
$key = $existing_post->post_type . ':' . $existing_post->post_name;
if ( isset( $needed_posts[ $key ] ) && ! isset( $existing_starter_content_posts[ $key ] ) ) {
$existing_starter_content_posts[ $key ] = $existing_post;
}
}
}
// Attachments are technically posts but handled differently.
if ( ! empty( $attachments ) ) {
$attachment_ids = array();
foreach ( $attachments as $symbol => $attachment ) {
$file_array = array(
'name' => $attachment['file_name'],
);
$file_path = $attachment['file_path'];
$attachment_id = null;
$attached_file = null;
if ( isset( $existing_starter_content_posts[ 'attachment:' . $attachment['post_name'] ] ) ) {
$attachment_post = $existing_starter_content_posts[ 'attachment:' . $attachment['post_name'] ];
$attachment_id = $attachment_post->ID;
$attached_file = get_attached_file( $attachment_id );
if ( empty( $attached_file ) || ! file_exists( $attached_file ) ) {
$attachment_id = null;
$attached_file = null;
} elseif ( $this->get_stylesheet() !== get_post_meta( $attachment_post->ID, '_starter_content_theme', true ) ) {
// Re-generate attachment metadata since it was previously generated for a different theme.
$metadata = wp_generate_attachment_metadata( $attachment_post->ID, $attached_file );
wp_update_attachment_metadata( $attachment_id, $metadata );
update_post_meta( $attachment_id, '_starter_content_theme', $this->get_stylesheet() );
}
}
// Insert the attachment auto-draft because it doesn't yet exist or the attached file is gone.
if ( ! $attachment_id ) {
// Copy file to temp location so that original file won't get deleted from theme after sideloading.
$temp_file_name = wp_tempnam( basename( $file_path ) );
if ( $temp_file_name && copy( $file_path, $temp_file_name ) ) {
$file_array['tmp_name'] = $temp_file_name;
}
if ( empty( $file_array['tmp_name'] ) ) {
continue;
}
$attachment_post_data = array_merge(
wp_array_slice_assoc( $attachment, array( 'post_title', 'post_content', 'post_excerpt' ) ),
array(
'post_status' => 'auto-draft', // So attachment will be garbage collected in a week if changeset is never published.
)
);
// In PHP < 5.6 filesize() returns 0 for the temp files unless we clear the file status cache.
// Technically, PHP < 5.6.0 || < 5.5.13 || < 5.4.29 but no need to be so targeted.
// See https://bugs.php.net/bug.php?id=65701
if ( version_compare( PHP_VERSION, '5.6', '<' ) ) {
clearstatcache();
}
$attachment_id = media_handle_sideload( $file_array, 0, null, $attachment_post_data );
if ( is_wp_error( $attachment_id ) ) {
continue;
}
update_post_meta( $attachment_id, '_starter_content_theme', $this->get_stylesheet() );
update_post_meta( $attachment_id, '_customize_draft_post_name', $attachment['post_name'] );
}
$attachment_ids[ $symbol ] = $attachment_id;
}
$starter_content_auto_draft_post_ids = array_merge( $starter_content_auto_draft_post_ids, array_values( $attachment_ids ) );
}
// Posts & pages.
if ( ! empty( $posts ) ) {
foreach ( array_keys( $posts ) as $post_symbol ) {
if ( empty( $posts[ $post_symbol ]['post_type'] ) || empty( $posts[ $post_symbol ]['post_name'] ) ) {
continue;
}
$post_type = $posts[ $post_symbol ]['post_type'];
if ( ! empty( $posts[ $post_symbol ]['post_name'] ) ) {
$post_name = $posts[ $post_symbol ]['post_name'];
} elseif ( ! empty( $posts[ $post_symbol ]['post_title'] ) ) {
$post_name = sanitize_title( $posts[ $post_symbol ]['post_title'] );
} else {
continue;
}
// Use existing auto-draft post if one already exists with the same type and name.
if ( isset( $existing_starter_content_posts[ $post_type . ':' . $post_name ] ) ) {
$posts[ $post_symbol ]['ID'] = $existing_starter_content_posts[ $post_type . ':' . $post_name ]->ID;
continue;
}
// Translate the featured image symbol.
if ( ! empty( $posts[ $post_symbol ]['thumbnail'] )
&& preg_match( '/^{{(?P<symbol>.+)}}$/', $posts[ $post_symbol ]['thumbnail'], $matches )
&& isset( $attachment_ids[ $matches['symbol'] ] ) ) {
$posts[ $post_symbol ]['meta_input']['_thumbnail_id'] = $attachment_ids[ $matches['symbol'] ];
}
if ( ! empty( $posts[ $post_symbol ]['template'] ) ) {
$posts[ $post_symbol ]['meta_input']['_wp_page_template'] = $posts[ $post_symbol ]['template'];
}
$r = $this->nav_menus->insert_auto_draft_post( $posts[ $post_symbol ] );
if ( $r instanceof WP_Post ) {
$posts[ $post_symbol ]['ID'] = $r->ID;
}
}
$starter_content_auto_draft_post_ids = array_merge( $starter_content_auto_draft_post_ids, wp_list_pluck( $posts, 'ID' ) );
}
// The nav_menus_created_posts setting is why nav_menus component is dependency for adding posts.
if ( ! empty( $this->nav_menus ) && ! empty( $starter_content_auto_draft_post_ids ) ) {
$setting_id = 'nav_menus_created_posts';
$this->set_post_value( $setting_id, array_unique( array_values( $starter_content_auto_draft_post_ids ) ) );
$this->pending_starter_content_settings_ids[] = $setting_id;
}
// Nav menus.
$placeholder_id = -1;
$reused_nav_menu_setting_ids = array();
foreach ( $nav_menus as $nav_menu_location => $nav_menu ) {
$nav_menu_term_id = null;
$nav_menu_setting_id = null;
$matches = array();
// Look for an existing placeholder menu with starter content to re-use.
foreach ( $changeset_data as $setting_id => $setting_params ) {
$can_reuse = (
! empty( $setting_params['starter_content'] )
&&
! in_array( $setting_id, $reused_nav_menu_setting_ids, true )
&&
preg_match( '#^nav_menu\[(?P<nav_menu_id>-?\d+)\]$#', $setting_id, $matches )
);
if ( $can_reuse ) {
$nav_menu_term_id = intval( $matches['nav_menu_id'] );
$nav_menu_setting_id = $setting_id;
$reused_nav_menu_setting_ids[] = $setting_id;
break;
}
}
if ( ! $nav_menu_term_id ) {
while ( isset( $changeset_data[ sprintf( 'nav_menu[%d]', $placeholder_id ) ] ) ) {
$placeholder_id--;
}
$nav_menu_term_id = $placeholder_id;
$nav_menu_setting_id = sprintf( 'nav_menu[%d]', $placeholder_id );
}
$this->set_post_value( $nav_menu_setting_id, array(
'name' => isset( $nav_menu['name'] ) ? $nav_menu['name'] : $nav_menu_location,
) );
$this->pending_starter_content_settings_ids[] = $nav_menu_setting_id;
// @todo Add support for menu_item_parent.
$position = 0;
foreach ( $nav_menu['items'] as $nav_menu_item ) {
$nav_menu_item_setting_id = sprintf( 'nav_menu_item[%d]', $placeholder_id-- );
if ( ! isset( $nav_menu_item['position'] ) ) {
$nav_menu_item['position'] = $position++;
}
$nav_menu_item['nav_menu_term_id'] = $nav_menu_term_id;
if ( isset( $nav_menu_item['object_id'] ) ) {
if ( 'post_type' === $nav_menu_item['type'] && preg_match( '/^{{(?P<symbol>.+)}}$/', $nav_menu_item['object_id'], $matches ) && isset( $posts[ $matches['symbol'] ] ) ) {
$nav_menu_item['object_id'] = $posts[ $matches['symbol'] ]['ID'];
if ( empty( $nav_menu_item['title'] ) ) {
$original_object = get_post( $nav_menu_item['object_id'] );
$nav_menu_item['title'] = $original_object->post_title;
}
} else {
continue;
}
} else {
$nav_menu_item['object_id'] = 0;
}
if ( empty( $changeset_data[ $nav_menu_item_setting_id ] ) || ! empty( $changeset_data[ $nav_menu_item_setting_id ]['starter_content'] ) ) {
$this->set_post_value( $nav_menu_item_setting_id, $nav_menu_item );
$this->pending_starter_content_settings_ids[] = $nav_menu_item_setting_id;
}
}
$setting_id = sprintf( 'nav_menu_locations[%s]', $nav_menu_location );
if ( empty( $changeset_data[ $setting_id ] ) || ! empty( $changeset_data[ $setting_id ]['starter_content'] ) ) {
$this->set_post_value( $setting_id, $nav_menu_term_id );
$this->pending_starter_content_settings_ids[] = $setting_id;
}
}
// Options.
foreach ( $options as $name => $value ) {
if ( preg_match( '/^{{(?P<symbol>.+)}}$/', $value, $matches ) ) {
if ( isset( $posts[ $matches['symbol'] ] ) ) {
$value = $posts[ $matches['symbol'] ]['ID'];
} elseif ( isset( $attachment_ids[ $matches['symbol'] ] ) ) {
$value = $attachment_ids[ $matches['symbol'] ];
} else {
continue;
}
}
if ( empty( $changeset_data[ $name ] ) || ! empty( $changeset_data[ $name ]['starter_content'] ) ) {
$this->set_post_value( $name, $value );
$this->pending_starter_content_settings_ids[] = $name;
}
}
// Theme mods.
foreach ( $theme_mods as $name => $value ) {
if ( preg_match( '/^{{(?P<symbol>.+)}}$/', $value, $matches ) ) {
if ( isset( $posts[ $matches['symbol'] ] ) ) {
$value = $posts[ $matches['symbol'] ]['ID'];
} elseif ( isset( $attachment_ids[ $matches['symbol'] ] ) ) {
$value = $attachment_ids[ $matches['symbol'] ];
} else {
continue;
}
}
// Handle header image as special case since setting has a legacy format.
if ( 'header_image' === $name ) {
$name = 'header_image_data';
$metadata = wp_get_attachment_metadata( $value );
if ( empty( $metadata ) ) {
continue;
}
$value = array(
'attachment_id' => $value,
'url' => wp_get_attachment_url( $value ),
'height' => $metadata['height'],
'width' => $metadata['width'],
);
} elseif ( 'background_image' === $name ) {
$value = wp_get_attachment_url( $value );
}
if ( empty( $changeset_data[ $name ] ) || ! empty( $changeset_data[ $name ]['starter_content'] ) ) {
$this->set_post_value( $name, $value );
$this->pending_starter_content_settings_ids[] = $name;
}
}
if ( ! empty( $this->pending_starter_content_settings_ids ) ) {
if ( did_action( 'customize_register' ) ) {
$this->_save_starter_content_changeset();
} else {
add_action( 'customize_register', array( $this, '_save_starter_content_changeset' ), 1000 );
}
}
}
/**
* Prepare starter content attachments.
*
* Ensure that the attachments are valid and that they have slugs and file name/path.
*
* @since 4.7.0
* @access private
*
* @param array $attachments Attachments.
* @return array Prepared attachments.
*/
protected function prepare_starter_content_attachments( $attachments ) {
$prepared_attachments = array();
if ( empty( $attachments ) ) {
return $prepared_attachments;
}
// Such is The WordPress Way.
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
require_once( ABSPATH . 'wp-admin/includes/image.php' );
foreach ( $attachments as $symbol => $attachment ) {
// A file is required and URLs to files are not currently allowed.
if ( empty( $attachment['file'] ) || preg_match( '#^https?://$#', $attachment['file'] ) ) {
continue;
}
$file_path = null;
if ( file_exists( $attachment['file'] ) ) {
$file_path = $attachment['file']; // Could be absolute path to file in plugin.
} elseif ( is_child_theme() && file_exists( get_stylesheet_directory() . '/' . $attachment['file'] ) ) {
$file_path = get_stylesheet_directory() . '/' . $attachment['file'];
} elseif ( file_exists( get_template_directory() . '/' . $attachment['file'] ) ) {
$file_path = get_template_directory() . '/' . $attachment['file'];
} else {
continue;
}
$file_name = basename( $attachment['file'] );
// Skip file types that are not recognized.
$checked_filetype = wp_check_filetype( $file_name );
if ( empty( $checked_filetype['type'] ) ) {
continue;
}
// Ensure post_name is set since not automatically derived from post_title for new auto-draft posts.
if ( empty( $attachment['post_name'] ) ) {
if ( ! empty( $attachment['post_title'] ) ) {
$attachment['post_name'] = sanitize_title( $attachment['post_title'] );
} else {
$attachment['post_name'] = sanitize_title( preg_replace( '/\.\w+$/', '', $file_name ) );
}
}
$attachment['file_name'] = $file_name;
$attachment['file_path'] = $file_path;
$prepared_attachments[ $symbol ] = $attachment;
}
return $prepared_attachments;
}
/**
* Save starter content changeset.
*
* @since 4.7.0
* @access private
*/
public function _save_starter_content_changeset() {
if ( empty( $this->pending_starter_content_settings_ids ) ) {
return;
}
$this->save_changeset_post( array(
'data' => array_fill_keys( $this->pending_starter_content_settings_ids, array( 'starter_content' => true ) ),
'starter_content' => true,
) );
$this->pending_starter_content_settings_ids = array();
}
/**
* Get dirty pre-sanitized setting values in the current customized state.
*
* The returned array consists of a merge of three sources:
* 1. If the theme is not currently active, then the base array is any stashed
* theme mods that were modified previously but never published.
* 2. The values from the current changeset, if it exists.
* 3. If the user can customize, the values parsed from the incoming
* `$_POST['customized']` JSON data.
* 4. Any programmatically-set post values via `WP_Customize_Manager::set_post_value()`.
*
* The name "unsanitized_post_values" is a carry-over from when the customized
* state was exclusively sourced from `$_POST['customized']`. Nevertheless,
* the value returned will come from the current changeset post and from the
* incoming post data.
*
* @since 4.1.1
* @since 4.7.0 Added $args param and merging with changeset values and stashed theme mods.
*
* @param array $args {
* Args.
*
* @type bool $exclude_changeset Whether the changeset values should also be excluded. Defaults to false.
* @type bool $exclude_post_data Whether the post input values should also be excluded. Defaults to false when lacking the customize capability.
* }
* @return array
*/
public function unsanitized_post_values( $args = array() ) {
$args = array_merge(
array(
'exclude_changeset' => false,
'exclude_post_data' => ! current_user_can( 'customize' ),
),
$args
);
$values = array();
// Let default values be from the stashed theme mods if doing a theme switch and if no changeset is present.
if ( ! $this->is_theme_active() ) {
$stashed_theme_mods = get_option( 'customize_stashed_theme_mods' );
$stylesheet = $this->get_stylesheet();
if ( isset( $stashed_theme_mods[ $stylesheet ] ) ) {
$values = array_merge( $values, wp_list_pluck( $stashed_theme_mods[ $stylesheet ], 'value' ) );
}
}
if ( ! $args['exclude_changeset'] ) {
foreach ( $this->changeset_data() as $setting_id => $setting_params ) {
if ( ! array_key_exists( 'value', $setting_params ) ) {
continue;
}
if ( isset( $setting_params['type'] ) && 'theme_mod' === $setting_params['type'] ) {
// Ensure that theme mods values are only used if they were saved under the current theme.
$namespace_pattern = '/^(?P<stylesheet>.+?)::(?P<setting_id>.+)$/';
if ( preg_match( $namespace_pattern, $setting_id, $matches ) && $this->get_stylesheet() === $matches['stylesheet'] ) {
$values[ $matches['setting_id'] ] = $setting_params['value'];
}
} else {
$values[ $setting_id ] = $setting_params['value'];
}
}
}
if ( ! $args['exclude_post_data'] ) {
if ( ! isset( $this->_post_values ) ) {
if ( isset( $_POST['customized'] ) ) {
$post_values = json_decode( wp_unslash( $_POST['customized'] ), true );
} else {
$post_values = array();
}
if ( is_array( $post_values ) ) {
$this->_post_values = $post_values;
} else {
$this->_post_values = array();
}
}
$values = array_merge( $values, $this->_post_values );
}
return $values;
}
/**
* Returns the sanitized value for a given setting from the current customized state.
*
* The name "post_value" is a carry-over from when the customized state was exclusively
* sourced from `$_POST['customized']`. Nevertheless, the value returned will come
* from the current changeset post and from the incoming post data.
*
* @since 3.4.0
* @since 4.1.1 Introduced the `$default` parameter.
* @since 4.6.0 `$default` is now returned early when the setting post value is invalid.
* @access public
*
* @see WP_REST_Server::dispatch()
* @see WP_Rest_Request::sanitize_params()
* @see WP_Rest_Request::has_valid_params()
*
* @param WP_Customize_Setting $setting A WP_Customize_Setting derived object.
* @param mixed $default Value returned $setting has no post value (added in 4.2.0)
* or the post value is invalid (added in 4.6.0).
* @return string|mixed $post_value Sanitized value or the $default provided.
*/
public function post_value( $setting, $default = null ) {
$post_values = $this->unsanitized_post_values();
if ( ! array_key_exists( $setting->id, $post_values ) ) {
return $default;
}
$value = $post_values[ $setting->id ];
$valid = $setting->validate( $value );
if ( is_wp_error( $valid ) ) {
return $default;
}
$value = $setting->sanitize( $value );
if ( is_null( $value ) || is_wp_error( $value ) ) {
return $default;
}
return $value;
}
/**
* Override a setting's value in the current customized state.
*
* The name "post_value" is a carry-over from when the customized state was
* exclusively sourced from `$_POST['customized']`.
*
* @since 4.2.0
* @access public
*
* @param string $setting_id ID for the WP_Customize_Setting instance.
* @param mixed $value Post value.
*/
public function set_post_value( $setting_id, $value ) {
$this->unsanitized_post_values(); // Populate _post_values from $_POST['customized'].
$this->_post_values[ $setting_id ] = $value;
/**
* Announce when a specific setting's unsanitized post value has been set.
*
* Fires when the WP_Customize_Manager::set_post_value() method is called.
*
* The dynamic portion of the hook name, `$setting_id`, refers to the setting ID.
*
* @since 4.4.0
*
* @param mixed $value Unsanitized setting post value.
* @param WP_Customize_Manager $this WP_Customize_Manager instance.
*/
do_action( "customize_post_value_set_{$setting_id}", $value, $this );
/**
* Announce when any setting's unsanitized post value has been set.
*
* Fires when the WP_Customize_Manager::set_post_value() method is called.
*
* This is useful for `WP_Customize_Setting` instances to watch
* in order to update a cached previewed value.
*
* @since 4.4.0
*
* @param string $setting_id Setting ID.
* @param mixed $value Unsanitized setting post value.
* @param WP_Customize_Manager $this WP_Customize_Manager instance.
*/
do_action( 'customize_post_value_set', $setting_id, $value, $this );
}
/**
* Print JavaScript settings.
*
* @since 3.4.0
*/
public function customize_preview_init() {
/*
* Now that Customizer previews are loaded into iframes via GET requests
* and natural URLs with transaction UUIDs added, we need to ensure that
* the responses are never cached by proxies. In practice, this will not
* be needed if the user is logged-in anyway. But if anonymous access is
* allowed then the auth cookies would not be sent and WordPress would
* not send no-cache headers by default.
*/
if ( ! headers_sent() ) {
nocache_headers();
header( 'X-Robots: noindex, nofollow, noarchive' );
}
add_action( 'wp_head', 'wp_no_robots' );
add_filter( 'wp_headers', array( $this, 'filter_iframe_security_headers' ) );
/*
* If preview is being served inside the customizer preview iframe, and
* if the user doesn't have customize capability, then it is assumed
* that the user's session has expired and they need to re-authenticate.
*/
if ( $this->messenger_channel && ! current_user_can( 'customize' ) ) {
$this->wp_die( -1, __( 'Unauthorized. You may remove the customize_messenger_channel param to preview as frontend.' ) );
return;
}
$this->prepare_controls();
add_filter( 'wp_redirect', array( $this, 'add_state_query_params' ) );
wp_enqueue_script( 'customize-preview' );
wp_enqueue_style( 'customize-preview' );
add_action( 'wp_head', array( $this, 'customize_preview_loading_style' ) );
add_action( 'wp_head', array( $this, 'remove_frameless_preview_messenger_channel' ) );
add_action( 'wp_footer', array( $this, 'customize_preview_settings' ), 20 );
add_filter( 'get_edit_post_link', '__return_empty_string' );
/**
* Fires once the Customizer preview has initialized and JavaScript
* settings have been printed.
*
* @since 3.4.0
*
* @param WP_Customize_Manager $this WP_Customize_Manager instance.
*/
do_action( 'customize_preview_init', $this );
}
/**
* Filter the X-Frame-Options and Content-Security-Policy headers to ensure frontend can load in customizer.
*
* @since 4.7.0
* @access public
*
* @param array $headers Headers.
* @return array Headers.
*/
public function filter_iframe_security_headers( $headers ) {
$customize_url = admin_url( 'customize.php' );
$headers['X-Frame-Options'] = 'ALLOW-FROM ' . $customize_url;
$headers['Content-Security-Policy'] = 'frame-ancestors ' . preg_replace( '#^(\w+://[^/]+).+?$#', '$1', $customize_url );
return $headers;
}
/**
* Add customize state query params to a given URL if preview is allowed.
*
* @since 4.7.0
* @access public
* @see wp_redirect()
* @see WP_Customize_Manager::get_allowed_url()
*
* @param string $url URL.
* @return string URL.
*/
public function add_state_query_params( $url ) {
$parsed_original_url = wp_parse_url( $url );
$is_allowed = false;
foreach ( $this->get_allowed_urls() as $allowed_url ) {
$parsed_allowed_url = wp_parse_url( $allowed_url );
$is_allowed = (
$parsed_allowed_url['scheme'] === $parsed_original_url['scheme']
&&
$parsed_allowed_url['host'] === $parsed_original_url['host']
&&
0 === strpos( $parsed_original_url['path'], $parsed_allowed_url['path'] )
);
if ( $is_allowed ) {
break;
}
}
if ( $is_allowed ) {
$query_params = array(
'customize_changeset_uuid' => $this->changeset_uuid(),
);
if ( ! $this->is_theme_active() ) {
$query_params['customize_theme'] = $this->get_stylesheet();
}
if ( $this->messenger_channel ) {
$query_params['customize_messenger_channel'] = $this->messenger_channel;
}
$url = add_query_arg( $query_params, $url );
}
return $url;
}
/**
* Prevent sending a 404 status when returning the response for the customize
* preview, since it causes the jQuery Ajax to fail. Send 200 instead.
*
* @since 4.0.0
* @deprecated 4.7.0
* @access public
*/
public function customize_preview_override_404_status() {
_deprecated_function( __METHOD__, '4.7.0' );
}
/**
* Print base element for preview frame.
*
* @since 3.4.0
* @deprecated 4.7.0
*/
public function customize_preview_base() {
_deprecated_function( __METHOD__, '4.7.0' );
}
/**
* Print a workaround to handle HTML5 tags in IE < 9.
*
* @since 3.4.0
* @deprecated 4.7.0 Customizer no longer supports IE8, so all supported browsers recognize HTML5.
*/
public function customize_preview_html5() {
_deprecated_function( __FUNCTION__, '4.7.0' );
}
/**
* Print CSS for loading indicators for the Customizer preview.
*
* @since 4.2.0
* @access public
*/
public function customize_preview_loading_style() {
?><style>
body.wp-customizer-unloading {
opacity: 0.25;
cursor: progress !important;
-webkit-transition: opacity 0.5s;
transition: opacity 0.5s;
}
body.wp-customizer-unloading * {
pointer-events: none !important;
}
form.customize-unpreviewable,
form.customize-unpreviewable input,
form.customize-unpreviewable select,
form.customize-unpreviewable button,
a.customize-unpreviewable,
area.customize-unpreviewable {
cursor: not-allowed !important;
}
</style><?php
}
/**
* Remove customize_messenger_channel query parameter from the preview window when it is not in an iframe.
*
* This ensures that the admin bar will be shown. It also ensures that link navigation will
* work as expected since the parent frame is not being sent the URL to navigate to.
*
* @since 4.7.0
* @access public
*/
public function remove_frameless_preview_messenger_channel() {
if ( ! $this->messenger_channel ) {
return;
}
?>
<script>
( function() {
var urlParser, oldQueryParams, newQueryParams, i;
if ( parent !== window ) {
return;
}
urlParser = document.createElement( 'a' );
urlParser.href = location.href;
oldQueryParams = urlParser.search.substr( 1 ).split( /&/ );
newQueryParams = [];
for ( i = 0; i < oldQueryParams.length; i += 1 ) {
if ( ! /^customize_messenger_channel=/.test( oldQueryParams[ i ] ) ) {
newQueryParams.push( oldQueryParams[ i ] );
}
}
urlParser.search = newQueryParams.join( '&' );
if ( urlParser.search !== location.search ) {
location.replace( urlParser.href );
}
} )();
</script>
<?php
}
/**
* Print JavaScript settings for preview frame.
*
* @since 3.4.0
*/
public function customize_preview_settings() {
$post_values = $this->unsanitized_post_values( array( 'exclude_changeset' => true ) );
$setting_validities = $this->validate_setting_values( $post_values );
$exported_setting_validities = array_map( array( $this, 'prepare_setting_validity_for_js' ), $setting_validities );
// Note that the REQUEST_URI is not passed into home_url() since this breaks subdirectory installs.
$self_url = empty( $_SERVER['REQUEST_URI'] ) ? home_url( '/' ) : esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) );
$state_query_params = array(
'customize_theme',
'customize_changeset_uuid',
'customize_messenger_channel',
);
$self_url = remove_query_arg( $state_query_params, $self_url );
$allowed_urls = $this->get_allowed_urls();
$allowed_hosts = array();
foreach ( $allowed_urls as $allowed_url ) {
$parsed = wp_parse_url( $allowed_url );
if ( empty( $parsed['host'] ) ) {
continue;
}
$host = $parsed['host'];
if ( ! empty( $parsed['port'] ) ) {
$host .= ':' . $parsed['port'];
}
$allowed_hosts[] = $host;
}
$switched_locale = switch_to_locale( get_user_locale() );
$l10n = array(
'shiftClickToEdit' => __( 'Shift-click to edit this element.' ),
'linkUnpreviewable' => __( 'This link is not live-previewable.' ),
'formUnpreviewable' => __( 'This form is not live-previewable.' ),
);
if ( $switched_locale ) {
restore_previous_locale();
}
$settings = array(
'changeset' => array(
'uuid' => $this->_changeset_uuid,
),
'timeouts' => array(
'selectiveRefresh' => 250,
'keepAliveSend' => 1000,
),
'theme' => array(
'stylesheet' => $this->get_stylesheet(),
'active' => $this->is_theme_active(),
),
'url' => array(
'self' => $self_url,
'allowed' => array_map( 'esc_url_raw', $this->get_allowed_urls() ),
'allowedHosts' => array_unique( $allowed_hosts ),
'isCrossDomain' => $this->is_cross_domain(),
),
'channel' => $this->messenger_channel,
'activePanels' => array(),
'activeSections' => array(),
'activeControls' => array(),
'settingValidities' => $exported_setting_validities,
'nonce' => current_user_can( 'customize' ) ? $this->get_nonces() : array(),
'l10n' => $l10n,
'_dirty' => array_keys( $post_values ),
);
foreach ( $this->panels as $panel_id => $panel ) {
if ( $panel->check_capabilities() ) {
$settings['activePanels'][ $panel_id ] = $panel->active();
foreach ( $panel->sections as $section_id => $section ) {
if ( $section->check_capabilities() ) {
$settings['activeSections'][ $section_id ] = $section->active();
}
}
}
}
foreach ( $this->sections as $id => $section ) {
if ( $section->check_capabilities() ) {
$settings['activeSections'][ $id ] = $section->active();
}
}
foreach ( $this->controls as $id => $control ) {
if ( $control->check_capabilities() ) {
$settings['activeControls'][ $id ] = $control->active();
}
}
?>
<script type="text/javascript">
var _wpCustomizeSettings = <?php echo wp_json_encode( $settings ); ?>;
_wpCustomizeSettings.values = {};
(function( v ) {
<?php
/*
* Serialize settings separately from the initial _wpCustomizeSettings
* serialization in order to avoid a peak memory usage spike.
* @todo We may not even need to export the values at all since the pane syncs them anyway.
*/
foreach ( $this->settings as $id => $setting ) {
if ( $setting->check_capabilities() ) {
printf(
"v[%s] = %s;\n",
wp_json_encode( $id ),
wp_json_encode( $setting->js_value() )
);
}
}
?>
})( _wpCustomizeSettings.values );
</script>
<?php
}
/**
* Prints a signature so we can ensure the Customizer was properly executed.
*
* @since 3.4.0
* @deprecated 4.7.0
*/
public function customize_preview_signature() {
_deprecated_function( __METHOD__, '4.7.0' );
}
/**
* Removes the signature in case we experience a case where the Customizer was not properly executed.
*
* @since 3.4.0
* @deprecated 4.7.0
*
* @param mixed $return Value passed through for {@see 'wp_die_handler'} filter.
* @return mixed Value passed through for {@see 'wp_die_handler'} filter.
*/
public function remove_preview_signature( $return = null ) {
_deprecated_function( __METHOD__, '4.7.0' );
return $return;
}
/**
* Is it a theme preview?
*
* @since 3.4.0
*
* @return bool True if it's a preview, false if not.
*/
public function is_preview() {
return (bool) $this->previewing;
}
/**
* Retrieve the template name of the previewed theme.
*
* @since 3.4.0
*
* @return string Template name.
*/
public function get_template() {
return $this->theme()->get_template();
}
/**
* Retrieve the stylesheet name of the previewed theme.
*
* @since 3.4.0
*
* @return string Stylesheet name.
*/
public function get_stylesheet() {
return $this->theme()->get_stylesheet();
}
/**
* Retrieve the template root of the previewed theme.
*
* @since 3.4.0
*
* @return string Theme root.
*/
public function get_template_root() {
return get_raw_theme_root( $this->get_template(), true );
}
/**
* Retrieve the stylesheet root of the previewed theme.
*
* @since 3.4.0
*
* @return string Theme root.
*/
public function get_stylesheet_root() {
return get_raw_theme_root( $this->get_stylesheet(), true );
}
/**
* Filters the current theme and return the name of the previewed theme.
*
* @since 3.4.0
*
* @param $current_theme {@internal Parameter is not used}
* @return string Theme name.
*/
public function current_theme( $current_theme ) {
return $this->theme()->display('Name');
}
/**
* Validates setting values.
*
* Validation is skipped for unregistered settings or for values that are
* already null since they will be skipped anyway. Sanitization is applied
* to values that pass validation, and values that become null or `WP_Error`
* after sanitizing are marked invalid.
*
* @since 4.6.0
* @access public
*
* @see WP_REST_Request::has_valid_params()
* @see WP_Customize_Setting::validate()
*
* @param array $setting_values Mapping of setting IDs to values to validate and sanitize.
* @param array $options {
* Options.
*
* @type bool $validate_existence Whether a setting's existence will be checked.
* @type bool $validate_capability Whether the setting capability will be checked.
* }
* @return array Mapping of setting IDs to return value of validate method calls, either `true` or `WP_Error`.
*/
public function validate_setting_values( $setting_values, $options = array() ) {
$options = wp_parse_args( $options, array(
'validate_capability' => false,
'validate_existence' => false,
) );
$validities = array();
foreach ( $setting_values as $setting_id => $unsanitized_value ) {
$setting = $this->get_setting( $setting_id );
if ( ! $setting ) {
if ( $options['validate_existence'] ) {
$validities[ $setting_id ] = new WP_Error( 'unrecognized', __( 'Setting does not exist or is unrecognized.' ) );
}
continue;
}
if ( $options['validate_capability'] && ! current_user_can( $setting->capability ) ) {
$validity = new WP_Error( 'unauthorized', __( 'Unauthorized to modify setting due to capability.' ) );
} else {
if ( is_null( $unsanitized_value ) ) {
continue;
}
$validity = $setting->validate( $unsanitized_value );
}
if ( ! is_wp_error( $validity ) ) {
/** This filter is documented in wp-includes/class-wp-customize-setting.php */
$late_validity = apply_filters( "customize_validate_{$setting->id}", new WP_Error(), $unsanitized_value, $setting );
if ( ! empty( $late_validity->errors ) ) {
$validity = $late_validity;
}
}
if ( ! is_wp_error( $validity ) ) {
$value = $setting->sanitize( $unsanitized_value );
if ( is_null( $value ) ) {
$validity = false;
} elseif ( is_wp_error( $value ) ) {
$validity = $value;
}
}
if ( false === $validity ) {
$validity = new WP_Error( 'invalid_value', __( 'Invalid value.' ) );
}
$validities[ $setting_id ] = $validity;
}
return $validities;
}
/**
* Prepares setting validity for exporting to the client (JS).
*
* Converts `WP_Error` instance into array suitable for passing into the
* `wp.customize.Notification` JS model.
*
* @since 4.6.0
* @access public
*
* @param true|WP_Error $validity Setting validity.
* @return true|array If `$validity` was a WP_Error, the error codes will be array-mapped
* to their respective `message` and `data` to pass into the
* `wp.customize.Notification` JS model.
*/
public function prepare_setting_validity_for_js( $validity ) {
if ( is_wp_error( $validity ) ) {
$notification = array();
foreach ( $validity->errors as $error_code => $error_messages ) {
$notification[ $error_code ] = array(
'message' => join( ' ', $error_messages ),
'data' => $validity->get_error_data( $error_code ),
);
}
return $notification;
} else {
return true;
}
}
/**
* Handle customize_save WP Ajax request to save/update a changeset.
*
* @since 3.4.0
* @since 4.7.0 The semantics of this method have changed to update a changeset, optionally to also change the status and other attributes.
*/
public function save() {
if ( ! is_user_logged_in() ) {
wp_send_json_error( 'unauthenticated' );
}
if ( ! $this->is_preview() ) {
wp_send_json_error( 'not_preview' );
}
$action = 'save-customize_' . $this->get_stylesheet();
if ( ! check_ajax_referer( $action, 'nonce', false ) ) {
wp_send_json_error( 'invalid_nonce' );
}
$changeset_post_id = $this->changeset_post_id();
if ( empty( $changeset_post_id ) ) {
if ( ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->create_posts ) ) {
wp_send_json_error( 'cannot_create_changeset_post' );
}
} else {
if ( ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->edit_post, $changeset_post_id ) ) {
wp_send_json_error( 'cannot_edit_changeset_post' );
}
}
if ( ! empty( $_POST['customize_changeset_data'] ) ) {
$input_changeset_data = json_decode( wp_unslash( $_POST['customize_changeset_data'] ), true );
if ( ! is_array( $input_changeset_data ) ) {
wp_send_json_error( 'invalid_customize_changeset_data' );
}
} else {
$input_changeset_data = array();
}
// Validate title.
$changeset_title = null;
if ( isset( $_POST['customize_changeset_title'] ) ) {
$changeset_title = sanitize_text_field( wp_unslash( $_POST['customize_changeset_title'] ) );
}
// Validate changeset status param.
$is_publish = null;
$changeset_status = null;
if ( isset( $_POST['customize_changeset_status'] ) ) {
$changeset_status = wp_unslash( $_POST['customize_changeset_status'] );
if ( ! get_post_status_object( $changeset_status ) || ! in_array( $changeset_status, array( 'draft', 'pending', 'publish', 'future' ), true ) ) {
wp_send_json_error( 'bad_customize_changeset_status', 400 );
}
$is_publish = ( 'publish' === $changeset_status || 'future' === $changeset_status );
if ( $is_publish && ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->publish_posts ) ) {
wp_send_json_error( 'changeset_publish_unauthorized', 403 );
}
}
/*
* Validate changeset date param. Date is assumed to be in local time for
* the WP if in MySQL format (YYYY-MM-DD HH:MM:SS). Otherwise, the date
* is parsed with strtotime() so that ISO date format may be supplied
* or a string like "+10 minutes".
*/
$changeset_date_gmt = null;
if ( isset( $_POST['customize_changeset_date'] ) ) {
$changeset_date = wp_unslash( $_POST['customize_changeset_date'] );
if ( preg_match( '/^\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d$/', $changeset_date ) ) {
$mm = substr( $changeset_date, 5, 2 );
$jj = substr( $changeset_date, 8, 2 );
$aa = substr( $changeset_date, 0, 4 );
$valid_date = wp_checkdate( $mm, $jj, $aa, $changeset_date );
if ( ! $valid_date ) {
wp_send_json_error( 'bad_customize_changeset_date', 400 );
}
$changeset_date_gmt = get_gmt_from_date( $changeset_date );
} else {
$timestamp = strtotime( $changeset_date );
if ( ! $timestamp ) {
wp_send_json_error( 'bad_customize_changeset_date', 400 );
}
$changeset_date_gmt = gmdate( 'Y-m-d H:i:s', $timestamp );
}
}
$r = $this->save_changeset_post( array(
'status' => $changeset_status,
'title' => $changeset_title,
'date_gmt' => $changeset_date_gmt,
'data' => $input_changeset_data,
) );
if ( is_wp_error( $r ) ) {
$response = array(
'message' => $r->get_error_message(),
'code' => $r->get_error_code(),
);
if ( is_array( $r->get_error_data() ) ) {
$response = array_merge( $response, $r->get_error_data() );
} else {
$response['data'] = $r->get_error_data();
}
} else {
$response = $r;
// Note that if the changeset status was publish, then it will get set to trash if revisions are not supported.
$response['changeset_status'] = get_post_status( $this->changeset_post_id() );
if ( $is_publish && 'trash' === $response['changeset_status'] ) {
$response['changeset_status'] = 'publish';
}
if ( 'publish' === $response['changeset_status'] ) {
$response['next_changeset_uuid'] = wp_generate_uuid4();
}
}
if ( isset( $response['setting_validities'] ) ) {
$response['setting_validities'] = array_map( array( $this, 'prepare_setting_validity_for_js' ), $response['setting_validities'] );
}
/**
* Filters response data for a successful customize_save Ajax request.
*
* This filter does not apply if there was a nonce or authentication failure.
*
* @since 4.2.0
*
* @param array $response Additional information passed back to the 'saved'
* event on `wp.customize`.
* @param WP_Customize_Manager $this WP_Customize_Manager instance.
*/
$response = apply_filters( 'customize_save_response', $response, $this );
if ( is_wp_error( $r ) ) {
wp_send_json_error( $response );
} else {
wp_send_json_success( $response );
}
}
/**
* Save the post for the loaded changeset.
*
* @since 4.7.0
* @access public
*
* @param array $args {
* Args for changeset post.
*
* @type array $data Optional additional changeset data. Values will be merged on top of any existing post values.
* @type string $status Post status. Optional. If supplied, the save will be transactional and a post revision will be allowed.
* @type string $title Post title. Optional.
* @type string $date_gmt Date in GMT. Optional.
* @type int $user_id ID for user who is saving the changeset. Optional, defaults to the current user ID.
* @type bool $starter_content Whether the data is starter content. If false (default), then $starter_content will be cleared for any $data being saved.
* }
*
* @return array|WP_Error Returns array on success and WP_Error with array data on error.
*/
function save_changeset_post( $args = array() ) {
$args = array_merge(
array(
'status' => null,
'title' => null,
'data' => array(),
'date_gmt' => null,
'user_id' => get_current_user_id(),
'starter_content' => false,
),
$args
);
$changeset_post_id = $this->changeset_post_id();
$existing_changeset_data = array();
if ( $changeset_post_id ) {
$existing_status = get_post_status( $changeset_post_id );
if ( 'publish' === $existing_status || 'trash' === $existing_status ) {
return new WP_Error( 'changeset_already_published' );
}
$existing_changeset_data = $this->get_changeset_post_data( $changeset_post_id );
}
// Fail if attempting to publish but publish hook is missing.
if ( 'publish' === $args['status'] && false === has_action( 'transition_post_status', '_wp_customize_publish_changeset' ) ) {
return new WP_Error( 'missing_publish_callback' );
}
// Validate date.
$now = gmdate( 'Y-m-d H:i:59' );
if ( $args['date_gmt'] ) {
$is_future_dated = ( mysql2date( 'U', $args['date_gmt'], false ) > mysql2date( 'U', $now, false ) );
if ( ! $is_future_dated ) {
return new WP_Error( 'not_future_date' ); // Only future dates are allowed.
}
if ( ! $this->is_theme_active() && ( 'future' === $args['status'] || $is_future_dated ) ) {
return new WP_Error( 'cannot_schedule_theme_switches' ); // This should be allowed in the future, when theme is a regular setting.
}
$will_remain_auto_draft = ( ! $args['status'] && ( ! $changeset_post_id || 'auto-draft' === get_post_status( $changeset_post_id ) ) );
if ( $will_remain_auto_draft ) {
return new WP_Error( 'cannot_supply_date_for_auto_draft_changeset' );
}
} elseif ( $changeset_post_id && 'future' === $args['status'] ) {
// Fail if the new status is future but the existing post's date is not in the future.
$changeset_post = get_post( $changeset_post_id );
if ( mysql2date( 'U', $changeset_post->post_date_gmt, false ) <= mysql2date( 'U', $now, false ) ) {
return new WP_Error( 'not_future_date' );
}
}
// The request was made via wp.customize.previewer.save().
$update_transactionally = (bool) $args['status'];
$allow_revision = (bool) $args['status'];
// Amend post values with any supplied data.
foreach ( $args['data'] as $setting_id => $setting_params ) {
if ( array_key_exists( 'value', $setting_params ) ) {
$this->set_post_value( $setting_id, $setting_params['value'] ); // Add to post values so that they can be validated and sanitized.
}
}
// Note that in addition to post data, this will include any stashed theme mods.
$post_values = $this->unsanitized_post_values( array(
'exclude_changeset' => true,
'exclude_post_data' => false,
) );
$this->add_dynamic_settings( array_keys( $post_values ) ); // Ensure settings get created even if they lack an input value.
/*
* Get list of IDs for settings that have values different from what is currently
* saved in the changeset. By skipping any values that are already the same, the
* subset of changed settings can be passed into validate_setting_values to prevent
* an underprivileged modifying a single setting for which they have the capability
* from being blocked from saving. This also prevents a user from touching of the
* previous saved settings and overriding the associated user_id if they made no change.
*/
$changed_setting_ids = array();
foreach ( $post_values as $setting_id => $setting_value ) {
$setting = $this->get_setting( $setting_id );
if ( $setting && 'theme_mod' === $setting->type ) {
$prefixed_setting_id = $this->get_stylesheet() . '::' . $setting->id;
} else {
$prefixed_setting_id = $setting_id;
}
$is_value_changed = (
! isset( $existing_changeset_data[ $prefixed_setting_id ] )
||
! array_key_exists( 'value', $existing_changeset_data[ $prefixed_setting_id ] )
||
$existing_changeset_data[ $prefixed_setting_id ]['value'] !== $setting_value
);
if ( $is_value_changed ) {
$changed_setting_ids[] = $setting_id;
}
}
/**
* Fires before save validation happens.
*
* Plugins can add just-in-time {@see 'customize_validate_{$this->ID}'} filters
* at this point to catch any settings registered after `customize_register`.
* The dynamic portion of the hook name, `$this->ID` refers to the setting ID.
*
* @since 4.6.0
*
* @param WP_Customize_Manager $this WP_Customize_Manager instance.
*/
do_action( 'customize_save_validation_before', $this );
// Validate settings.
$validated_values = array_merge(
array_fill_keys( array_keys( $args['data'] ), null ), // Make sure existence/capability checks are done on value-less setting updates.
$post_values
);
$setting_validities = $this->validate_setting_values( $validated_values, array(
'validate_capability' => true,
'validate_existence' => true,
) );
$invalid_setting_count = count( array_filter( $setting_validities, 'is_wp_error' ) );
/*
* Short-circuit if there are invalid settings the update is transactional.
* A changeset update is transactional when a status is supplied in the request.
*/
if ( $update_transactionally && $invalid_setting_count > 0 ) {
$response = array(
'setting_validities' => $setting_validities,
'message' => sprintf( _n( 'There is %s invalid setting.', 'There are %s invalid settings.', $invalid_setting_count ), number_format_i18n( $invalid_setting_count ) ),
);
return new WP_Error( 'transaction_fail', '', $response );
}
// Obtain/merge data for changeset.
$original_changeset_data = $this->get_changeset_post_data( $changeset_post_id );
$data = $original_changeset_data;
if ( is_wp_error( $data ) ) {
$data = array();
}
// Ensure that all post values are included in the changeset data.
foreach ( $post_values as $setting_id => $post_value ) {
if ( ! isset( $args['data'][ $setting_id ] ) ) {
$args['data'][ $setting_id ] = array();
}
if ( ! isset( $args['data'][ $setting_id ]['value'] ) ) {
$args['data'][ $setting_id ]['value'] = $post_value;
}
}
foreach ( $args['data'] as $setting_id => $setting_params ) {
$setting = $this->get_setting( $setting_id );
if ( ! $setting || ! $setting->check_capabilities() ) {
continue;
}
// Skip updating changeset for invalid setting values.
if ( isset( $setting_validities[ $setting_id ] ) && is_wp_error( $setting_validities[ $setting_id ] ) ) {
continue;
}
$changeset_setting_id = $setting_id;
if ( 'theme_mod' === $setting->type ) {
$changeset_setting_id = sprintf( '%s::%s', $this->get_stylesheet(), $setting_id );
}
if ( null === $setting_params ) {
// Remove setting from changeset entirely.
unset( $data[ $changeset_setting_id ] );
} else {
if ( ! isset( $data[ $changeset_setting_id ] ) ) {
$data[ $changeset_setting_id ] = array();
}
// Merge any additional setting params that have been supplied with the existing params.
$merged_setting_params = array_merge( $data[ $changeset_setting_id ], $setting_params );
// Skip updating setting params if unchanged (ensuring the user_id is not overwritten).
if ( $data[ $changeset_setting_id ] === $merged_setting_params ) {
continue;
}
$data[ $changeset_setting_id ] = array_merge(
$merged_setting_params,
array(
'type' => $setting->type,
'user_id' => $args['user_id'],
)
);
// Clear starter_content flag in data if changeset is not explicitly being updated for starter content.
if ( empty( $args['starter_content'] ) ) {
unset( $data[ $changeset_setting_id ]['starter_content'] );
}
}
}
$filter_context = array(
'uuid' => $this->changeset_uuid(),
'title' => $args['title'],
'status' => $args['status'],
'date_gmt' => $args['date_gmt'],
'post_id' => $changeset_post_id,
'previous_data' => is_wp_error( $original_changeset_data ) ? array() : $original_changeset_data,
'manager' => $this,
);
/**
* Filters the settings' data that will be persisted into the changeset.
*
* Plugins may amend additional data (such as additional meta for settings) into the changeset with this filter.
*
* @since 4.7.0
*
* @param array $data Updated changeset data, mapping setting IDs to arrays containing a $value item and optionally other metadata.
* @param array $context {
* Filter context.
*
* @type string $uuid Changeset UUID.
* @type string $title Requested title for the changeset post.
* @type string $status Requested status for the changeset post.
* @type string $date_gmt Requested date for the changeset post in MySQL format and GMT timezone.
* @type int|false $post_id Post ID for the changeset, or false if it doesn't exist yet.
* @type array $previous_data Previous data contained in the changeset.
* @type WP_Customize_Manager $manager Manager instance.
* }
*/
$data = apply_filters( 'customize_changeset_save_data', $data, $filter_context );
// Switch theme if publishing changes now.
if ( 'publish' === $args['status'] && ! $this->is_theme_active() ) {
// Temporarily stop previewing the theme to allow switch_themes() to operate properly.
$this->stop_previewing_theme();
switch_theme( $this->get_stylesheet() );
update_option( 'theme_switched_via_customizer', true );
$this->start_previewing_theme();
}
// Gather the data for wp_insert_post()/wp_update_post().
$json_options = 0;
if ( defined( 'JSON_UNESCAPED_SLASHES' ) ) {
$json_options |= JSON_UNESCAPED_SLASHES; // Introduced in PHP 5.4. This is only to improve readability as slashes needn't be escaped in storage.
}
$json_options |= JSON_PRETTY_PRINT; // Also introduced in PHP 5.4, but WP defines constant for back compat. See WP Trac #30139.
$post_array = array(
'post_content' => wp_json_encode( $data, $json_options ),
);
if ( $args['title'] ) {
$post_array['post_title'] = $args['title'];
}
if ( $changeset_post_id ) {
$post_array['ID'] = $changeset_post_id;
} else {
$post_array['post_type'] = 'customize_changeset';
$post_array['post_name'] = $this->changeset_uuid();
$post_array['post_status'] = 'auto-draft';
}
if ( $args['status'] ) {
$post_array['post_status'] = $args['status'];
}
// Reset post date to now if we are publishing, otherwise pass post_date_gmt and translate for post_date.
if ( 'publish' === $args['status'] ) {
$post_array['post_date_gmt'] = '0000-00-00 00:00:00';
$post_array['post_date'] = '0000-00-00 00:00:00';
} elseif ( $args['date_gmt'] ) {
$post_array['post_date_gmt'] = $args['date_gmt'];
$post_array['post_date'] = get_date_from_gmt( $args['date_gmt'] );
} elseif ( $changeset_post_id && 'auto-draft' === get_post_status( $changeset_post_id ) ) {
/*
* Keep bumping the date for the auto-draft whenever it is modified;
* this extends its life, preserving it from garbage-collection via
* wp_delete_auto_drafts().
*/
$post_array['post_date'] = current_time( 'mysql' );
$post_array['post_date_gmt'] = '';
}
$this->store_changeset_revision = $allow_revision;
add_filter( 'wp_save_post_revision_post_has_changed', array( $this, '_filter_revision_post_has_changed' ), 5, 3 );
// Update the changeset post. The publish_customize_changeset action will cause the settings in the changeset to be saved via WP_Customize_Setting::save().
$has_kses = ( false !== has_filter( 'content_save_pre', 'wp_filter_post_kses' ) );
if ( $has_kses ) {
kses_remove_filters(); // Prevent KSES from corrupting JSON in post_content.
}
// Note that updating a post with publish status will trigger WP_Customize_Manager::publish_changeset_values().
if ( $changeset_post_id ) {
$post_array['edit_date'] = true; // Prevent date clearing.
$r = wp_update_post( wp_slash( $post_array ), true );
} else {
$r = wp_insert_post( wp_slash( $post_array ), true );
if ( ! is_wp_error( $r ) ) {
$this->_changeset_post_id = $r; // Update cached post ID for the loaded changeset.
}
}
if ( $has_kses ) {
kses_init_filters();
}
$this->_changeset_data = null; // Reset so WP_Customize_Manager::changeset_data() will re-populate with updated contents.
remove_filter( 'wp_save_post_revision_post_has_changed', array( $this, '_filter_revision_post_has_changed' ) );
$response = array(
'setting_validities' => $setting_validities,
);
if ( is_wp_error( $r ) ) {
$response['changeset_post_save_failure'] = $r->get_error_code();
return new WP_Error( 'changeset_post_save_failure', '', $response );
}
return $response;
}
/**
* Whether a changeset revision should be made.
*
* @since 4.7.0
* @access private
* @var bool
*/
protected $store_changeset_revision;
/**
* Filters whether a changeset has changed to create a new revision.
*
* Note that this will not be called while a changeset post remains in auto-draft status.
*
* @since 4.7.0
* @access private
*
* @param bool $post_has_changed Whether the post has changed.
* @param WP_Post $last_revision The last revision post object.
* @param WP_Post $post The post object.
*
* @return bool Whether a revision should be made.
*/
public function _filter_revision_post_has_changed( $post_has_changed, $last_revision, $post ) {
unset( $last_revision );
if ( 'customize_changeset' === $post->post_type ) {
$post_has_changed = $this->store_changeset_revision;
}
return $post_has_changed;
}
/**
* Publish changeset values.
*
* This will the values contained in a changeset, even changesets that do not
* correspond to current manager instance. This is called by
* `_wp_customize_publish_changeset()` when a customize_changeset post is
* transitioned to the `publish` status. As such, this method should not be
* called directly and instead `wp_publish_post()` should be used.
*
* Please note that if the settings in the changeset are for a non-activated
* theme, the theme must first be switched to (via `switch_theme()`) before
* invoking this method.
*
* @since 4.7.0
* @access private
* @see _wp_customize_publish_changeset()
*
* @param int $changeset_post_id ID for customize_changeset post. Defaults to the changeset for the current manager instance.
* @return true|WP_Error True or error info.
*/
public function _publish_changeset_values( $changeset_post_id ) {
$publishing_changeset_data = $this->get_changeset_post_data( $changeset_post_id );
if ( is_wp_error( $publishing_changeset_data ) ) {
return $publishing_changeset_data;
}
$changeset_post = get_post( $changeset_post_id );
/*
* Temporarily override the changeset context so that it will be read
* in calls to unsanitized_post_values() and so that it will be available
* on the $wp_customize object passed to hooks during the save logic.
*/
$previous_changeset_post_id = $this->_changeset_post_id;
$this->_changeset_post_id = $changeset_post_id;
$previous_changeset_uuid = $this->_changeset_uuid;
$this->_changeset_uuid = $changeset_post->post_name;
$previous_changeset_data = $this->_changeset_data;
$this->_changeset_data = $publishing_changeset_data;
// Parse changeset data to identify theme mod settings and user IDs associated with settings to be saved.
$setting_user_ids = array();
$theme_mod_settings = array();
$namespace_pattern = '/^(?P<stylesheet>.+?)::(?P<setting_id>.+)$/';
$matches = array();
foreach ( $this->_changeset_data as $raw_setting_id => $setting_params ) {
$actual_setting_id = null;
$is_theme_mod_setting = (
isset( $setting_params['value'] )
&&
isset( $setting_params['type'] )
&&
'theme_mod' === $setting_params['type']
&&
preg_match( $namespace_pattern, $raw_setting_id, $matches )
);
if ( $is_theme_mod_setting ) {
if ( ! isset( $theme_mod_settings[ $matches['stylesheet'] ] ) ) {
$theme_mod_settings[ $matches['stylesheet'] ] = array();
}
$theme_mod_settings[ $matches['stylesheet'] ][ $matches['setting_id'] ] = $setting_params;
if ( $this->get_stylesheet() === $matches['stylesheet'] ) {
$actual_setting_id = $matches['setting_id'];
}
} else {
$actual_setting_id = $raw_setting_id;
}
// Keep track of the user IDs for settings actually for this theme.
if ( $actual_setting_id && isset( $setting_params['user_id'] ) ) {
$setting_user_ids[ $actual_setting_id ] = $setting_params['user_id'];
}
}
$changeset_setting_values = $this->unsanitized_post_values( array(
'exclude_post_data' => true,
'exclude_changeset' => false,
) );
$changeset_setting_ids = array_keys( $changeset_setting_values );
$this->add_dynamic_settings( $changeset_setting_ids );
/**
* Fires once the theme has switched in the Customizer, but before settings
* have been saved.
*
* @since 3.4.0
*
* @param WP_Customize_Manager $manager WP_Customize_Manager instance.
*/
do_action( 'customize_save', $this );
/*
* Ensure that all settings will allow themselves to be saved. Note that
* this is safe because the setting would have checked the capability
* when the setting value was written into the changeset. So this is why
* an additional capability check is not required here.
*/
$original_setting_capabilities = array();
foreach ( $changeset_setting_ids as $setting_id ) {
$setting = $this->get_setting( $setting_id );
if ( $setting && ! isset( $setting_user_ids[ $setting_id ] ) ) {
$original_setting_capabilities[ $setting->id ] = $setting->capability;
$setting->capability = 'exist';
}
}
$original_user_id = get_current_user_id();
foreach ( $changeset_setting_ids as $setting_id ) {
$setting = $this->get_setting( $setting_id );
if ( $setting ) {
/*
* Set the current user to match the user who saved the value into
* the changeset so that any filters that apply during the save
* process will respect the original user's capabilities. This
* will ensure, for example, that KSES won't strip unsafe HTML
* when a scheduled changeset publishes via WP Cron.
*/
if ( isset( $setting_user_ids[ $setting_id ] ) ) {
wp_set_current_user( $setting_user_ids[ $setting_id ] );
} else {
wp_set_current_user( $original_user_id );
}
$setting->save();
}
}
wp_set_current_user( $original_user_id );
// Update the stashed theme mod settings, removing the active theme's stashed settings, if activated.
if ( did_action( 'switch_theme' ) ) {
$other_theme_mod_settings = $theme_mod_settings;
unset( $other_theme_mod_settings[ $this->get_stylesheet() ] );
$this->update_stashed_theme_mod_settings( $other_theme_mod_settings );
}
/**
* Fires after Customize settings have been saved.
*
* @since 3.6.0
*
* @param WP_Customize_Manager $manager WP_Customize_Manager instance.
*/
do_action( 'customize_save_after', $this );
// Restore original capabilities.
foreach ( $original_setting_capabilities as $setting_id => $capability ) {
$setting = $this->get_setting( $setting_id );
if ( $setting ) {
$setting->capability = $capability;
}
}
// Restore original changeset data.
$this->_changeset_data = $previous_changeset_data;
$this->_changeset_post_id = $previous_changeset_post_id;
$this->_changeset_uuid = $previous_changeset_uuid;
return true;
}
/**
* Update stashed theme mod settings.
*
* @since 4.7.0
* @access private
*
* @param array $inactive_theme_mod_settings Mapping of stylesheet to arrays of theme mod settings.
* @return array|false Returns array of updated stashed theme mods or false if the update failed or there were no changes.
*/
protected function update_stashed_theme_mod_settings( $inactive_theme_mod_settings ) {
$stashed_theme_mod_settings = get_option( 'customize_stashed_theme_mods' );
if ( empty( $stashed_theme_mod_settings ) ) {
$stashed_theme_mod_settings = array();
}
// Delete any stashed theme mods for the active theme since since they would have been loaded and saved upon activation.
unset( $stashed_theme_mod_settings[ $this->get_stylesheet() ] );
// Merge inactive theme mods with the stashed theme mod settings.
foreach ( $inactive_theme_mod_settings as $stylesheet => $theme_mod_settings ) {
if ( ! isset( $stashed_theme_mod_settings[ $stylesheet ] ) ) {
$stashed_theme_mod_settings[ $stylesheet ] = array();
}
$stashed_theme_mod_settings[ $stylesheet ] = array_merge(
$stashed_theme_mod_settings[ $stylesheet ],
$theme_mod_settings
);
}
$autoload = false;
$result = update_option( 'customize_stashed_theme_mods', $stashed_theme_mod_settings, $autoload );
if ( ! $result ) {
return false;
}
return $stashed_theme_mod_settings;
}
/**
* Refresh nonces for the current preview.
*
* @since 4.2.0
*/
public function refresh_nonces() {
if ( ! $this->is_preview() ) {
wp_send_json_error( 'not_preview' );
}
wp_send_json_success( $this->get_nonces() );
}
/**
* Add a customize setting.
*
* @since 3.4.0
* @since 4.5.0 Return added WP_Customize_Setting instance.
*
* @param WP_Customize_Setting|string $id Customize Setting object, or ID.
* @param array $args {
* Optional. Array of properties for the new WP_Customize_Setting. Default empty array.
*
* @type string $type Type of the setting. Default 'theme_mod'.
* Default 160.
* @type string $capability Capability required for the setting. Default 'edit_theme_options'
* @type string|array $theme_supports Theme features required to support the panel. Default is none.
* @type string $default Default value for the setting. Default is empty string.
* @type string $transport Options for rendering the live preview of changes in Theme Customizer.
* Using 'refresh' makes the change visible by reloading the whole preview.
* Using 'postMessage' allows a custom JavaScript to handle live changes.
* @link https://developer.wordpress.org/themes/customize-api
* Default is 'refresh'
* @type callable $validate_callback Server-side validation callback for the setting's value.
* @type callable $sanitize_callback Callback to filter a Customize setting value in un-slashed form.
* @type callable $sanitize_js_callback Callback to convert a Customize PHP setting value to a value that is
* JSON serializable.
* @type bool $dirty Whether or not the setting is initially dirty when created.
* }
* @return WP_Customize_Setting The instance of the setting that was added.
*/
public function add_setting( $id, $args = array() ) {
if ( $id instanceof WP_Customize_Setting ) {
$setting = $id;
} else {
$class = 'WP_Customize_Setting';
/** This filter is documented in wp-includes/class-wp-customize-manager.php */
$args = apply_filters( 'customize_dynamic_setting_args', $args, $id );
/** This filter is documented in wp-includes/class-wp-customize-manager.php */
$class = apply_filters( 'customize_dynamic_setting_class', $class, $id, $args );
$setting = new $class( $this, $id, $args );
}
$this->settings[ $setting->id ] = $setting;
return $setting;
}
/**
* Register any dynamically-created settings, such as those from $_POST['customized']
* that have no corresponding setting created.
*
* This is a mechanism to "wake up" settings that have been dynamically created
* on the front end and have been sent to WordPress in `$_POST['customized']`. When WP
* loads, the dynamically-created settings then will get created and previewed
* even though they are not directly created statically with code.
*
* @since 4.2.0
* @access public
*
* @param array $setting_ids The setting IDs to add.
* @return array The WP_Customize_Setting objects added.
*/
public function add_dynamic_settings( $setting_ids ) {
$new_settings = array();
foreach ( $setting_ids as $setting_id ) {
// Skip settings already created
if ( $this->get_setting( $setting_id ) ) {
continue;
}
$setting_args = false;
$setting_class = 'WP_Customize_Setting';
/**
* Filters a dynamic setting's constructor args.
*
* For a dynamic setting to be registered, this filter must be employed
* to override the default false value with an array of args to pass to
* the WP_Customize_Setting constructor.
*
* @since 4.2.0
*
* @param false|array $setting_args The arguments to the WP_Customize_Setting constructor.
* @param string $setting_id ID for dynamic setting, usually coming from `$_POST['customized']`.
*/
$setting_args = apply_filters( 'customize_dynamic_setting_args', $setting_args, $setting_id );
if ( false === $setting_args ) {
continue;
}
/**
* Allow non-statically created settings to be constructed with custom WP_Customize_Setting subclass.
*
* @since 4.2.0
*
* @param string $setting_class WP_Customize_Setting or a subclass.
* @param string $setting_id ID for dynamic setting, usually coming from `$_POST['customized']`.
* @param array $setting_args WP_Customize_Setting or a subclass.
*/
$setting_class = apply_filters( 'customize_dynamic_setting_class', $setting_class, $setting_id, $setting_args );
$setting = new $setting_class( $this, $setting_id, $setting_args );
$this->add_setting( $setting );
$new_settings[] = $setting;
}
return $new_settings;
}
/**
* Retrieve a customize setting.
*
* @since 3.4.0
*
* @param string $id Customize Setting ID.
* @return WP_Customize_Setting|void The setting, if set.
*/
public function get_setting( $id ) {
if ( isset( $this->settings[ $id ] ) ) {
return $this->settings[ $id ];
}
}
/**
* Remove a customize setting.
*
* @since 3.4.0
*
* @param string $id Customize Setting ID.
*/
public function remove_setting( $id ) {
unset( $this->settings[ $id ] );
}
/**
* Add a customize panel.
*
* @since 4.0.0
* @since 4.5.0 Return added WP_Customize_Panel instance.
*
* @param WP_Customize_Panel|string $id Customize Panel object, or Panel ID.
* @param array $args {
* Optional. Array of properties for the new Panel object. Default empty array.
* @type int $priority Priority of the panel, defining the display order of panels and sections.
* Default 160.
* @type string $capability Capability required for the panel. Default `edit_theme_options`
* @type string|array $theme_supports Theme features required to support the panel.
* @type string $title Title of the panel to show in UI.
* @type string $description Description to show in the UI.
* @type string $type Type of the panel.
* @type callable $active_callback Active callback.
* }
* @return WP_Customize_Panel The instance of the panel that was added.
*/
public function add_panel( $id, $args = array() ) {
if ( $id instanceof WP_Customize_Panel ) {
$panel = $id;
} else {
$panel = new WP_Customize_Panel( $this, $id, $args );
}
$this->panels[ $panel->id ] = $panel;
return $panel;
}
/**
* Retrieve a customize panel.
*
* @since 4.0.0
* @access public
*
* @param string $id Panel ID to get.
* @return WP_Customize_Panel|void Requested panel instance, if set.
*/
public function get_panel( $id ) {
if ( isset( $this->panels[ $id ] ) ) {
return $this->panels[ $id ];
}
}
/**
* Remove a customize panel.
*
* @since 4.0.0
* @access public
*
* @param string $id Panel ID to remove.
*/
public function remove_panel( $id ) {
// Removing core components this way is _doing_it_wrong().
if ( in_array( $id, $this->components, true ) ) {
/* translators: 1: panel id, 2: link to 'customize_loaded_components' filter reference */
$message = sprintf( __( 'Removing %1$s manually will cause PHP warnings. Use the %2$s filter instead.' ),
$id,
'<a href="' . esc_url( 'https://developer.wordpress.org/reference/hooks/customize_loaded_components/' ) . '"><code>customize_loaded_components</code></a>'
);
_doing_it_wrong( __METHOD__, $message, '4.5.0' );
}
unset( $this->panels[ $id ] );
}
/**
* Register a customize panel type.
*
* Registered types are eligible to be rendered via JS and created dynamically.
*
* @since 4.3.0
* @access public
*
* @see WP_Customize_Panel
*
* @param string $panel Name of a custom panel which is a subclass of WP_Customize_Panel.
*/
public function register_panel_type( $panel ) {
$this->registered_panel_types[] = $panel;
}
/**
* Render JS templates for all registered panel types.
*
* @since 4.3.0
* @access public
*/
public function render_panel_templates() {
foreach ( $this->registered_panel_types as $panel_type ) {
$panel = new $panel_type( $this, 'temp', array() );
$panel->print_template();
}
}
/**
* Add a customize section.
*
* @since 3.4.0
* @since 4.5.0 Return added WP_Customize_Section instance.
* @access public
*
* @param WP_Customize_Section|string $id Customize Section object, or Section ID.
* @param array $args {
* Optional. Array of properties for the new Panel object. Default empty array.
* @type int $priority Priority of the panel, defining the display order of panels and sections.
* Default 160.
* @type string $panel Priority of the panel, defining the display order of panels and sections.
* @type string $capability Capability required for the panel. Default 'edit_theme_options'
* @type string|array $theme_supports Theme features required to support the panel.
* @type string $title Title of the panel to show in UI.
* @type string $description Description to show in the UI.
* @type string $type Type of the panel.
* @type callable $active_callback Active callback.
* @type bool $description_hidden Hide the description behind a help icon, instead of . Default false.
* }
* @return WP_Customize_Section The instance of the section that was added.
*/
public function add_section( $id, $args = array() ) {
if ( $id instanceof WP_Customize_Section ) {
$section = $id;
} else {
$section = new WP_Customize_Section( $this, $id, $args );
}
$this->sections[ $section->id ] = $section;
return $section;
}
/**
* Retrieve a customize section.
*
* @since 3.4.0
*
* @param string $id Section ID.
* @return WP_Customize_Section|void The section, if set.
*/
public function get_section( $id ) {
if ( isset( $this->sections[ $id ] ) )
return $this->sections[ $id ];
}
/**
* Remove a customize section.
*
* @since 3.4.0
*
* @param string $id Section ID.
*/
public function remove_section( $id ) {
unset( $this->sections[ $id ] );
}
/**
* Register a customize section type.
*
* Registered types are eligible to be rendered via JS and created dynamically.
*
* @since 4.3.0
* @access public
*
* @see WP_Customize_Section
*
* @param string $section Name of a custom section which is a subclass of WP_Customize_Section.
*/
public function register_section_type( $section ) {
$this->registered_section_types[] = $section;
}
/**
* Render JS templates for all registered section types.
*
* @since 4.3.0
* @access public
*/
public function render_section_templates() {
foreach ( $this->registered_section_types as $section_type ) {
$section = new $section_type( $this, 'temp', array() );
$section->print_template();
}
}
/**
* Add a customize control.
*
* @since 3.4.0
* @since 4.5.0 Return added WP_Customize_Control instance.
* @access public
*
* @param WP_Customize_Control|string $id Customize Control object, or ID.
* @param array $args {
* Optional. Array of properties for the new Control object. Default empty array.
*
* @type array $settings All settings tied to the control. If undefined, defaults to `$setting`.
* IDs in the array correspond to the ID of a registered `WP_Customize_Setting`.
* @type string $setting The primary setting for the control (if there is one). Default is 'default'.
* @type string $capability Capability required to use this control. Normally derived from `$settings`.
* @type int $priority Order priority to load the control. Default 10.
* @type string $section The section this control belongs to. Default empty.
* @type string $label Label for the control. Default empty.
* @type string $description Description for the control. Default empty.
* @type array $choices List of choices for 'radio' or 'select' type controls, where values
* are the keys, and labels are the values. Default empty array.
* @type array $input_attrs List of custom input attributes for control output, where attribute
* names are the keys and values are the values. Default empty array.
* @type bool $allow_addition Show UI for adding new content, currently only used for the
* dropdown-pages control. Default false.
* @type string $type The type of the control. Default 'text'.
* @type callback $active_callback Active callback.
* }
* @return WP_Customize_Control The instance of the control that was added.
*/
public function add_control( $id, $args = array() ) {
if ( $id instanceof WP_Customize_Control ) {
$control = $id;
} else {
$control = new WP_Customize_Control( $this, $id, $args );
}
$this->controls[ $control->id ] = $control;
return $control;
}
/**
* Retrieve a customize control.
*
* @since 3.4.0
*
* @param string $id ID of the control.
* @return WP_Customize_Control|void The control object, if set.
*/
public function get_control( $id ) {
if ( isset( $this->controls[ $id ] ) )
return $this->controls[ $id ];
}
/**
* Remove a customize control.
*
* @since 3.4.0
*
* @param string $id ID of the control.
*/
public function remove_control( $id ) {
unset( $this->controls[ $id ] );
}
/**
* Register a customize control type.
*
* Registered types are eligible to be rendered via JS and created dynamically.
*
* @since 4.1.0
* @access public
*
* @param string $control Name of a custom control which is a subclass of
* WP_Customize_Control.
*/
public function register_control_type( $control ) {
$this->registered_control_types[] = $control;
}
/**
* Render JS templates for all registered control types.
*
* @since 4.1.0
* @access public
*/
public function render_control_templates() {
foreach ( $this->registered_control_types as $control_type ) {
$control = new $control_type( $this, 'temp', array(
'settings' => array(),
) );
$control->print_template();
}
?>
<script type="text/html" id="tmpl-customize-control-notifications">
<ul>
<# _.each( data.notifications, function( notification ) { #>
<li class="notice notice-{{ notification.type || 'info' }} {{ data.altNotice ? 'notice-alt' : '' }}" data-code="{{ notification.code }}" data-type="{{ notification.type }}">{{{ notification.message || notification.code }}}</li>
<# } ); #>
</ul>
</script>
<?php
}
/**
* Helper function to compare two objects by priority, ensuring sort stability via instance_number.
*
* @since 3.4.0
* @deprecated 4.7.0 Use wp_list_sort()
*
* @param WP_Customize_Panel|WP_Customize_Section|WP_Customize_Control $a Object A.
* @param WP_Customize_Panel|WP_Customize_Section|WP_Customize_Control $b Object B.
* @return int
*/
protected function _cmp_priority( $a, $b ) {
_deprecated_function( __METHOD__, '4.7.0', 'wp_list_sort' );
if ( $a->priority === $b->priority ) {
return $a->instance_number - $b->instance_number;
} else {
return $a->priority - $b->priority;
}
}
/**
* Prepare panels, sections, and controls.
*
* For each, check if required related components exist,
* whether the user has the necessary capabilities,
* and sort by priority.
*
* @since 3.4.0
*/
public function prepare_controls() {
$controls = array();
$this->controls = wp_list_sort( $this->controls, array(
'priority' => 'ASC',
'instance_number' => 'ASC',
), 'ASC', true );
foreach ( $this->controls as $id => $control ) {
if ( ! isset( $this->sections[ $control->section ] ) || ! $control->check_capabilities() ) {
continue;
}
$this->sections[ $control->section ]->controls[] = $control;
$controls[ $id ] = $control;
}
$this->controls = $controls;
// Prepare sections.
$this->sections = wp_list_sort( $this->sections, array(
'priority' => 'ASC',
'instance_number' => 'ASC',
), 'ASC', true );
$sections = array();
foreach ( $this->sections as $section ) {
if ( ! $section->check_capabilities() ) {
continue;
}
$section->controls = wp_list_sort( $section->controls, array(
'priority' => 'ASC',
'instance_number' => 'ASC',
) );
if ( ! $section->panel ) {
// Top-level section.
$sections[ $section->id ] = $section;
} else {
// This section belongs to a panel.
if ( isset( $this->panels [ $section->panel ] ) ) {
$this->panels[ $section->panel ]->sections[ $section->id ] = $section;
}
}
}
$this->sections = $sections;
// Prepare panels.
$this->panels = wp_list_sort( $this->panels, array(
'priority' => 'ASC',
'instance_number' => 'ASC',
), 'ASC', true );
$panels = array();
foreach ( $this->panels as $panel ) {
if ( ! $panel->check_capabilities() ) {
continue;
}
$panel->sections = wp_list_sort( $panel->sections, array(
'priority' => 'ASC',
'instance_number' => 'ASC',
), 'ASC', true );
$panels[ $panel->id ] = $panel;
}
$this->panels = $panels;
// Sort panels and top-level sections together.
$this->containers = array_merge( $this->panels, $this->sections );
$this->containers = wp_list_sort( $this->containers, array(
'priority' => 'ASC',
'instance_number' => 'ASC',
), 'ASC', true );
}
/**
* Enqueue scripts for customize controls.
*
* @since 3.4.0
*/
public function enqueue_control_scripts() {
foreach ( $this->controls as $control ) {
$control->enqueue();
}
}
/**
* Determine whether the user agent is iOS.
*
* @since 4.4.0
* @access public
*
* @return bool Whether the user agent is iOS.
*/
public function is_ios() {
return wp_is_mobile() && preg_match( '/iPad|iPod|iPhone/', $_SERVER['HTTP_USER_AGENT'] );
}
/**
* Get the template string for the Customizer pane document title.
*
* @since 4.4.0
* @access public
*
* @return string The template string for the document title.
*/
public function get_document_title_template() {
if ( $this->is_theme_active() ) {
/* translators: %s: document title from the preview */
$document_title_tmpl = __( 'Customize: %s' );
} else {
/* translators: %s: document title from the preview */
$document_title_tmpl = __( 'Live Preview: %s' );
}
$document_title_tmpl = html_entity_decode( $document_title_tmpl, ENT_QUOTES, 'UTF-8' ); // Because exported to JS and assigned to document.title.
return $document_title_tmpl;
}
/**
* Set the initial URL to be previewed.
*
* URL is validated.
*
* @since 4.4.0
* @access public
*
* @param string $preview_url URL to be previewed.
*/
public function set_preview_url( $preview_url ) {
$preview_url = esc_url_raw( $preview_url );
$this->preview_url = wp_validate_redirect( $preview_url, home_url( '/' ) );
}
/**
* Get the initial URL to be previewed.
*
* @since 4.4.0
* @access public
*
* @return string URL being previewed.
*/
public function get_preview_url() {
if ( empty( $this->preview_url ) ) {
$preview_url = home_url( '/' );
} else {
$preview_url = $this->preview_url;
}
return $preview_url;
}
/**
* Determines whether the admin and the frontend are on different domains.
*
* @since 4.7.0
* @access public
*
* @return bool Whether cross-domain.
*/
public function is_cross_domain() {
$admin_origin = wp_parse_url( admin_url() );
$home_origin = wp_parse_url( home_url() );
$cross_domain = ( strtolower( $admin_origin['host'] ) !== strtolower( $home_origin['host'] ) );
return $cross_domain;
}
/**
* Get URLs allowed to be previewed.
*
* If the front end and the admin are served from the same domain, load the
* preview over ssl if the Customizer is being loaded over ssl. This avoids
* insecure content warnings. This is not attempted if the admin and front end
* are on different domains to avoid the case where the front end doesn't have
* ssl certs. Domain mapping plugins can allow other urls in these conditions
* using the customize_allowed_urls filter.
*
* @since 4.7.0
* @access public
*
* @returns array Allowed URLs.
*/
public function get_allowed_urls() {
$allowed_urls = array( home_url( '/' ) );
if ( is_ssl() && ! $this->is_cross_domain() ) {
$allowed_urls[] = home_url( '/', 'https' );
}
/**
* Filters the list of URLs allowed to be clicked and followed in the Customizer preview.
*
* @since 3.4.0
*
* @param array $allowed_urls An array of allowed URLs.
*/
$allowed_urls = array_unique( apply_filters( 'customize_allowed_urls', $allowed_urls ) );
return $allowed_urls;
}
/**
* Get messenger channel.
*
* @since 4.7.0
* @access public
*
* @return string Messenger channel.
*/
public function get_messenger_channel() {
return $this->messenger_channel;
}
/**
* Set URL to link the user to when closing the Customizer.
*
* URL is validated.
*
* @since 4.4.0
* @access public
*
* @param string $return_url URL for return link.
*/
public function set_return_url( $return_url ) {
$return_url = esc_url_raw( $return_url );
$return_url = remove_query_arg( wp_removable_query_args(), $return_url );
$return_url = wp_validate_redirect( $return_url );
$this->return_url = $return_url;
}
/**
* Get URL to link the user to when closing the Customizer.
*
* @since 4.4.0
* @access public
*
* @return string URL for link to close Customizer.
*/
public function get_return_url() {
$referer = wp_get_referer();
$excluded_referer_basenames = array( 'customize.php', 'wp-login.php' );
if ( $this->return_url ) {
$return_url = $this->return_url;
} else if ( $referer && ! in_array( basename( parse_url( $referer, PHP_URL_PATH ) ), $excluded_referer_basenames, true ) ) {
$return_url = $referer;
} else if ( $this->preview_url ) {
$return_url = $this->preview_url;
} else {
$return_url = home_url( '/' );
}
return $return_url;
}
/**
* Set the autofocused constructs.
*
* @since 4.4.0
* @access public
*
* @param array $autofocus {
* Mapping of 'panel', 'section', 'control' to the ID which should be autofocused.
*
* @type string [$control] ID for control to be autofocused.
* @type string [$section] ID for section to be autofocused.
* @type string [$panel] ID for panel to be autofocused.
* }
*/
public function set_autofocus( $autofocus ) {
$this->autofocus = array_filter( wp_array_slice_assoc( $autofocus, array( 'panel', 'section', 'control' ) ), 'is_string' );
}
/**
* Get the autofocused constructs.
*
* @since 4.4.0
* @access public
*
* @return array {
* Mapping of 'panel', 'section', 'control' to the ID which should be autofocused.
*
* @type string [$control] ID for control to be autofocused.
* @type string [$section] ID for section to be autofocused.
* @type string [$panel] ID for panel to be autofocused.
* }
*/
public function get_autofocus() {
return $this->autofocus;
}
/**
* Get nonces for the Customizer.
*
* @since 4.5.0
*
* @return array Nonces.
*/
public function get_nonces() {
$nonces = array(
'save' => wp_create_nonce( 'save-customize_' . $this->get_stylesheet() ),
'preview' => wp_create_nonce( 'preview-customize_' . $this->get_stylesheet() ),
);
/**
* Filters nonces for Customizer.
*
* @since 4.2.0
*
* @param array $nonces Array of refreshed nonces for save and
* preview actions.
* @param WP_Customize_Manager $this WP_Customize_Manager instance.
*/
$nonces = apply_filters( 'customize_refresh_nonces', $nonces, $this );
return $nonces;
}
/**
* Print JavaScript settings for parent window.
*
* @since 4.4.0
*/
public function customize_pane_settings() {
$login_url = add_query_arg( array(
'interim-login' => 1,
'customize-login' => 1,
), wp_login_url() );
// Ensure dirty flags are set for modified settings.
foreach ( array_keys( $this->unsanitized_post_values() ) as $setting_id ) {
$setting = $this->get_setting( $setting_id );
if ( $setting ) {
$setting->dirty = true;
}
}
// Prepare Customizer settings to pass to JavaScript.
$settings = array(
'changeset' => array(
'uuid' => $this->changeset_uuid(),
'status' => $this->changeset_post_id() ? get_post_status( $this->changeset_post_id() ) : '',
),
'timeouts' => array(
'windowRefresh' => 250,
'changesetAutoSave' => AUTOSAVE_INTERVAL * 1000,
'keepAliveCheck' => 2500,
'reflowPaneContents' => 100,
'previewFrameSensitivity' => 2000,
),
'theme' => array(
'stylesheet' => $this->get_stylesheet(),
'active' => $this->is_theme_active(),
),
'url' => array(
'preview' => esc_url_raw( $this->get_preview_url() ),
'parent' => esc_url_raw( admin_url() ),
'activated' => esc_url_raw( home_url( '/' ) ),
'ajax' => esc_url_raw( admin_url( 'admin-ajax.php', 'relative' ) ),
'allowed' => array_map( 'esc_url_raw', $this->get_allowed_urls() ),
'isCrossDomain' => $this->is_cross_domain(),
'home' => esc_url_raw( home_url( '/' ) ),
'login' => esc_url_raw( $login_url ),
),
'browser' => array(
'mobile' => wp_is_mobile(),
'ios' => $this->is_ios(),
),
'panels' => array(),
'sections' => array(),
'nonce' => $this->get_nonces(),
'autofocus' => $this->get_autofocus(),
'documentTitleTmpl' => $this->get_document_title_template(),
'previewableDevices' => $this->get_previewable_devices(),
);
// Prepare Customize Section objects to pass to JavaScript.
foreach ( $this->sections() as $id => $section ) {
if ( $section->check_capabilities() ) {
$settings['sections'][ $id ] = $section->json();
}
}
// Prepare Customize Panel objects to pass to JavaScript.
foreach ( $this->panels() as $panel_id => $panel ) {
if ( $panel->check_capabilities() ) {
$settings['panels'][ $panel_id ] = $panel->json();
foreach ( $panel->sections as $section_id => $section ) {
if ( $section->check_capabilities() ) {
$settings['sections'][ $section_id ] = $section->json();
}
}
}
}
?>
<script type="text/javascript">
var _wpCustomizeSettings = <?php echo wp_json_encode( $settings ); ?>;
_wpCustomizeSettings.controls = {};
_wpCustomizeSettings.settings = {};
<?php
// Serialize settings one by one to improve memory usage.
echo "(function ( s ){\n";
foreach ( $this->settings() as $setting ) {
if ( $setting->check_capabilities() ) {
printf(
"s[%s] = %s;\n",
wp_json_encode( $setting->id ),
wp_json_encode( $setting->json() )
);
}
}
echo "})( _wpCustomizeSettings.settings );\n";
// Serialize controls one by one to improve memory usage.
echo "(function ( c ){\n";
foreach ( $this->controls() as $control ) {
if ( $control->check_capabilities() ) {
printf(
"c[%s] = %s;\n",
wp_json_encode( $control->id ),
wp_json_encode( $control->json() )
);
}
}
echo "})( _wpCustomizeSettings.controls );\n";
?>
</script>
<?php
}
/**
* Returns a list of devices to allow previewing.
*
* @since 4.5.0
*
* @return array List of devices with labels and default setting.
*/
public function get_previewable_devices() {
$devices = array(
'desktop' => array(
'label' => __( 'Enter desktop preview mode' ),
'default' => true,
),
'tablet' => array(
'label' => __( 'Enter tablet preview mode' ),
),
'mobile' => array(
'label' => __( 'Enter mobile preview mode' ),
),
);
/**
* Filters the available devices to allow previewing in the Customizer.
*
* @since 4.5.0
*
* @see WP_Customize_Manager::get_previewable_devices()
*
* @param array $devices List of devices with labels and default setting.
*/
$devices = apply_filters( 'customize_previewable_devices', $devices );
return $devices;
}
/**
* Register some default controls.
*
* @since 3.4.0
*/
public function register_controls() {
/* Panel, Section, and Control Types */
$this->register_panel_type( 'WP_Customize_Panel' );
$this->register_section_type( 'WP_Customize_Section' );
$this->register_section_type( 'WP_Customize_Sidebar_Section' );
$this->register_control_type( 'WP_Customize_Color_Control' );
$this->register_control_type( 'WP_Customize_Media_Control' );
$this->register_control_type( 'WP_Customize_Upload_Control' );
$this->register_control_type( 'WP_Customize_Image_Control' );
$this->register_control_type( 'WP_Customize_Background_Image_Control' );
$this->register_control_type( 'WP_Customize_Background_Position_Control' );
$this->register_control_type( 'WP_Customize_Cropped_Image_Control' );
$this->register_control_type( 'WP_Customize_Site_Icon_Control' );
$this->register_control_type( 'WP_Customize_Theme_Control' );
/* Themes */
$this->add_section( new WP_Customize_Themes_Section( $this, 'themes', array(
'title' => $this->theme()->display( 'Name' ),
'capability' => 'switch_themes',
'priority' => 0,
) ) );
// Themes Setting (unused - the theme is considerably more fundamental to the Customizer experience).
$this->add_setting( new WP_Customize_Filter_Setting( $this, 'active_theme', array(
'capability' => 'switch_themes',
) ) );
require_once( ABSPATH . 'wp-admin/includes/theme.php' );
// Theme Controls.
// Add a control for the active/original theme.
if ( ! $this->is_theme_active() ) {
$themes = wp_prepare_themes_for_js( array( wp_get_theme( $this->original_stylesheet ) ) );
$active_theme = current( $themes );
$active_theme['isActiveTheme'] = true;
$this->add_control( new WP_Customize_Theme_Control( $this, $active_theme['id'], array(
'theme' => $active_theme,
'section' => 'themes',
'settings' => 'active_theme',
) ) );
}
$themes = wp_prepare_themes_for_js();
foreach ( $themes as $theme ) {
if ( $theme['active'] || $theme['id'] === $this->original_stylesheet ) {
continue;
}
$theme_id = 'theme_' . $theme['id'];
$theme['isActiveTheme'] = false;
$this->add_control( new WP_Customize_Theme_Control( $this, $theme_id, array(
'theme' => $theme,
'section' => 'themes',
'settings' => 'active_theme',
) ) );
}
/* Site Identity */
$this->add_section( 'title_tagline', array(
'title' => __( 'Site Identity' ),
'priority' => 20,
) );
$this->add_setting( 'blogname', array(
'default' => get_option( 'blogname' ),
'type' => 'option',
'capability' => 'manage_options',
) );
$this->add_control( 'blogname', array(
'label' => __( 'Site Title' ),
'section' => 'title_tagline',
) );
$this->add_setting( 'blogdescription', array(
'default' => get_option( 'blogdescription' ),
'type' => 'option',
'capability' => 'manage_options',
) );
$this->add_control( 'blogdescription', array(
'label' => __( 'Tagline' ),
'section' => 'title_tagline',
) );
// Add a setting to hide header text if the theme doesn't support custom headers.
if ( ! current_theme_supports( 'custom-header', 'header-text' ) ) {
$this->add_setting( 'header_text', array(
'theme_supports' => array( 'custom-logo', 'header-text' ),
'default' => 1,
'sanitize_callback' => 'absint',
) );
$this->add_control( 'header_text', array(
'label' => __( 'Display Site Title and Tagline' ),
'section' => 'title_tagline',
'settings' => 'header_text',
'type' => 'checkbox',
) );
}
$this->add_setting( 'site_icon', array(
'type' => 'option',
'capability' => 'manage_options',
'transport' => 'postMessage', // Previewed with JS in the Customizer controls window.
) );
$this->add_control( new WP_Customize_Site_Icon_Control( $this, 'site_icon', array(
'label' => __( 'Site Icon' ),
'description' => sprintf(
/* translators: %s: site icon size in pixels */
__( 'The Site Icon is used as a browser and app icon for your site. Icons must be square, and at least %s pixels wide and tall.' ),
'<strong>512</strong>'
),
'section' => 'title_tagline',
'priority' => 60,
'height' => 512,
'width' => 512,
) ) );
$this->add_setting( 'custom_logo', array(
'theme_supports' => array( 'custom-logo' ),
'transport' => 'postMessage',
) );
$custom_logo_args = get_theme_support( 'custom-logo' );
$this->add_control( new WP_Customize_Cropped_Image_Control( $this, 'custom_logo', array(
'label' => __( 'Logo' ),
'section' => 'title_tagline',
'priority' => 8,
'height' => $custom_logo_args[0]['height'],
'width' => $custom_logo_args[0]['width'],
'flex_height' => $custom_logo_args[0]['flex-height'],
'flex_width' => $custom_logo_args[0]['flex-width'],
'button_labels' => array(
'select' => __( 'Select logo' ),
'change' => __( 'Change logo' ),
'remove' => __( 'Remove' ),
'default' => __( 'Default' ),
'placeholder' => __( 'No logo selected' ),
'frame_title' => __( 'Select logo' ),
'frame_button' => __( 'Choose logo' ),
),
) ) );
$this->selective_refresh->add_partial( 'custom_logo', array(
'settings' => array( 'custom_logo' ),
'selector' => '.custom-logo-link',
'render_callback' => array( $this, '_render_custom_logo_partial' ),
'container_inclusive' => true,
) );
/* Colors */
$this->add_section( 'colors', array(
'title' => __( 'Colors' ),
'priority' => 40,
) );
$this->add_setting( 'header_textcolor', array(
'theme_supports' => array( 'custom-header', 'header-text' ),
'default' => get_theme_support( 'custom-header', 'default-text-color' ),
'sanitize_callback' => array( $this, '_sanitize_header_textcolor' ),
'sanitize_js_callback' => 'maybe_hash_hex_color',
) );
// Input type: checkbox
// With custom value
$this->add_control( 'display_header_text', array(
'settings' => 'header_textcolor',
'label' => __( 'Display Site Title and Tagline' ),
'section' => 'title_tagline',
'type' => 'checkbox',
'priority' => 40,
) );
$this->add_control( new WP_Customize_Color_Control( $this, 'header_textcolor', array(
'label' => __( 'Header Text Color' ),
'section' => 'colors',
) ) );
// Input type: Color
// With sanitize_callback
$this->add_setting( 'background_color', array(
'default' => get_theme_support( 'custom-background', 'default-color' ),
'theme_supports' => 'custom-background',
'sanitize_callback' => 'sanitize_hex_color_no_hash',
'sanitize_js_callback' => 'maybe_hash_hex_color',
) );
$this->add_control( new WP_Customize_Color_Control( $this, 'background_color', array(
'label' => __( 'Background Color' ),
'section' => 'colors',
) ) );
/* Custom Header */
if ( current_theme_supports( 'custom-header', 'video' ) ) {
$title = __( 'Header Media' );
$description = '<p>' . __( 'If you add a video, the image will be used as a fallback while the video loads.' ) . '</p>';
// @todo Customizer sections should support having notifications just like controls do. See <https://core.trac.wordpress.org/ticket/38794>.
$description .= '<div class="customize-control-notifications-container header-video-not-currently-previewable" style="display: none"><ul>';
$description .= '<li class="notice notice-info">' . __( 'This theme doesn\'t support video headers on this page. Navigate to the front page or another page that supports video headers.' ) . '</li>';
$description .= '</ul></div>';
$width = absint( get_theme_support( 'custom-header', 'width' ) );
$height = absint( get_theme_support( 'custom-header', 'height' ) );
if ( $width && $height ) {
$control_description = sprintf(
/* translators: 1: .mp4, 2: header size in pixels */
__( 'Upload your video in %1$s format and minimize its file size for best results. Your theme recommends dimensions of %2$s pixels.' ),
'<code>.mp4</code>',
sprintf( '<strong>%s × %s</strong>', $width, $height )
);
} elseif ( $width ) {
$control_description = sprintf(
/* translators: 1: .mp4, 2: header width in pixels */
__( 'Upload your video in %1$s format and minimize its file size for best results. Your theme recommends a width of %2$s pixels.' ),
'<code>.mp4</code>',
sprintf( '<strong>%s</strong>', $width )
);
} else {
$control_description = sprintf(
/* translators: 1: .mp4, 2: header height in pixels */
__( 'Upload your video in %1$s format and minimize its file size for best results. Your theme recommends a height of %2$s pixels.' ),
'<code>.mp4</code>',
sprintf( '<strong>%s</strong>', $height )
);
}
} else {
$title = __( 'Header Image' );
$description = '';
$control_description = '';
}
$this->add_section( 'header_image', array(
'title' => $title,
'description' => $description,
'theme_supports' => 'custom-header',
'priority' => 60,
) );
$this->add_setting( 'header_video', array(
'theme_supports' => array( 'custom-header', 'video' ),
'transport' => 'postMessage',
'sanitize_callback' => 'absint',
'validate_callback' => array( $this, '_validate_header_video' ),
) );
$this->add_setting( 'external_header_video', array(
'theme_supports' => array( 'custom-header', 'video' ),
'transport' => 'postMessage',
'sanitize_callback' => array( $this, '_sanitize_external_header_video' ),
'validate_callback' => array( $this, '_validate_external_header_video' ),
) );
$this->add_setting( new WP_Customize_Filter_Setting( $this, 'header_image', array(
'default' => sprintf( get_theme_support( 'custom-header', 'default-image' ), get_template_directory_uri(), get_stylesheet_directory_uri() ),
'theme_supports' => 'custom-header',
) ) );
$this->add_setting( new WP_Customize_Header_Image_Setting( $this, 'header_image_data', array(
'theme_supports' => 'custom-header',
) ) );
/*
* Switch image settings to postMessage when video support is enabled since
* it entails that the_custom_header_markup() will be used, and thus selective
* refresh can be utilized.
*/
if ( current_theme_supports( 'custom-header', 'video' ) ) {
$this->get_setting( 'header_image' )->transport = 'postMessage';
$this->get_setting( 'header_image_data' )->transport = 'postMessage';
}
$this->add_control( new WP_Customize_Media_Control( $this, 'header_video', array(
'theme_supports' => array( 'custom-header', 'video' ),
'label' => __( 'Header Video' ),
'description' => $control_description,
'section' => 'header_image',
'mime_type' => 'video',
// @todo These button_labels can be removed once WP_Customize_Media_Control provides mime_type-specific labels automatically. See <https://core.trac.wordpress.org/ticket/38796>.
'button_labels' => array(
'select' => __( 'Select Video' ),
'change' => __( 'Change Video' ),
'placeholder' => __( 'No video selected' ),
'frame_title' => __( 'Select Video' ),
'frame_button' => __( 'Choose Video' ),
),
'active_callback' => 'is_header_video_active',
) ) );
$this->add_control( 'external_header_video', array(
'theme_supports' => array( 'custom-header', 'video' ),
'type' => 'url',
'description' => __( 'Or, enter a YouTube URL:' ),
'section' => 'header_image',
'active_callback' => 'is_header_video_active',
) );
$this->add_control( new WP_Customize_Header_Image_Control( $this ) );
$this->selective_refresh->add_partial( 'custom_header', array(
'selector' => '#wp-custom-header',
'render_callback' => 'the_custom_header_markup',
'settings' => array( 'header_video', 'external_header_video', 'header_image' ), // The image is used as a video fallback here.
'container_inclusive' => true,
) );
/* Custom Background */
$this->add_section( 'background_image', array(
'title' => __( 'Background Image' ),
'theme_supports' => 'custom-background',
'priority' => 80,
) );
$this->add_setting( 'background_image', array(
'default' => get_theme_support( 'custom-background', 'default-image' ),
'theme_supports' => 'custom-background',
'sanitize_callback' => array( $this, '_sanitize_background_setting' ),
) );
$this->add_setting( new WP_Customize_Background_Image_Setting( $this, 'background_image_thumb', array(
'theme_supports' => 'custom-background',
'sanitize_callback' => array( $this, '_sanitize_background_setting' ),
) ) );
$this->add_control( new WP_Customize_Background_Image_Control( $this ) );
$this->add_setting( 'background_preset', array(
'default' => get_theme_support( 'custom-background', 'default-preset' ),
'theme_supports' => 'custom-background',
'sanitize_callback' => array( $this, '_sanitize_background_setting' ),
) );
$this->add_control( 'background_preset', array(
'label' => _x( 'Preset', 'Background Preset' ),
'section' => 'background_image',
'type' => 'select',
'choices' => array(
'default' => _x( 'Default', 'Default Preset' ),
'fill' => __( 'Fill Screen' ),
'fit' => __( 'Fit to Screen' ),
'repeat' => _x( 'Repeat', 'Repeat Image' ),
'custom' => _x( 'Custom', 'Custom Preset' ),
),
) );
$this->add_setting( 'background_position_x', array(
'default' => get_theme_support( 'custom-background', 'default-position-x' ),
'theme_supports' => 'custom-background',
'sanitize_callback' => array( $this, '_sanitize_background_setting' ),
) );
$this->add_setting( 'background_position_y', array(
'default' => get_theme_support( 'custom-background', 'default-position-y' ),
'theme_supports' => 'custom-background',
'sanitize_callback' => array( $this, '_sanitize_background_setting' ),
) );
$this->add_control( new WP_Customize_Background_Position_Control( $this, 'background_position', array(
'label' => __( 'Image Position' ),
'section' => 'background_image',
'settings' => array(
'x' => 'background_position_x',
'y' => 'background_position_y',
),
) ) );
$this->add_setting( 'background_size', array(
'default' => get_theme_support( 'custom-background', 'default-size' ),
'theme_supports' => 'custom-background',
'sanitize_callback' => array( $this, '_sanitize_background_setting' ),
) );
$this->add_control( 'background_size', array(
'label' => __( 'Image Size' ),
'section' => 'background_image',
'type' => 'select',
'choices' => array(
'auto' => __( 'Original' ),
'contain' => __( 'Fit to Screen' ),
'cover' => __( 'Fill Screen' ),
),
) );
$this->add_setting( 'background_repeat', array(
'default' => get_theme_support( 'custom-background', 'default-repeat' ),
'sanitize_callback' => array( $this, '_sanitize_background_setting' ),
'theme_supports' => 'custom-background',
) );
$this->add_control( 'background_repeat', array(
'label' => __( 'Repeat Background Image' ),
'section' => 'background_image',
'type' => 'checkbox',
) );
$this->add_setting( 'background_attachment', array(
'default' => get_theme_support( 'custom-background', 'default-attachment' ),
'sanitize_callback' => array( $this, '_sanitize_background_setting' ),
'theme_supports' => 'custom-background',
) );
$this->add_control( 'background_attachment', array(
'label' => __( 'Scroll with Page' ),
'section' => 'background_image',
'type' => 'checkbox',
) );
// If the theme is using the default background callback, we can update
// the background CSS using postMessage.
if ( get_theme_support( 'custom-background', 'wp-head-callback' ) === '_custom_background_cb' ) {
foreach ( array( 'color', 'image', 'preset', 'position_x', 'position_y', 'size', 'repeat', 'attachment' ) as $prop ) {
$this->get_setting( 'background_' . $prop )->transport = 'postMessage';
}
}
/*
* Static Front Page
* See also https://core.trac.wordpress.org/ticket/19627 which introduces the the static-front-page theme_support.
* The following replicates behavior from options-reading.php.
*/
$this->add_section( 'static_front_page', array(
'title' => __( 'Static Front Page' ),
'priority' => 120,
'description' => __( 'Your theme supports a static front page.' ),
'active_callback' => array( $this, 'has_published_pages' ),
) );
$this->add_setting( 'show_on_front', array(
'default' => get_option( 'show_on_front' ),
'capability' => 'manage_options',
'type' => 'option',
) );
$this->add_control( 'show_on_front', array(
'label' => __( 'Front page displays' ),
'section' => 'static_front_page',
'type' => 'radio',
'choices' => array(
'posts' => __( 'Your latest posts' ),
'page' => __( 'A static page' ),
),
) );
$this->add_setting( 'page_on_front', array(
'type' => 'option',
'capability' => 'manage_options',
) );
$this->add_control( 'page_on_front', array(
'label' => __( 'Front page' ),
'section' => 'static_front_page',
'type' => 'dropdown-pages',
'allow_addition' => true,
) );
$this->add_setting( 'page_for_posts', array(
'type' => 'option',
'capability' => 'manage_options',
) );
$this->add_control( 'page_for_posts', array(
'label' => __( 'Posts page' ),
'section' => 'static_front_page',
'type' => 'dropdown-pages',
'allow_addition' => true,
) );
/* Custom CSS */
$this->add_section( 'custom_css', array(
'title' => __( 'Additional CSS' ),
'priority' => 200,
'description_hidden' => true,
'description' => sprintf( '%s<br /><a href="%s" class="external-link" target="_blank">%s<span class="screen-reader-text">%s</span></a>',
__( 'CSS allows you to customize the appearance and layout of your site with code. Separate CSS is saved for each of your themes. In the editing area the Tab key enters a tab character. To move below this area by pressing Tab, press the Esc key followed by the Tab key.' ),
esc_url( __( 'https://codex.wordpress.org/CSS' ) ),
__( 'Learn more about CSS' ),
/* translators: accessibility text */
__( '(opens in a new window)' )
),
) );
$custom_css_setting = new WP_Customize_Custom_CSS_Setting( $this, sprintf( 'custom_css[%s]', get_stylesheet() ), array(
'capability' => 'edit_css',
'default' => sprintf( "/*\n%s\n*/", __( "You can add your own CSS here.\n\nClick the help icon above to learn more." ) ),
) );
$this->add_setting( $custom_css_setting );
$this->add_control( 'custom_css', array(
'type' => 'textarea',
'section' => 'custom_css',
'settings' => array( 'default' => $custom_css_setting->id ),
'input_attrs' => array(
'class' => 'code', // Ensures contents displayed as LTR instead of RTL.
),
) );
}
/**
* Return whether there are published pages.
*
* Used as active callback for static front page section and controls.
*
* @since 4.7.0
*
* @returns bool Whether there are published (or to be published) pages.
*/
public function has_published_pages() {
$setting = $this->get_setting( 'nav_menus_created_posts' );
if ( $setting ) {
foreach ( $setting->value() as $post_id ) {
if ( 'page' === get_post_type( $post_id ) ) {
return true;
}
}
}
return 0 !== count( get_pages() );
}
/**
* Add settings from the POST data that were not added with code, e.g. dynamically-created settings for Widgets
*
* @since 4.2.0
* @access public
*
* @see add_dynamic_settings()
*/
public function register_dynamic_settings() {
$setting_ids = array_keys( $this->unsanitized_post_values() );
$this->add_dynamic_settings( $setting_ids );
}
/**
* Callback for validating the header_textcolor value.
*
* Accepts 'blank', and otherwise uses sanitize_hex_color_no_hash().
* Returns default text color if hex color is empty.
*
* @since 3.4.0
*
* @param string $color
* @return mixed
*/
public function _sanitize_header_textcolor( $color ) {
if ( 'blank' === $color )
return 'blank';
$color = sanitize_hex_color_no_hash( $color );
if ( empty( $color ) )
$color = get_theme_support( 'custom-header', 'default-text-color' );
return $color;
}
/**
* Callback for validating a background setting value.
*
* @since 4.7.0
*
* @param string $value Repeat value.
* @param WP_Customize_Setting $setting Setting.
* @return string|WP_Error Background value or validation error.
*/
public function _sanitize_background_setting( $value, $setting ) {
if ( 'background_repeat' === $setting->id ) {
if ( ! in_array( $value, array( 'repeat-x', 'repeat-y', 'repeat', 'no-repeat' ) ) ) {
return new WP_Error( 'invalid_value', __( 'Invalid value for background repeat.' ) );
}
} elseif ( 'background_attachment' === $setting->id ) {
if ( ! in_array( $value, array( 'fixed', 'scroll' ) ) ) {
return new WP_Error( 'invalid_value', __( 'Invalid value for background attachment.' ) );
}
} elseif ( 'background_position_x' === $setting->id ) {
if ( ! in_array( $value, array( 'left', 'center', 'right' ), true ) ) {
return new WP_Error( 'invalid_value', __( 'Invalid value for background position X.' ) );
}
} elseif ( 'background_position_y' === $setting->id ) {
if ( ! in_array( $value, array( 'top', 'center', 'bottom' ), true ) ) {
return new WP_Error( 'invalid_value', __( 'Invalid value for background position Y.' ) );
}
} elseif ( 'background_size' === $setting->id ) {
if ( ! in_array( $value, array( 'auto', 'contain', 'cover' ), true ) ) {
return new WP_Error( 'invalid_value', __( 'Invalid value for background size.' ) );
}
} elseif ( 'background_preset' === $setting->id ) {
if ( ! in_array( $value, array( 'default', 'fill', 'fit', 'repeat', 'custom' ), true ) ) {
return new WP_Error( 'invalid_value', __( 'Invalid value for background size.' ) );
}
} elseif ( 'background_image' === $setting->id || 'background_image_thumb' === $setting->id ) {
$value = empty( $value ) ? '' : esc_url_raw( $value );
} else {
return new WP_Error( 'unrecognized_setting', __( 'Unrecognized background setting.' ) );
}
return $value;
}
/**
* Export header video settings to facilitate selective refresh.
*
* @since 4.7.0
*
* @param array $response Response.
* @param WP_Customize_Selective_Refresh $selective_refresh Selective refresh component.
* @param array $partials Array of partials.
* @return array
*/
public function export_header_video_settings( $response, $selective_refresh, $partials ) {
if ( isset( $partials['custom_header'] ) ) {
$response['custom_header_settings'] = get_header_video_settings();
}
return $response;
}
/**
* Callback for validating the header_video value.
*
* Ensures that the selected video is less than 8MB and provides an error message.
*
* @since 4.7.0
*
* @param WP_Error $validity
* @param mixed $value
* @return mixed
*/
public function _validate_header_video( $validity, $value ) {
$video = get_attached_file( absint( $value ) );
if ( $video ) {
$size = filesize( $video );
if ( 8 < $size / pow( 1024, 2 ) ) { // Check whether the size is larger than 8MB.
$validity->add( 'size_too_large',
__( 'This video file is too large to use as a header video. Try a shorter video or optimize the compression settings and re-upload a file that is less than 8MB. Or, upload your video to YouTube and link it with the option below.' )
);
}
if ( '.mp4' !== substr( $video, -4 ) && '.mov' !== substr( $video, -4 ) ) { // Check for .mp4 or .mov format, which (assuming h.264 encoding) are the only cross-browser-supported formats.
$validity->add( 'invalid_file_type', sprintf(
/* translators: 1: .mp4, 2: .mov */
__( 'Only %1$s or %2$s files may be used for header video. Please convert your video file and try again, or, upload your video to YouTube and link it with the option below.' ),
'<code>.mp4</code>',
'<code>.mov</code>'
) );
}
}
return $validity;
}
/**
* Callback for validating the external_header_video value.
*
* Ensures that the provided URL is supported.
*
* @since 4.7.0
*
* @param WP_Error $validity
* @param mixed $value
* @return mixed
*/
public function _validate_external_header_video( $validity, $value ) {
$video = esc_url_raw( $value );
if ( $video ) {
if ( ! preg_match( '#^https?://(?:www\.)?(?:youtube\.com/watch|youtu\.be/)#', $video ) ) {
$validity->add( 'invalid_url', __( 'Please enter a valid YouTube URL.' ) );
}
}
return $validity;
}
/**
* Callback for sanitizing the external_header_video value.
*
* @since 4.7.1
*
* @param string $value URL.
* @return string Sanitized URL.
*/
public function _sanitize_external_header_video( $value ) {
return esc_url_raw( trim( $value ) );
}
/**
* Callback for rendering the custom logo, used in the custom_logo partial.
*
* This method exists because the partial object and context data are passed
* into a partial's render_callback so we cannot use get_custom_logo() as
* the render_callback directly since it expects a blog ID as the first
* argument. When WP no longer supports PHP 5.3, this method can be removed
* in favor of an anonymous function.
*
* @see WP_Customize_Manager::register_controls()
*
* @since 4.5.0
*
* @return string Custom logo.
*/
public function _render_custom_logo_partial() {
return get_custom_logo();
}
}
| alvintheodora/kopigenik | public/wordpress/wp-includes/class-wp-customize-manager.php | PHP | mit | 149,184 |
# encoding: utf-8
module Mongoid
module Relations
module Targets
# This class is the wrapper for all relational associations that have a
# target that can be a criteria or array of _loaded documents. This
# handles both cases or a combination of the two.
class Enumerable
include ::Enumerable
# The three main instance variables are collections of documents.
#
# @attribute [rw] _added Documents that have been appended.
# @attribute [rw] _loaded Persisted documents that have been _loaded.
# @attribute [rw] _unloaded A criteria representing persisted docs.
attr_accessor :_added, :_loaded, :_unloaded
delegate :===, :is_a?, :kind_of?, to: []
# Check if the enumerable is equal to the other object.
#
# @example Check equality.
# enumerable == []
#
# @param [ Enumerable ] other The other enumerable.
#
# @return [ true, false ] If the objects are equal.
#
# @since 2.1.0
def ==(other)
return false unless other.respond_to?(:entries)
entries == other.entries
end
# Append a document to the enumerable.
#
# @example Append the document.
# enumerable << document
#
# @param [ Document ] document The document to append.
#
# @return [ Document ] The document.
#
# @since 2.1.0
def <<(document)
_added[document.id] = document
self
end
alias :push :<<
# Clears out all the documents in this enumerable. If passed a block it
# will yield to each document that is in memory.
#
# @example Clear out the enumerable.
# enumerable.clear
#
# @example Clear out the enumerable with a block.
# enumerable.clear do |doc|
# doc.unbind
# end
#
# @return [ Array<Document> ] The cleared out _added docs.
#
# @since 2.1.0
def clear
if block_given?
in_memory { |doc| yield(doc) }
end
_loaded.clear and _added.clear
end
# Clones each document in the enumerable.
#
# @note This loads all documents into memory.
#
# @example Clone the enumerable.
# enumerable.clone
#
# @return [ Array<Document> ] An array clone of the enumerable.
#
# @since 2.1.6
def clone
collect { |doc| doc.clone }
end
# Delete the supplied document from the enumerable.
#
# @example Delete the document.
# enumerable.delete(document)
#
# @param [ Document ] document The document to delete.
#
# @return [ Document ] The deleted document.
#
# @since 2.1.0
def delete(document)
doc = (_loaded.delete(document.id) || _added.delete(document.id))
unless doc
if _unloaded && _unloaded.where(_id: document.id).exists?
yield(document) if block_given?
return document
end
end
yield(doc) if block_given?
doc
end
# Deletes every document in the enumerable for where the block returns
# true.
#
# @note This operation loads all documents from the database.
#
# @example Delete all matching documents.
# enumerable.delete_if do |doc|
# dod.id == id
# end
#
# @return [ Array<Document> ] The remaining docs.
#
# @since 2.1.0
def delete_if(&block)
load_all!
deleted = in_memory.select(&block)
deleted.each do |doc|
_loaded.delete(doc.id)
_added.delete(doc.id)
end
self
end
# Iterating over this enumerable has to handle a few different
# scenarios.
#
# If the enumerable has its criteria _loaded into memory then it yields
# to all the _loaded docs and all the _added docs.
#
# If the enumerable has not _loaded the criteria then it iterates over
# the cursor while loading the documents and then iterates over the
# _added docs.
#
# @example Iterate over the enumerable.
# enumerable.each do |doc|
# puts doc
# end
#
# @return [ true ] That the enumerable is now _loaded.
#
# @since 2.1.0
def each
if _loaded?
_loaded.each_pair do |id, doc|
yield(doc)
end
else
_unloaded.each do |doc|
document = _added.delete(doc.id) || _loaded.delete(doc.id) || doc
yield(document)
_loaded[document.id] = document
end
end
_added.each_pair do |id, doc|
yield(doc)
end
@executed = true
end
# Is the enumerable empty? Will determine if the count is zero based on
# whether or not it is _loaded.
#
# @example Is the enumerable empty?
# enumerable.empty?
#
# @return [ true, false ] If the enumerable is empty.
#
# @since 2.1.0
def empty?
if _loaded?
in_memory.count == 0
else
_unloaded.count + _added.count == 0
end
end
# Get the first document in the enumerable. Will check the persisted
# documents first. Does not load the entire enumerable.
#
# @example Get the first document.
# enumerable.first
#
# @return [ Document ] The first document found.
#
# @since 2.1.0
def first
matching_document(:first)
end
# Initialize the new enumerable either with a criteria or an array.
#
# @example Initialize the enumerable with a criteria.
# Enumberable.new(Post.where(:person_id => id))
#
# @example Initialize the enumerable with an array.
# Enumerable.new([ post ])
#
# @param [ Criteria, Array<Document> ] target The wrapped object.
#
# @since 2.1.0
def initialize(target)
if target.is_a?(Criteria)
@_added, @executed, @_loaded, @_unloaded = {}, false, {}, target
else
@_added, @executed = {}, true
@_loaded = target.inject({}) do |_target, doc|
_target[doc.id] = doc
_target
end
end
end
# Does the target include the provided document?
#
# @example Does the target include the document?
# enumerable.include?(document)
#
# @param [ Document ] doc The document to check.
#
# @return [ true, false ] If the document is in the target.
#
# @since 3.0.0
def include?(doc)
return super unless _unloaded
_unloaded.where(_id: doc.id).exists? || _added.has_key?(doc.id)
end
# Inspection will just inspect the entries for nice array-style
# printing.
#
# @example Inspect the enumerable.
# enumerable.inspect
#
# @return [ String ] The inspected enum.
#
# @since 2.1.0
def inspect
entries.inspect
end
# Return all the documents in the enumerable that have been _loaded or
# _added.
#
# @note When passed a block it yields to each document.
#
# @example Get the in memory docs.
# enumerable.in_memory
#
# @return [ Array<Document> ] The in memory docs.
#
# @since 2.1.0
def in_memory
docs = (_loaded.values + _added.values)
docs.each { |doc| yield(doc) } if block_given?
docs
end
# Get the last document in the enumerable. Will check the new
# documents first. Does not load the entire enumerable.
#
# @example Get the last document.
# enumerable.last
#
# @return [ Document ] The last document found.
#
# @since 2.1.0
def last
matching_document(:last)
end
# Loads all the documents in the enumerable from the database.
#
# @example Load all the documents.
# enumerable.load_all!
#
# @return [ true ] That the enumerable is _loaded.
#
# @since 2.1.0
alias :load_all! :entries
# Has the enumerable been _loaded? This will be true if the criteria has
# been executed or we manually load the entire thing.
#
# @example Is the enumerable _loaded?
# enumerable._loaded?
#
# @return [ true, false ] If the enumerable has been _loaded.
#
# @since 2.1.0
def _loaded?
!!@executed
end
# Reset the enumerable back to it's persisted state.
#
# @example Reset the enumerable.
# enumerable.reset
#
# @return [ false ] Always false.
#
# @since 2.1.0
def reset
_loaded.clear and _added.clear
@executed = false
end
# Does this enumerable respond to the provided method?
#
# @example Does the enumerable respond to the method?
# enumerable.respond_to?(:sum)
#
# @param [ String, Symbol ] name The name of the method.
# @param [ true, false ] include_private Whether to include private
# methods.
#
# @return [ true, false ] Whether the enumerable responds.
#
# @since 2.1.0
def respond_to?(name, include_private = false)
[].respond_to?(name, include_private) || super
end
# Gets the total size of this enumerable. This is a combination of all
# the persisted and unpersisted documents.
#
# @example Get the size.
# enumerable.size
#
# @return [ Integer ] The size of the enumerable.
#
# @since 2.1.0
def size
count = (_unloaded ? _unloaded.count : _loaded.count)
if count.zero?
count + _added.count
else
count + _added.values.count{ |d| d.new_record? }
end
end
alias :length :size
# Send #to_json to the entries.
#
# @example Get the enumerable as json.
# enumerable.to_json
#
# @param [ Hash ] options Optional parameters.
#
# @return [ String ] The entries all _loaded as a string.
#
# @since 2.2.0
def to_json(options = {})
entries.to_json(options)
end
# Send #as_json to the entries, without encoding.
#
# @example Get the enumerable as json.
# enumerable.as_json
#
# @param [ Hash ] options Optional parameters.
#
# @return [ Hash ] The entries all _loaded as a hash.
#
# @since 2.2.0
def as_json(options = {})
entries.as_json(options)
end
# Return all the unique documents in the enumerable.
#
# @note This operation loads all documents from the database.
#
# @example Get all the unique documents.
# enumerable.uniq
#
# @return [ Array<Document> ] The unique documents.
#
# @since 2.1.0
def uniq
entries.uniq
end
private
def method_missing(name, *args, &block)
entries.send(name, *args, &block)
end
def matching_document(location)
_loaded.try(:values).try(location) ||
_added[_unloaded.try(location).try(:id)] ||
_unloaded.try(location) ||
_added.values.try(location)
end
end
end
end
end
| git-mums254/mongoid | lib/mongoid/relations/targets/enumerable.rb | Ruby | mit | 12,190 |
"use strict";
var core_1 = require('@angular/core');
var collection_1 = require('../../src/facade/collection');
var lang_1 = require('../../src/facade/lang');
var modelModule = require('./model');
var FormBuilder = (function () {
function FormBuilder() {
}
/**
* Construct a new {@link ControlGroup} with the given map of configuration.
* Valid keys for the `extra` parameter map are `optionals` and `validator`.
*
* See the {@link ControlGroup} constructor for more details.
*/
FormBuilder.prototype.group = function (controlsConfig, extra) {
if (extra === void 0) { extra = null; }
var controls = this._reduceControls(controlsConfig);
var optionals = (lang_1.isPresent(extra) ? collection_1.StringMapWrapper.get(extra, "optionals") : null);
var validator = lang_1.isPresent(extra) ? collection_1.StringMapWrapper.get(extra, "validator") : null;
var asyncValidator = lang_1.isPresent(extra) ? collection_1.StringMapWrapper.get(extra, "asyncValidator") : null;
return new modelModule.ControlGroup(controls, optionals, validator, asyncValidator);
};
/**
* Construct a new {@link Control} with the given `value`,`validator`, and `asyncValidator`.
*/
FormBuilder.prototype.control = function (value, validator, asyncValidator) {
if (validator === void 0) { validator = null; }
if (asyncValidator === void 0) { asyncValidator = null; }
return new modelModule.Control(value, validator, asyncValidator);
};
/**
* Construct an array of {@link Control}s from the given `controlsConfig` array of
* configuration, with the given optional `validator` and `asyncValidator`.
*/
FormBuilder.prototype.array = function (controlsConfig, validator, asyncValidator) {
var _this = this;
if (validator === void 0) { validator = null; }
if (asyncValidator === void 0) { asyncValidator = null; }
var controls = controlsConfig.map(function (c) { return _this._createControl(c); });
return new modelModule.ControlArray(controls, validator, asyncValidator);
};
/** @internal */
FormBuilder.prototype._reduceControls = function (controlsConfig) {
var _this = this;
var controls = {};
collection_1.StringMapWrapper.forEach(controlsConfig, function (controlConfig, controlName) {
controls[controlName] = _this._createControl(controlConfig);
});
return controls;
};
/** @internal */
FormBuilder.prototype._createControl = function (controlConfig) {
if (controlConfig instanceof modelModule.Control ||
controlConfig instanceof modelModule.ControlGroup ||
controlConfig instanceof modelModule.ControlArray) {
return controlConfig;
}
else if (lang_1.isArray(controlConfig)) {
var value = controlConfig[0];
var validator = controlConfig.length > 1 ? controlConfig[1] : null;
var asyncValidator = controlConfig.length > 2 ? controlConfig[2] : null;
return this.control(value, validator, asyncValidator);
}
else {
return this.control(controlConfig);
}
};
FormBuilder.decorators = [
{ type: core_1.Injectable },
];
return FormBuilder;
}());
exports.FormBuilder = FormBuilder;
//# sourceMappingURL=form_builder.js.map | DanGeffroy/BigPics | dist/vendor/@angular/common/src/forms/form_builder.js | JavaScript | mit | 3,426 |
# encoding: utf-8
module Mongoid #:nodoc:
# This module contains the behaviour of Mongoid's clone/dup of documents.
module Copyable
extend ActiveSupport::Concern
COPYABLES = [
:@accessed,
:@attributes,
:@metadata,
:@modifications,
:@previous_modifications
]
protected
# Clone or dup the current +Document+. This will return all attributes with
# the exception of the document's id and versions, and will reset all the
# instance variables.
#
# This clone also includes embedded documents.
#
# @example Clone the document.
# document.clone
#
# @example Dup the document.
# document.dup
#
# @param [ Document ] other The document getting cloned.
#
# @return [ Document ] The new document.
def initialize_copy(other)
@attributes = other.as_document
instance_variables.each { |name| remove_instance_variable(name) }
COPYABLES.each do |name|
value = other.instance_variable_get(name)
instance_variable_set(name, value ? value.dup : nil)
end
attributes.delete("_id")
if attributes.delete("versions")
attributes["version"] = 1
end
@new_record = true
identify
end
end
end
| robotmay/mongoid | lib/mongoid/copyable.rb | Ruby | mit | 1,270 |
/*! jQuery v2.0.0 -sizzle,-wrap,-css,-ajax,-ajax/script,-ajax/jsonp,-ajax/xhr,-effects,-offset,-dimensions | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license
//@ sourceMappingURL=jquery.min.map
*/
(function(e,undefined){var t,n,r=typeof undefined,i=e.location,o=e.document,a=o.documentElement,s=e.jQuery,u=e.$,l={},c=[],f="2.0.0 -sizzle,-wrap,-css,-ajax,-ajax/script,-ajax/jsonp,-ajax/xhr,-effects,-offset,-dimensions",p=c.concat,h=c.push,d=c.slice,g=c.indexOf,m=l.toString,y=l.hasOwnProperty,v=f.trim,b=function(e,n){return new b.fn.init(e,n,t)},x=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,k=/\S+/g,w=/^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,T=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,C=/^-ms-/,N=/-([\da-z])/gi,D=function(e,t){return t.toUpperCase()},S=function(){o.removeEventListener("DOMContentLoaded",S,!1),e.removeEventListener("load",S,!1),b.ready()};b.fn=b.prototype={jquery:f,constructor:b,init:function(e,t,n){var r,i;if(!e)return this;if("string"==typeof e){if(r="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:w.exec(e),!r||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof b?t[0]:t,b.merge(this,b.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:o,!0)),T.test(r[1])&&b.isPlainObject(t))for(r in t)b.isFunction(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return i=o.getElementById(r[2]),i&&i.parentNode&&(this.length=1,this[0]=i),this.context=o,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):b.isFunction(e)?n.ready(e):(e.selector!==undefined&&(this.selector=e.selector,this.context=e.context),b.makeArray(e,this))},selector:"",length:0,toArray:function(){return d.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=b.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return b.each(this,e,t)},ready:function(e){return b.ready.promise().done(e),this},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(b.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:h,sort:[].sort,splice:[].splice},b.fn.init.prototype=b.fn,b.extend=b.fn.extend=function(){var e,t,n,r,i,o,a=arguments[0]||{},s=1,u=arguments.length,l=!1;for("boolean"==typeof a&&(l=a,a=arguments[1]||{},s=2),"object"==typeof a||b.isFunction(a)||(a={}),u===s&&(a=this,--s);u>s;s++)if(null!=(e=arguments[s]))for(t in e)n=a[t],r=e[t],a!==r&&(l&&r&&(b.isPlainObject(r)||(i=b.isArray(r)))?(i?(i=!1,o=n&&b.isArray(n)?n:[]):o=n&&b.isPlainObject(n)?n:{},a[t]=b.extend(l,o,r)):r!==undefined&&(a[t]=r));return a},b.extend({expando:"jQuery"+(f+Math.random()).replace(/\D/g,""),noConflict:function(t){return e.$===b&&(e.$=u),t&&e.jQuery===b&&(e.jQuery=s),b},isReady:!1,readyWait:1,holdReady:function(e){e?b.readyWait++:b.ready(!0)},ready:function(e){(e===!0?--b.readyWait:b.isReady)||(b.isReady=!0,e!==!0&&--b.readyWait>0||(n.resolveWith(o,[b]),b.fn.trigger&&b(o).trigger("ready").off("ready")))},isFunction:function(e){return"function"===b.type(e)},isArray:Array.isArray,isWindow:function(e){return null!=e&&e===e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?l[m.call(e)]||"object":typeof e},isPlainObject:function(e){if("object"!==b.type(e)||e.nodeType||b.isWindow(e))return!1;try{if(e.constructor&&!y.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(t){return!1}return!0},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||o;var r=T.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=b.buildFragment([e],t,i),i&&b(i).remove(),b.merge([],r.childNodes))},parseJSON:JSON.parse,parseXML:function(e){var t,n;if(!e||"string"!=typeof e)return null;try{n=new DOMParser,t=n.parseFromString(e,"text/xml")}catch(r){t=undefined}return(!t||t.getElementsByTagName("parsererror").length)&&b.error("Invalid XML: "+e),t},noop:function(){},globalEval:function(e){var t,n=eval;e=b.trim(e),e&&(1===e.indexOf("use strict")?(t=o.createElement("script"),t.text=e,o.head.appendChild(t).parentNode.removeChild(t)):n(e))},camelCase:function(e){return e.replace(C,"ms-").replace(N,D)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,a=A(e);if(n){if(a){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(a){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:function(e){return null==e?"":v.call(e)},makeArray:function(e,t){var n=t||[];return null!=e&&(A(Object(e))?b.merge(n,"string"==typeof e?[e]:e):h.call(n,e)),n},inArray:function(e,t,n){return null==t?-1:g.call(t,e,n)},merge:function(e,t){var n=t.length,r=e.length,i=0;if("number"==typeof n)for(;n>i;i++)e[r++]=t[i];else while(t[i]!==undefined)e[r++]=t[i++];return e.length=r,e},grep:function(e,t,n){var r,i=[],o=0,a=e.length;for(n=!!n;a>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,a=A(e),s=[];if(a)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(s[s.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(s[s.length]=r);return p.apply([],s)},guid:1,proxy:function(e,t){var n,r,i;return"string"==typeof t&&(n=e[t],t=e,e=n),b.isFunction(e)?(r=d.call(arguments,2),i=function(){return e.apply(t||this,r.concat(d.call(arguments)))},i.guid=e.guid=e.guid||b.guid++,i):undefined},access:function(e,t,n,r,i,o,a){var s=0,u=e.length,l=null==n;if("object"===b.type(n)){i=!0;for(s in n)b.access(e,t,s,n[s],!0,o,a)}else if(r!==undefined&&(i=!0,b.isFunction(r)||(a=!0),l&&(a?(t.call(e,r),t=null):(l=t,t=function(e,t,n){return l.call(b(e),n)})),t))for(;u>s;s++)t(e[s],n,a?r:r.call(e[s],s,t(e[s],n)));return i?e:l?t.call(e):u?t(e[0],n):o},now:Date.now,swap:function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i}}),b.ready.promise=function(t){return n||(n=b.Deferred(),"complete"===o.readyState?setTimeout(b.ready):(o.addEventListener("DOMContentLoaded",S,!1),e.addEventListener("load",S,!1))),n.promise(t)},b.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){l["[object "+t+"]"]=t.toLowerCase()});function A(e){var t=e.length,n=b.type(e);return b.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}t=b(o);var j,E=a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.msMatchesSelector,L=function(e,t){if(e===t)return j=!0,0;var n=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t);return n?1&n?e===o||b.contains(o,e)?-1:t===o||b.contains(o,t)?1:0:4&n?-1:1:e.compareDocumentPosition?-1:1};b.extend({find:function(e,t,n,r){var i,a=0;if(n=n||[],t=t||o,r)while(i=r[a++])b.find.matchesSelector(i,e)&&n.push(i);else b.merge(n,t.querySelectorAll(e));return n},unique:function(e){var t,n=[],r=0,i=0;if(j=!1,e.sort(L),j){while(t=e[r++])t===e[r]&&(i=n.push(r));while(i--)e.splice(n[i],1)}return e},text:function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i)return e.textContent;if(3===i||4===i)return e.nodeValue}else while(t=e[r++])n+=b.text(t);return n},contains:function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!n.contains(r))},isXMLDoc:function(e){return"HTML"!==(e.ownerDocument||e).documentElement.nodeName},expr:{attrHandle:{},match:{"boolean":/^(?:checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped)$/i,needsContext:/^[\x20\t\r\n\f]*[>+~]/}}}),b.extend(b.find,{matches:function(e,t){return b.find(e,null,null,t)},matchesSelector:function(e,t){return E.call(e,t)},attr:function(e,t){return e.getAttribute(t)}});var O={};function P(e){var t=O[e]={};return b.each(e.match(k)||[],function(e,n){t[n]=!0}),t}b.Callbacks=function(e){e="string"==typeof e?O[e]||P(e):b.extend({},e);var t,n,r,i,o,a,s=[],u=!e.once&&[],l=function(f){for(t=e.memory&&f,n=!0,a=i||0,i=0,o=s.length,r=!0;s&&o>a;a++)if(s[a].apply(f[0],f[1])===!1&&e.stopOnFalse){t=!1;break}r=!1,s&&(u?u.length&&l(u.shift()):t?s=[]:c.disable())},c={add:function(){if(s){var n=s.length;(function a(t){b.each(t,function(t,n){var r=b.type(n);"function"===r?e.unique&&c.has(n)||s.push(n):n&&n.length&&"string"!==r&&a(n)})})(arguments),r?o=s.length:t&&(i=n,l(t))}return this},remove:function(){return s&&b.each(arguments,function(e,t){var n;while((n=b.inArray(t,s,n))>-1)s.splice(n,1),r&&(o>=n&&o--,a>=n&&a--)}),this},has:function(e){return e?b.inArray(e,s)>-1:!(!s||!s.length)},empty:function(){return s=[],o=0,this},disable:function(){return s=u=t=undefined,this},disabled:function(){return!s},lock:function(){return u=undefined,t||c.disable(),this},locked:function(){return!u},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],!s||n&&!u||(r?u.push(t):l(t)),this},fire:function(){return c.fireWith(this,arguments),this},fired:function(){return!!n}};return c},b.extend({Deferred:function(e){var t=[["resolve","done",b.Callbacks("once memory"),"resolved"],["reject","fail",b.Callbacks("once memory"),"rejected"],["notify","progress",b.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return b.Deferred(function(n){b.each(t,function(t,o){var a=o[0],s=b.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&b.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[a+"With"](this===r?n.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?b.extend(e,r):r}},i={};return r.pipe=r.then,b.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=d.call(arguments),r=n.length,i=1!==r||e&&b.isFunction(e.promise)?r:0,o=1===i?e:b.Deferred(),a=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?d.call(arguments):r,n===s?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},s,u,l;if(r>1)for(s=Array(r),u=Array(r),l=Array(r);r>t;t++)n[t]&&b.isFunction(n[t].promise)?n[t].promise().done(a(t,l,n)).fail(o.reject).progress(a(t,u,s)):--i;return i||o.resolveWith(l,n),o.promise()}}),b.support=function(t){var n=o.createElement("input"),r=o.createDocumentFragment(),i=o.createElement("div"),a=o.createElement("select"),s=a.appendChild(o.createElement("option"));return n.type?(n.type="checkbox",t.checkOn=""!==n.value,t.optSelected=s.selected,t.reliableMarginRight=!0,t.boxSizingReliable=!0,t.pixelPosition=!1,n.checked=!0,t.noCloneChecked=n.cloneNode(!0).checked,a.disabled=!0,t.optDisabled=!s.disabled,n=o.createElement("input"),n.value="t",n.type="radio",t.radioValue="t"===n.value,n.setAttribute("checked","t"),n.setAttribute("name","t"),r.appendChild(n),t.checkClone=r.cloneNode(!0).cloneNode(!0).lastChild.checked,t.focusinBubbles="onfocusin"in e,i.style.backgroundClip="content-box",i.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===i.style.backgroundClip,b(function(){var n,r,a="padding:0;margin:0;border:0;display:block;-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box",s=o.getElementsByTagName("body")[0];s&&(n=o.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",s.appendChild(n).appendChild(i),i.innerHTML="",i.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%",b.swap(s,null!=s.style.zoom?{zoom:1}:{},function(){t.boxSizing=4===i.offsetWidth}),e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(i,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(i,null)||{width:"4px"}).width,r=i.appendChild(o.createElement("div")),r.style.cssText=i.style.cssText=a,r.style.marginRight=r.style.width="0",i.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),s.removeChild(n))}),t):t}({});var q,H,F=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,M=/([A-Z])/g;function W(){Object.defineProperty(this.cache={},0,{get:function(){return{}}}),this.expando=b.expando+Math.random()}W.uid=1,W.accepts=function(e){return e.nodeType?1===e.nodeType||9===e.nodeType:!0},W.prototype={key:function(e){if(!W.accepts(e))return 0;var t={},n=e[this.expando];if(!n){n=W.uid++;try{t[this.expando]={value:n},Object.defineProperties(e,t)}catch(r){t[this.expando]=n,b.extend(e,t)}}return this.cache[n]||(this.cache[n]={}),n},set:function(e,t,n){var r,i=this.key(e),o=this.cache[i];if("string"==typeof t)o[t]=n;else if(b.isEmptyObject(o))this.cache[i]=t;else for(r in t)o[r]=t[r]},get:function(e,t){var n=this.cache[this.key(e)];return t===undefined?n:n[t]},access:function(e,t,n){return t===undefined||t&&"string"==typeof t&&n===undefined?this.get(e,t):(this.set(e,t,n),n!==undefined?n:t)},remove:function(e,t){var n,r,i=this.key(e),o=this.cache[i];if(t===undefined)this.cache[i]={};else{b.isArray(t)?r=t.concat(t.map(b.camelCase)):t in o?r=[t]:(r=b.camelCase(t),r=r in o?[r]:r.match(k)||[]),n=r.length;while(n--)delete o[r[n]]}},hasData:function(e){return!b.isEmptyObject(this.cache[e[this.expando]]||{})},discard:function(e){delete this.cache[this.key(e)]}},q=new W,H=new W,b.extend({acceptData:W.accepts,hasData:function(e){return q.hasData(e)||H.hasData(e)},data:function(e,t,n){return q.access(e,t,n)},removeData:function(e,t){q.remove(e,t)},_data:function(e,t,n){return H.access(e,t,n)},_removeData:function(e,t){H.remove(e,t)}}),b.fn.extend({data:function(e,t){var n,r,i=this[0],o=0,a=null;if(e===undefined){if(this.length&&(a=q.get(i),1===i.nodeType&&!H.get(i,"hasDataAttrs"))){for(n=i.attributes;n.length>o;o++)r=n[o].name,0===r.indexOf("data-")&&(r=b.camelCase(r.substring(5)),$(i,r,a[r]));H.set(i,"hasDataAttrs",!0)}return a}return"object"==typeof e?this.each(function(){q.set(this,e)}):b.access(this,function(t){var n,r=b.camelCase(e);if(i&&t===undefined){if(n=q.get(i,e),n!==undefined)return n;if(n=q.get(i,r),n!==undefined)return n;if(n=$(i,r,undefined),n!==undefined)return n}else this.each(function(){var n=q.get(this,r);q.set(this,r,t),-1!==e.indexOf("-")&&n!==undefined&&q.set(this,e,t)})},null,t,arguments.length>1,null,!0)},removeData:function(e){return this.each(function(){q.remove(this,e)})}});function $(e,t,n){var r;if(n===undefined&&1===e.nodeType)if(r="data-"+t.replace(M,"-$1").toLowerCase(),n=e.getAttribute(r),"string"==typeof n){try{n="true"===n?!0:"false"===n?!1:"null"===n?null:+n+""===n?+n:F.test(n)?JSON.parse(n):n}catch(i){}q.set(e,t,n)}else n=undefined;return n}b.extend({queue:function(e,t,n){var r;return e?(t=(t||"fx")+"queue",r=H.get(e,t),n&&(!r||b.isArray(n)?r=H.access(e,t,b.makeArray(n)):r.push(n)),r||[]):undefined},dequeue:function(e,t){t=t||"fx";var n=b.queue(e,t),r=n.length,i=n.shift(),o=b._queueHooks(e,t),a=function(){b.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),o.cur=i,i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return H.get(e,n)||H.access(e,n,{empty:b.Callbacks("once memory").add(function(){H.remove(e,[t+"queue",n])})})}}),b.fn.extend({queue:function(e,t){var n=2;return"string"!=typeof e&&(t=e,e="fx",n--),n>arguments.length?b.queue(this[0],e):t===undefined?this:this.each(function(){var n=b.queue(this,e,t);b._queueHooks(this,e),"fx"===e&&"inprogress"!==n[0]&&b.dequeue(this,e)})},dequeue:function(e){return this.each(function(){b.dequeue(this,e)})},delay:function(e,t){return e=b.fx?b.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,t){var n,r=1,i=b.Deferred(),o=this,a=this.length,s=function(){--r||i.resolveWith(o,[o])};"string"!=typeof e&&(t=e,e=undefined),e=e||"fx";while(a--)n=H.get(o[a],e+"queueHooks"),n&&n.empty&&(r++,n.empty.add(s));return s(),i.promise(t)}});var _,z,B=/[\t\r\n]/g,R=/\r/g,I=/^(?:input|select|textarea|button)$/i;b.fn.extend({attr:function(e,t){return b.access(this,b.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){b.removeAttr(this,e)})},prop:function(e,t){return b.access(this,b.prop,e,t,arguments.length>1)},removeProp:function(e){return this.each(function(){delete this[b.propFix[e]||e]})},addClass:function(e){var t,n,r,i,o,a=0,s=this.length,u="string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).addClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(k)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(B," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=b.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,a=0,s=this.length,u=0===arguments.length||"string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).removeClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(k)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(B," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?b.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e,i="boolean"==typeof t;return b.isFunction(e)?this.each(function(n){b(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var o,a=0,s=b(this),u=t,l=e.match(k)||[];while(o=l[a++])u=i?u:!s.hasClass(o),s[u?"addClass":"removeClass"](o)}else(n===r||"boolean"===n)&&(this.className&&H.set(this,"__className__",this.className),this.className=this.className||e===!1?"":H.get(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(B," ").indexOf(t)>=0)return!0;return!1},val:function(e){var t,n,r,i=this[0];{if(arguments.length)return r=b.isFunction(e),this.each(function(n){var i,o=b(this);1===this.nodeType&&(i=r?e.call(this,n,o.val()):e,null==i?i="":"number"==typeof i?i+="":b.isArray(i)&&(i=b.map(i,function(e){return null==e?"":e+""})),t=b.valHooks[this.type]||b.valHooks[this.nodeName.toLowerCase()],t&&"set"in t&&t.set(this,i,"value")!==undefined||(this.value=i))});if(i)return t=b.valHooks[i.type]||b.valHooks[i.nodeName.toLowerCase()],t&&"get"in t&&(n=t.get(i,"value"))!==undefined?n:(n=i.value,"string"==typeof n?n.replace(R,""):null==n?"":n)}}}),b.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,u=0>i?s:o?i:0;for(;s>u;u++)if(n=r[u],!(!n.selected&&u!==i||(b.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&b.nodeName(n.parentNode,"optgroup"))){if(t=b(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n,r,i=e.options,o=b.makeArray(t),a=i.length;while(a--)r=i[a],(r.selected=b.inArray(b(r).val(),o)>=0)&&(n=!0);return n||(e.selectedIndex=-1),o}}},attr:function(e,t,n){var i,o,a=e.nodeType;if(e&&3!==a&&8!==a&&2!==a)return typeof e.getAttribute===r?b.prop(e,t,n):(1===a&&b.isXMLDoc(e)||(t=t.toLowerCase(),i=b.attrHooks[t]||(b.expr.match.boolean.test(t)?z:_)),n===undefined?i&&"get"in i&&null!==(o=i.get(e,t))?o:(o=b.find.attr(e,t),null==o?undefined:o):null!==n?i&&"set"in i&&(o=i.set(e,n,t))!==undefined?o:(e.setAttribute(t,n+""),n):(b.removeAttr(e,t),undefined))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(k);if(o&&1===e.nodeType)while(n=o[i++])r=b.propFix[n]||n,b.expr.match.boolean.test(n)&&(e[r]=!1),e.removeAttribute(n)},attrHooks:{type:{set:function(e,t){if(!b.support.radioValue&&"radio"===t&&b.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{"for":"htmlFor","class":"className"},prop:function(e,t,n){var r,i,o,a=e.nodeType;if(e&&3!==a&&8!==a&&2!==a)return o=1!==a||!b.isXMLDoc(e),o&&(t=b.propFix[t]||t,i=b.propHooks[t]),n!==undefined?i&&"set"in i&&(r=i.set(e,n,t))!==undefined?r:e[t]=n:i&&"get"in i&&null!==(r=i.get(e,t))?r:e[t]},propHooks:{tabIndex:{get:function(e){return e.hasAttribute("tabindex")||I.test(e.nodeName)||e.href?e.tabIndex:-1}}}}),z={set:function(e,t,n){return t===!1?b.removeAttr(e,n):e.setAttribute(n,n),n}},b.each(b.expr.match.boolean.source.match(/\w+/g),function(e,t){var n=b.expr.attrHandle[t]||b.find.attr;b.expr.attrHandle[t]=function(e,t,r){var i=b.expr.attrHandle[t],o=r?undefined:(b.expr.attrHandle[t]=undefined)!=n(e,t,r)?t.toLowerCase():null;return b.expr.attrHandle[t]=i,o}}),b.support.optSelected||(b.propHooks.selected={get:function(e){var t=e.parentNode;return t&&t.parentNode&&t.parentNode.selectedIndex,null}}),b.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){b.propFix[this.toLowerCase()]=this}),b.each(["radio","checkbox"],function(){b.valHooks[this]={set:function(e,t){return b.isArray(t)?e.checked=b.inArray(b(e).val(),t)>=0:undefined}},b.support.checkOn||(b.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var X=/^key/,U=/^(?:mouse|contextmenu)|click/,V=/^(?:focusinfocus|focusoutblur)$/,Q=/^([^.]*)(?:\.(.+)|)$/;function Y(){return!0}function K(){return!1}function J(){try{return o.activeElement}catch(e){}}b.event={global:{},add:function(e,t,n,i,o){var a,s,u,l,c,f,p,h,d,g,m,y=H.get(e);if(y){n.handler&&(a=n,n=a.handler,o=a.selector),n.guid||(n.guid=b.guid++),(l=y.events)||(l=y.events={}),(s=y.handle)||(s=y.handle=function(e){return typeof b===r||e&&b.event.triggered===e.type?undefined:b.event.dispatch.apply(s.elem,arguments)},s.elem=e),t=(t||"").match(k)||[""],c=t.length;while(c--)u=Q.exec(t[c])||[],d=m=u[1],g=(u[2]||"").split(".").sort(),d&&(p=b.event.special[d]||{},d=(o?p.delegateType:p.bindType)||d,p=b.event.special[d]||{},f=b.extend({type:d,origType:m,data:i,handler:n,guid:n.guid,selector:o,needsContext:o&&b.expr.match.needsContext.test(o),namespace:g.join(".")},a),(h=l[d])||(h=l[d]=[],h.delegateCount=0,p.setup&&p.setup.call(e,i,g,s)!==!1||e.addEventListener&&e.addEventListener(d,s,!1)),p.add&&(p.add.call(e,f),f.handler.guid||(f.handler.guid=n.guid)),o?h.splice(h.delegateCount++,0,f):h.push(f),b.event.global[d]=!0);e=null}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,f,p,h,d,g,m=H.hasData(e)&&H.get(e);if(m&&(u=m.events)){t=(t||"").match(k)||[""],l=t.length;while(l--)if(s=Q.exec(t[l])||[],h=g=s[1],d=(s[2]||"").split(".").sort(),h){f=b.event.special[h]||{},h=(r?f.delegateType:f.bindType)||h,p=u[h]||[],s=s[2]&&RegExp("(^|\\.)"+d.join("\\.(?:.*\\.|)")+"(\\.|$)"),a=o=p.length;while(o--)c=p[o],!i&&g!==c.origType||n&&n.guid!==c.guid||s&&!s.test(c.namespace)||r&&r!==c.selector&&("**"!==r||!c.selector)||(p.splice(o,1),c.selector&&p.delegateCount--,f.remove&&f.remove.call(e,c));a&&!p.length&&(f.teardown&&f.teardown.call(e,d,m.handle)!==!1||b.removeEvent(e,h,m.handle),delete u[h])}else for(h in u)b.event.remove(e,h+t[l],n,r,!0);b.isEmptyObject(u)&&(delete m.handle,H.remove(e,"events"))}},trigger:function(t,n,r,i){var a,s,u,l,c,f,p,h=[r||o],d=y.call(t,"type")?t.type:t,g=y.call(t,"namespace")?t.namespace.split("."):[];if(s=u=r=r||o,3!==r.nodeType&&8!==r.nodeType&&!V.test(d+b.event.triggered)&&(d.indexOf(".")>=0&&(g=d.split("."),d=g.shift(),g.sort()),c=0>d.indexOf(":")&&"on"+d,t=t[b.expando]?t:new b.Event(d,"object"==typeof t&&t),t.isTrigger=i?2:3,t.namespace=g.join("."),t.namespace_re=t.namespace?RegExp("(^|\\.)"+g.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,t.result=undefined,t.target||(t.target=r),n=null==n?[t]:b.makeArray(n,[t]),p=b.event.special[d]||{},i||!p.trigger||p.trigger.apply(r,n)!==!1)){if(!i&&!p.noBubble&&!b.isWindow(r)){for(l=p.delegateType||d,V.test(l+d)||(s=s.parentNode);s;s=s.parentNode)h.push(s),u=s;u===(r.ownerDocument||o)&&h.push(u.defaultView||u.parentWindow||e)}a=0;while((s=h[a++])&&!t.isPropagationStopped())t.type=a>1?l:p.bindType||d,f=(H.get(s,"events")||{})[t.type]&&H.get(s,"handle"),f&&f.apply(s,n),f=c&&s[c],f&&b.acceptData(s)&&f.apply&&f.apply(s,n)===!1&&t.preventDefault();return t.type=d,i||t.isDefaultPrevented()||p._default&&p._default.apply(h.pop(),n)!==!1||!b.acceptData(r)||c&&b.isFunction(r[d])&&!b.isWindow(r)&&(u=r[c],u&&(r[c]=null),b.event.triggered=d,r[d](),b.event.triggered=undefined,u&&(r[c]=u)),t.result}},dispatch:function(e){e=b.event.fix(e);var t,n,r,i,o,a=[],s=d.call(arguments),u=(H.get(this,"events")||{})[e.type]||[],l=b.event.special[e.type]||{};if(s[0]=e,e.delegateTarget=this,!l.preDispatch||l.preDispatch.call(this,e)!==!1){a=b.event.handlers.call(this,e,u),t=0;while((i=a[t++])&&!e.isPropagationStopped()){e.currentTarget=i.elem,n=0;while((o=i.handlers[n++])&&!e.isImmediatePropagationStopped())(!e.namespace_re||e.namespace_re.test(o.namespace))&&(e.handleObj=o,e.data=o.data,r=((b.event.special[o.origType]||{}).handle||o.handler).apply(i.elem,s),r!==undefined&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()))}return l.postDispatch&&l.postDispatch.call(this,e),e.result}},handlers:function(e,t){var n,r,i,o,a=[],s=t.delegateCount,u=e.target;if(s&&u.nodeType&&(!e.button||"click"!==e.type))for(;u!==this;u=u.parentNode||this)if(u.disabled!==!0||"click"!==e.type){for(r=[],n=0;s>n;n++)o=t[n],i=o.selector+" ",r[i]===undefined&&(r[i]=o.needsContext?b(i,this).index(u)>=0:b.find(i,this,null,[u]).length),r[i]&&r.push(o);r.length&&a.push({elem:u,handlers:r})}return t.length>s&&a.push({elem:this,handlers:t.slice(s)}),a},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,t){var n,r,i,a=t.button;return null==e.pageX&&null!=t.clientX&&(n=e.target.ownerDocument||o,r=n.documentElement,i=n.body,e.pageX=t.clientX+(r&&r.scrollLeft||i&&i.scrollLeft||0)-(r&&r.clientLeft||i&&i.clientLeft||0),e.pageY=t.clientY+(r&&r.scrollTop||i&&i.scrollTop||0)-(r&&r.clientTop||i&&i.clientTop||0)),e.which||a===undefined||(e.which=1&a?1:2&a?3:4&a?2:0),e}},fix:function(e){if(e[b.expando])return e;var t,n,r,i=e.type,o=e,a=this.fixHooks[i];a||(this.fixHooks[i]=a=U.test(i)?this.mouseHooks:X.test(i)?this.keyHooks:{}),r=a.props?this.props.concat(a.props):this.props,e=new b.Event(o),t=r.length;while(t--)n=r[t],e[n]=o[n];return 3===e.target.nodeType&&(e.target=e.target.parentNode),a.filter?a.filter(e,o):e},special:{load:{noBubble:!0},focus:{trigger:function(){return this!==J()&&this.focus?(this.focus(),!1):undefined},delegateType:"focusin"},blur:{trigger:function(){return this===J()&&this.blur?(this.blur(),!1):undefined},delegateType:"focusout"},click:{trigger:function(){return"checkbox"===this.type&&this.click&&b.nodeName(this,"input")?(this.click(),!1):undefined},_default:function(e){return b.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){e.result!==undefined&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=b.extend(new b.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?b.event.trigger(i,null,t):b.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},b.removeEvent=function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)},b.Event=function(e,t){return this instanceof b.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.getPreventDefault&&e.getPreventDefault()?Y:K):this.type=e,t&&b.extend(this,t),this.timeStamp=e&&e.timeStamp||b.now(),this[b.expando]=!0,undefined):new b.Event(e,t)},b.Event.prototype={isDefaultPrevented:K,isPropagationStopped:K,isImmediatePropagationStopped:K,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=Y,e&&e.preventDefault&&e.preventDefault()},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=Y,e&&e.stopPropagation&&e.stopPropagation()},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=Y,this.stopPropagation()}},b.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){b.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;return(!i||i!==r&&!b.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),b.support.focusinBubbles||b.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){b.event.simulate(t,e.target,b.event.fix(e),!0)};b.event.special[t]={setup:function(){0===n++&&o.addEventListener(e,r,!0)},teardown:function(){0===--n&&o.removeEventListener(e,r,!0)}}}),b.fn.extend({on:function(e,t,n,r,i){var o,a;if("object"==typeof e){"string"!=typeof t&&(n=n||t,t=undefined);for(a in e)this.on(a,t,n,e[a],i);return this}if(null==n&&null==r?(r=t,n=t=undefined):null==r&&("string"==typeof t?(r=n,n=undefined):(r=n,n=t,t=undefined)),r===!1)r=K;else if(!r)return this;return 1===i&&(o=r,r=function(e){return b().off(e),o.apply(this,arguments)},r.guid=o.guid||(o.guid=b.guid++)),this.each(function(){b.event.add(this,e,r,n,t)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,t,n){var r,i;if(e&&e.preventDefault&&e.handleObj)return r=e.handleObj,b(e.delegateTarget).off(r.namespace?r.origType+"."+r.namespace:r.origType,r.selector,r.handler),this;if("object"==typeof e){for(i in e)this.off(i,t,e[i]);return this}return(t===!1||"function"==typeof t)&&(n=t,t=undefined),n===!1&&(n=K),this.each(function(){b.event.remove(this,e,n,t)})},trigger:function(e,t){return this.each(function(){b.event.trigger(e,t,this)})},triggerHandler:function(e,t){var n=this[0];return n?b.event.trigger(e,t,n,!0):undefined}});var G=/^.[^:#\[\.,]*$/,Z=b.expr.match.needsContext,et={children:!0,contents:!0,next:!0,prev:!0};b.fn.extend({find:function(e){var t,n,r,i=this.length;if("string"!=typeof e)return t=this,this.pushStack(b(e).filter(function(){for(r=0;i>r;r++)if(b.contains(t[r],this))return!0}));for(n=[],r=0;i>r;r++)b.find(e,this[r],n);return n=this.pushStack(i>1?b.unique(n):n),n.selector=(this.selector?this.selector+" ":"")+e,n},has:function(e){var t=b(e,this),n=t.length;return this.filter(function(){var e=0;for(;n>e;e++)if(b.contains(this,t[e]))return!0})},not:function(e){return this.pushStack(nt(this,e||[],!0))},filter:function(e){return this.pushStack(nt(this,e||[],!1))},is:function(e){return!!e&&("string"==typeof e?Z.test(e)?b(e,this.context).index(this[0])>=0:b.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,o=[],a=Z.test(e)||"string"!=typeof e?b(e,t||this.context):0;for(;i>r;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(11>n.nodeType&&(a?a.index(n)>-1:1===n.nodeType&&b.find.matchesSelector(n,e))){n=o.push(n);break}return this.pushStack(o.length>1?b.unique(o):o)},index:function(e){return e?"string"==typeof e?g.call(b(e),this[0]):g.call(this,e.jquery?e[0]:e):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){var n="string"==typeof e?b(e,t):b.makeArray(e&&e.nodeType?[e]:e),r=b.merge(this.get(),n);return this.pushStack(b.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}});function tt(e,t){while((e=e[t])&&1!==e.nodeType);return e}b.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return b.dir(e,"parentNode")},parentsUntil:function(e,t,n){return b.dir(e,"parentNode",n)
},next:function(e){return tt(e,"nextSibling")},prev:function(e){return tt(e,"previousSibling")},nextAll:function(e){return b.dir(e,"nextSibling")},prevAll:function(e){return b.dir(e,"previousSibling")},nextUntil:function(e,t,n){return b.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return b.dir(e,"previousSibling",n)},siblings:function(e){return b.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return b.sibling(e.firstChild)},contents:function(e){return b.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:b.merge([],e.childNodes)}},function(e,t){b.fn[e]=function(n,r){var i=b.map(this,t,n);return"Until"!==e.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=b.filter(r,i)),this.length>1&&(et[e]||b.unique(i),"p"===e[0]&&i.reverse()),this.pushStack(i)}}),b.extend({filter:function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?b.find.matchesSelector(r,e)?[r]:[]:b.find.matches(e,b.grep(t,function(e){return 1===e.nodeType}))},dir:function(e,t,n){var r=[],i=n!==undefined;while((e=e[t])&&9!==e.nodeType)if(1===e.nodeType){if(i&&b(e).is(n))break;r.push(e)}return r},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});function nt(e,t,n){if(b.isFunction(t))return b.grep(e,function(e,r){return!!t.call(e,r,e)!==n});if(t.nodeType)return b.grep(e,function(e){return e===t!==n});if("string"==typeof t){if(G.test(t))return b.filter(t,e,n);t=b.filter(t,e)}return b.grep(e,function(e){return g.call(t,e)>=0!==n})}var rt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,it=/<([\w:]+)/,ot=/<|&#?\w+;/,at=/<(?:script|style|link)/i,st=/^(?:checkbox|radio)$/i,ut=/checked\s*(?:[^=]|=\s*.checked.)/i,lt=/^$|\/(?:java|ecma)script/i,ct=/^true\/(.*)/,ft=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,pt={option:[1,"<select multiple='multiple'>","</select>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};pt.optgroup=pt.option,pt.tbody=pt.tfoot=pt.colgroup=pt.caption=pt.col=pt.thead,pt.th=pt.td,b.fn.extend({text:function(e){return b.access(this,function(e){return e===undefined?b.text(this):this.empty().append((this[0]&&this[0].ownerDocument||o).createTextNode(e))},null,e,arguments.length)},append:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=ht(this,e);t.appendChild(e)}})},prepend:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=ht(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=e?b.filter(e,this):this,i=0;for(;null!=(n=r[i]);i++)t||1!==n.nodeType||b.cleanData(vt(n)),n.parentNode&&(t&&b.contains(n.ownerDocument,n)&&mt(vt(n,"script")),n.parentNode.removeChild(n));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++)1===e.nodeType&&(b.cleanData(vt(e,!1)),e.textContent="");return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return b.clone(this,e,t)})},html:function(e){return b.access(this,function(e){var t=this[0]||{},n=0,r=this.length;if(e===undefined&&1===t.nodeType)return t.innerHTML;if("string"==typeof e&&!at.test(e)&&!pt[(it.exec(e)||["",""])[1].toLowerCase()]){e=e.replace(rt,"<$1></$2>");try{for(;r>n;n++)t=this[n]||{},1===t.nodeType&&(b.cleanData(vt(t,!1)),t.innerHTML=e);t=0}catch(i){}}t&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=b.map(this,function(e){return[e.nextSibling,e.parentNode]}),t=0;return this.domManip(arguments,function(n){var r=e[t++],i=e[t++];i&&(b(this).remove(),i.insertBefore(n,r))},!0),t?this:this.remove()},detach:function(e){return this.remove(e,!0)},domManip:function(e,t,n){e=p.apply([],e);var r,i,o,a,s,u,l=0,c=this.length,f=this,h=c-1,d=e[0],g=b.isFunction(d);if(g||!(1>=c||"string"!=typeof d||b.support.checkClone)&&ut.test(d))return this.each(function(r){var i=f.eq(r);g&&(e[0]=d.call(this,r,i.html())),i.domManip(e,t,n)});if(c&&(r=b.buildFragment(e,this[0].ownerDocument,!1,!n&&this),i=r.firstChild,1===r.childNodes.length&&(r=i),i)){for(o=b.map(vt(r,"script"),dt),a=o.length;c>l;l++)s=r,l!==h&&(s=b.clone(s,!0,!0),a&&b.merge(o,vt(s,"script"))),t.call(this[l],s,l);if(a)for(u=o[o.length-1].ownerDocument,b.map(o,gt),l=0;a>l;l++)s=o[l],lt.test(s.type||"")&&!H.access(s,"globalEval")&&b.contains(u,s)&&(s.src?b._evalUrl(s.src):b.globalEval(s.textContent.replace(ft,"")))}return this}}),b.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){b.fn[e]=function(e){var n,r=[],i=b(e),o=i.length-1,a=0;for(;o>=a;a++)n=a===o?this:this.clone(!0),b(i[a])[t](n),h.apply(r,n.get());return this.pushStack(r)}}),b.extend({clone:function(e,t,n){var r,i,o,a,s=e.cloneNode(!0),u=b.contains(e.ownerDocument,e);if(!(b.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||b.isXMLDoc(e)))for(a=vt(s),o=vt(e),r=0,i=o.length;i>r;r++)bt(o[r],a[r]);if(t)if(n)for(o=o||vt(e),a=a||vt(s),r=0,i=o.length;i>r;r++)yt(o[r],a[r]);else yt(e,s);return a=vt(s,"script"),a.length>0&&mt(a,!u&&vt(e,"script")),s},buildFragment:function(e,t,n,r){var i,o,a,s,u,l,c=0,f=e.length,p=t.createDocumentFragment(),h=[];for(;f>c;c++)if(i=e[c],i||0===i)if("object"===b.type(i))b.merge(h,i.nodeType?[i]:i);else if(ot.test(i)){o=o||p.appendChild(t.createElement("div")),a=(it.exec(i)||["",""])[1].toLowerCase(),s=pt[a]||pt._default,o.innerHTML=s[1]+i.replace(rt,"<$1></$2>")+s[2],l=s[0];while(l--)o=o.firstChild;b.merge(h,o.childNodes),o=p.firstChild,o.textContent=""}else h.push(t.createTextNode(i));p.textContent="",c=0;while(i=h[c++])if((!r||-1===b.inArray(i,r))&&(u=b.contains(i.ownerDocument,i),o=vt(p.appendChild(i),"script"),u&&mt(o),n)){l=0;while(i=o[l++])lt.test(i.type||"")&&n.push(i)}return p},cleanData:function(e){var t,n,r,i=e.length,o=0,a=b.event.special;for(;i>o;o++){if(n=e[o],b.acceptData(n)&&(t=H.access(n)))for(r in t.events)a[r]?b.event.remove(n,r):b.removeEvent(n,r,t.handle);q.discard(n),H.discard(n)}},_evalUrl:function(e){return b.ajax({url:e,type:"GET",dataType:"text",async:!1,global:!1,success:b.globalEval})}});function ht(e,t){return b.nodeName(e,"table")&&b.nodeName(1===t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function dt(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function gt(e){var t=ct.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function mt(e,t){var n=e.length,r=0;for(;n>r;r++)H.set(e[r],"globalEval",!t||H.get(t[r],"globalEval"))}function yt(e,t){var n,r,i,o,a,s,u,l;if(1===t.nodeType){if(H.hasData(e)&&(o=H.access(e),a=b.extend({},o),l=o.events,H.set(t,a),l)){delete a.handle,a.events={};for(i in l)for(n=0,r=l[i].length;r>n;n++)b.event.add(t,i,l[i][n])}q.hasData(e)&&(s=q.access(e),u=b.extend({},s),q.set(t,u))}}function vt(e,t){var n=e.getElementsByTagName?e.getElementsByTagName(t||"*"):e.querySelectorAll?e.querySelectorAll(t||"*"):[];return t===undefined||t&&b.nodeName(e,t)?b.merge([e],n):n}function bt(e,t){var n=t.nodeName.toLowerCase();"input"===n&&st.test(e.type)?t.checked=e.checked:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}var xt=/%20/g,kt=/\[\]$/,wt=/\r?\n/g,Tt=/^(?:submit|button|image|reset|file)$/i,Ct=/^(?:input|select|textarea|keygen)/i;b.fn.extend({serialize:function(){return b.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=b.prop(this,"elements");return e?b.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!b(this).is(":disabled")&&Ct.test(this.nodeName)&&!Tt.test(e)&&(this.checked||!st.test(e))}).map(function(e,t){var n=b(this).val();return null==n?null:b.isArray(n)?b.map(n,function(e){return{name:t.name,value:e.replace(wt,"\r\n")}}):{name:t.name,value:n.replace(wt,"\r\n")}}).get()}}),b.param=function(e,t){var n,r=[],i=function(e,t){t=b.isFunction(t)?t():null==t?"":t,r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(t===undefined&&(t=b.ajaxSettings&&b.ajaxSettings.traditional),b.isArray(e)||e.jquery&&!b.isPlainObject(e))b.each(e,function(){i(this.name,this.value)});else for(n in e)Nt(n,e[n],t,i);return r.join("&").replace(xt,"+")};function Nt(e,t,n,r){var i;if(b.isArray(t))b.each(t,function(t,i){n||kt.test(e)?r(e,i):Nt(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==b.type(t))r(e,t);else for(i in t)Nt(e+"["+i+"]",t[i],n,r)}b.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){b.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),b.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)}}),b.fn.size=function(){return this.length},b.fn.andSelf=b.fn.addBack,"object"==typeof module&&"object"==typeof module.exports?module.exports=b:"function"==typeof define&&define.amd&&define("jquery",[],function(){return b}),"object"==typeof e&&"object"==typeof e.document&&(e.jQuery=e.$=b)})(window); | michaelBenin/jquery-builder | dist/2.0.0/jquery-ajax-css-dimensions-effects-sizzle-wrap.min.js | JavaScript | mit | 41,923 |
/*
* This file is part of the Micro Python project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2013, 2014 Damien P. George
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <stdio.h>
#include "py/obj.h"
STATIC const char *help_text =
"Welcome to Micro Python!\n"
"\n"
"For online help please visit http://micropython.org/help/.\n"
"\n"
"Quick overview of commands for the board:\n"
" pyb.info() -- print some general information\n"
" pyb.gc() -- run the garbage collector\n"
" pyb.delay(n) -- wait for n milliseconds\n"
" pyb.Switch() -- create a switch object\n"
" Switch methods: (), callback(f)\n"
" pyb.LED(n) -- create an LED object for LED n (n=1,2,3,4)\n"
" LED methods: on(), off(), toggle(), intensity(<n>)\n"
" pyb.Pin(pin) -- get a pin, eg pyb.Pin('X1')\n"
" pyb.Pin(pin, m, [p]) -- get a pin and configure it for IO mode m, pull mode p\n"
" Pin methods: init(..), value([v]), high(), low()\n"
" pyb.ExtInt(pin, m, p, callback) -- create an external interrupt object\n"
" pyb.ADC(pin) -- make an analog object from a pin\n"
" ADC methods: read(), read_timed(buf, freq)\n"
" pyb.DAC(port) -- make a DAC object\n"
" DAC methods: triangle(freq), write(n), write_timed(buf, freq)\n"
" pyb.RTC() -- make an RTC object; methods: datetime([val])\n"
" pyb.rng() -- get a 30-bit hardware random number\n"
" pyb.Servo(n) -- create Servo object for servo n (n=1,2,3,4)\n"
" Servo methods: calibration(..), angle([x, [t]]), speed([x, [t]])\n"
" pyb.Accel() -- create an Accelerometer object\n"
" Accelerometer methods: x(), y(), z(), tilt(), filtered_xyz()\n"
"\n"
"Pins are numbered X1-X12, X17-X22, Y1-Y12, or by their MCU name\n"
"Pin IO modes are: pyb.Pin.IN, pyb.Pin.OUT_PP, pyb.Pin.OUT_OD\n"
"Pin pull modes are: pyb.Pin.PULL_NONE, pyb.Pin.PULL_UP, pyb.Pin.PULL_DOWN\n"
"Additional serial bus objects: pyb.I2C(n), pyb.SPI(n), pyb.UART(n)\n"
"\n"
"Control commands:\n"
" CTRL-A -- on a blank line, enter raw REPL mode\n"
" CTRL-B -- on a blank line, enter normal REPL mode\n"
" CTRL-C -- interrupt a running program\n"
" CTRL-D -- on a blank line, do a soft reset of the board\n"
"\n"
"For further help on a specific object, type help(obj)\n"
;
STATIC void pyb_help_print_info_about_object(mp_obj_t name_o, mp_obj_t value) {
printf(" ");
mp_obj_print(name_o, PRINT_STR);
printf(" -- ");
mp_obj_print(value, PRINT_STR);
printf("\n");
}
STATIC mp_obj_t pyb_help(uint n_args, const mp_obj_t *args) {
if (n_args == 0) {
// print a general help message
printf("%s", help_text);
} else {
// try to print something sensible about the given object
printf("object ");
mp_obj_print(args[0], PRINT_STR);
printf(" is of type %s\n", mp_obj_get_type_str(args[0]));
mp_map_t *map = NULL;
if (MP_OBJ_IS_TYPE(args[0], &mp_type_module)) {
map = mp_obj_dict_get_map(mp_obj_module_get_globals(args[0]));
} else {
mp_obj_type_t *type;
if (MP_OBJ_IS_TYPE(args[0], &mp_type_type)) {
type = args[0];
} else {
type = mp_obj_get_type(args[0]);
}
if (type->locals_dict != MP_OBJ_NULL && MP_OBJ_IS_TYPE(type->locals_dict, &mp_type_dict)) {
map = mp_obj_dict_get_map(type->locals_dict);
}
}
if (map != NULL) {
for (uint i = 0; i < map->alloc; i++) {
if (map->table[i].key != MP_OBJ_NULL) {
pyb_help_print_info_about_object(map->table[i].key, map->table[i].value);
}
}
}
}
return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_builtin_help_obj, 0, 1, pyb_help);
| vriera/micropython | teensy/help.c | C | mit | 4,962 |
describe('TextEditor', function () {
var id = 'testContainer';
beforeEach(function () {
this.$container = $('<div id="' + id + '" style="width: 300px; height: 200px; overflow: hidden;"></div>').appendTo('body');
});
afterEach(function () {
if (this.$container) {
destroy();
this.$container.remove();
}
});
it('should begin editing when enterBeginsEditing equals true', function () {
handsontable({
enterBeginsEditing: true,
editor: 'text'
});
selectCell(2, 2);
keyDown('enter');
var selection = getSelected();
expect(selection).toEqual([2, 2, 2, 2]);
expect(isEditorVisible()).toEqual(true);
});
it('should move down after editing', function () {
handsontable({
editor: 'text'
});
selectCell(2, 2);
keyDown('enter');
keyDown('enter');
var selection = getSelected();
expect(selection).toEqual([3, 2, 3, 2]);
});
it('should move down when enterBeginsEditing equals false', function () {
handsontable({
enterBeginsEditing: false
});
selectCell(2, 2);
keyDown('enter');
var selection = getSelected();
expect(selection).toEqual([3, 2, 3, 2]);
expect(isEditorVisible()).toEqual(false);
});
it('should render string in textarea', function () {
handsontable();
setDataAtCell(2, 2, "string");
selectCell(2, 2);
keyDown('enter');
expect(keyProxy().val()).toEqual("string");
});
it('should render textarea editor in specified size at cell 0, 0 without headers', function () {
var hot = handsontable(),
editorHeight;
selectCell(0, 0);
keyDown('enter');
setTimeout(function () {
editorHeight = hot.getActiveEditor().TEXTAREA.style.height;
}, 200);
waitsFor(function () {
return editorHeight;
}, 'Retrieve editor height', 1000);
runs(function () {
expect(hot.getActiveEditor().TEXTAREA.style.height).toBe('23px');
expect(hot.getActiveEditor().TEXTAREA.style.width).toBe('40px');
});
});
it('should render textarea editor in specified size at cell 0, 0 with headers', function () {
var hot = handsontable({
rowHeaders: true,
colHeaders: true
}),
editorHeight;
selectCell(0, 0);
keyDown('enter');
setTimeout(function () {
editorHeight = hot.getActiveEditor().TEXTAREA.style.height;
}, 200);
waitsFor(function () {
return editorHeight;
}, 'Retrieve editor height', 1000);
runs(function () {
expect(hot.getActiveEditor().TEXTAREA.style.height).toBe('23px');
expect(hot.getActiveEditor().TEXTAREA.style.width).toBe('40px');
});
});
it('should hide whole editor when it is higher then header', function () {
var hot = handsontable({
data: Handsontable.helper.createSpreadsheetData(50, 50),
rowHeaders: true,
colHeaders: true
}),
editorHeight;
setDataAtCell(2, 2, "string\nstring\nstring");
selectCell(2, 2);
keyDown('enter');
keyUp('enter');
setTimeout(function () {
editorHeight = hot.getActiveEditor().TEXTAREA.style.height;
}, 200);
waitsFor(function () {
return editorHeight;
}, 'Retrieve editor height', 1000);
var mainHolder = hot.view.wt.wtTable.holder;
mainHolder.scrollTop = 150;
mainHolder.scrollLeft = 150;
runs(function () {
expect(hot.getActiveEditor().textareaParentStyle.top).toBe('-78px');
expect(hot.getActiveEditor().textareaParentStyle.left).toBe('-1px');
});
});
it('should hide editor when quick navigation by click scrollbar was triggered', function () {
var hot = handsontable({
data: Handsontable.helper.createSpreadsheetData(50, 50),
rowHeaders: true,
colHeaders: true
}),
editorHeight;
setDataAtCell(2, 2, "string\nstring\nstring");
selectCell(2, 2);
keyDown('enter');
keyUp('enter');
setTimeout(function () {
editorHeight = hot.getActiveEditor().TEXTAREA.style.height;
}, 200);
waitsFor(function () {
return editorHeight;
}, 'Retrieve editor height', 1000);
var mainHolder = hot.view.wt.wtTable.holder;
mainHolder.scrollTop = 1000;
runs(function () {
expect(hot.getActiveEditor().textareaParentStyle.top).toBe('72px');
expect(hot.getActiveEditor().textareaParentStyle.left).toBe('149px');
});
});
it('should render textarea editor in specified height (single line)', function () {
var hot = handsontable(),
editorHeight;
setDataAtCell(2, 2, "first line");
selectCell(2, 2);
keyDown('enter');
setTimeout(function () {
editorHeight = hot.getActiveEditor().TEXTAREA.style.height;
}, 200);
waitsFor(function () {
return editorHeight;
}, 'Retrieve editor height', 1000);
runs(function () {
expect(hot.getActiveEditor().TEXTAREA.style.height).toBe('23px');
});
});
it('should render textarea editor in specified height (multi line)', function () {
var hot = handsontable(),
editorHeight;
setDataAtCell(2, 2, "first line\n second line\n third line...");
selectCell(2, 2);
keyDown('enter');
setTimeout(function () {
editorHeight = hot.getActiveEditor().TEXTAREA.style.height;
}, 200);
waitsFor(function () {
return editorHeight;
}, 'Retrieve editor height', 1000);
runs(function () {
expect(hot.getActiveEditor().TEXTAREA.style.height).toBe('64px');
});
});
it('should render number in textarea', function () {
handsontable();
setDataAtCell(2, 2, 13);
selectCell(2, 2);
keyDown('enter');
expect(keyProxy().val()).toEqual("13");
});
it('should render boolean true in textarea', function () {
handsontable();
setDataAtCell(2, 2, true);
selectCell(2, 2);
keyDown('enter');
expect(keyProxy().val()).toEqual("true");
});
it('should render boolean false in textarea', function () {
handsontable();
setDataAtCell(2, 2, false);
selectCell(2, 2);
keyDown('enter');
expect(keyProxy().val()).toEqual("false");
});
it('should render null in textarea', function () {
handsontable();
setDataAtCell(2, 2, null);
selectCell(2, 2);
keyDown('enter');
expect(keyProxy().val()).toEqual("");
});
it('should render undefined in textarea', function () {
handsontable();
setDataAtCell(2, 2, void 0);
selectCell(2, 2);
keyDown('enter');
expect(keyProxy().val()).toEqual("");
});
it('should open editor after hitting F2', function () {
handsontable();
selectCell(2, 2);
var editor = $('.handsontableInput');
expect(isEditorVisible()).toEqual(false);
keyDown('f2');
expect(isEditorVisible()).toEqual(true);
});
it('should close editor after hitting ESC', function () {
handsontable();
selectCell(2, 2);
var editor = $('.handsontableInput');
expect(isEditorVisible()).toEqual(false);
keyDown('f2');
expect(isEditorVisible()).toEqual(true);
keyDown('esc');
expect(isEditorVisible()).toEqual(false);
});
it('should NOT open editor after hitting CapsLock', function () {
handsontable();
selectCell(2, 2);
var editor = $('.handsontableInput');
expect(isEditorVisible()).toEqual(false);
keyDown(Handsontable.helper.KEY_CODES.CAPS_LOCK);
expect(isEditorVisible()).toEqual(false);
});
it('should open editor after cancelling edit and beginning it again', function () {
handsontable();
selectCell(2, 2);
expect(isEditorVisible()).toEqual(false);
keyDown('f2');
expect(isEditorVisible()).toEqual(true);
keyDown('esc');
expect(isEditorVisible()).toEqual(false);
keyDown('f2');
expect(isEditorVisible()).toEqual(true);
});
it('loadData should not destroy editor', function () {
handsontable();
selectCell(2, 2);
keyDown('f2');
loadData(getData());
expect(isEditorVisible()).toEqual(true);
});
it('updateSettings should not destroy editor', function () {
handsontable();
selectCell(2, 2);
keyDown('f2');
updateSettings({data: getData()});
expect(isEditorVisible()).toEqual(true);
});
it('textarea should have cell dimensions (after render)', function () {
var data = [
["a", "b"],
["c", "d"]
];
var hot = handsontable({
data: data,
minRows: 4,
minCols: 4,
minSpareRows: 4,
minSpareCols: 4,
enterMoves: false
});
selectCell(1, 1);
var $td = getHtCore().find('tbody tr:eq(1) td:eq(1)');
var editor = hot.getActiveEditor();
keyDownUp('enter');
expect(keyProxy().width()).toEqual($td.width());
keyDownUp('enter');
data[1][1] = "dddddddddddddddddddd";
render();
keyDownUp('enter');
expect(keyProxy().width()).toEqual($td.width());
});
it('global shortcuts (like CTRL+A) should be blocked when cell is being edited', function () {
handsontable();
selectCell(2, 2);
keyDownUp('enter');
keyDown(65, {ctrlKey: true}); //CTRL+A should NOT select all table when cell is edited
var selection = getSelected();
expect(selection).toEqual([2, 2, 2, 2]);
expect(isEditorVisible()).toEqual(true);
});
it('should open editor after double clicking on a cell', function () {
var hot = handsontable({
data: Handsontable.helper.createSpreadsheetData(5, 2)
});
var cell = $(getCell(0, 0));
var clicks = 0;
window.scrollTo(0, cell.offset().top);
setTimeout(function () {
mouseDown(cell);
mouseUp(cell);
clicks++;
}, 0);
setTimeout(function () {
mouseDown(cell);
mouseUp(cell);
clicks++;
}, 100);
waitsFor(function () {
return clicks == 2;
}, 'Two clicks', 1000);
runs(function () {
var editor = hot.getActiveEditor();
expect(editor.isOpened()).toBe(true);
expect(editor.isInFullEditMode()).toBe(true);
});
});
it('should call editor focus() method after opening an editor', function () {
var hot = handsontable();
selectCell(2, 2);
var editor = hot.getActiveEditor();
spyOn(editor, 'focus');
expect(editor.isOpened()).toEqual(false);
expect(editor.focus).not.toHaveBeenCalled();
keyDown('f2');
expect(editor.isOpened()).toEqual(true);
expect(editor.focus).toHaveBeenCalled();
});
it('editor size should not exceed the viewport after text edit', function () {
handsontable({
data: Handsontable.helper.createSpreadsheetData(10, 5),
width: 200,
height: 200
});
selectCell(2, 2);
keyDown('enter');
expect(isEditorVisible()).toEqual(true);
document.activeElement.value = 'Very very very very very very very very very very very very very very very very very long text';
keyDownUp(32); //space - trigger textarea resize
var $textarea = $(document.activeElement);
var $wtHider = this.$container.find('.wtHider');
expect($textarea.offset().left + $textarea.outerWidth()).not.toBeGreaterThan($wtHider.offset().left + this.$container.outerWidth());
expect($textarea.offset().top + $textarea.outerHeight()).not.toBeGreaterThan($wtHider.offset().top + $wtHider.outerHeight());
});
it("should open editor after selecting cell in another table and hitting enter", function () {
this.$container2 = $('<div id="' + id + '-2"></div>').appendTo('body');
var hot1 = handsontable();
var hot2 = handsontable2.call(this);
this.$container.find('tbody tr:eq(0) td:eq(0)').simulate('mousedown');
this.$container.find('tbody tr:eq(0) td:eq(0)').simulate('mouseup');
//Open editor in HOT1
keyDown('enter');
var editor = $('.handsontableInputHolder');
expect(editor.is(':visible')).toBe(true);
//Close editor in HOT1
keyDown('enter');
expect(editor.is(':visible')).toBe(false);
this.$container2.find('tbody tr:eq(0) td:eq(0)').simulate('mousedown');
this.$container2.find('tbody tr:eq(0) td:eq(0)').simulate('mouseup');
expect(hot1.getSelected()).toBeUndefined();
expect(hot2.getSelected()).toEqual([0, 0, 0, 0]);
//Open editor in HOT2
keyDown('enter');
editor = $('.handsontableInputHolder');
expect(editor.is(':visible')).toBe(true);
this.$container2.handsontable('destroy');
this.$container2.remove();
function handsontable2(options) {
var container = this.$container2;
container.handsontable(options);
container[0].focus(); //otherwise TextEditor tests do not pass in IE8
return container.data('handsontable');
}
});
it("should open editor after pressing a printable character", function () {
var hot = handsontable({
data: Handsontable.helper.createSpreadsheetData(3, 3)
});
selectCell(0, 0);
var editorHolder = $('.handsontableInputHolder');
// var editorInput = editorHolder.find('.handsontableInput');
expect(editorHolder.is(':visible')).toBe(false);
// var keyboardEvent = $.Event('keydown', {
// keyCode: 'a'.charCodeAt(0)
// });
// this.$container.trigger(keyboardEvent);
this.$container.simulate('keydown', {keyCode: 'a'.charCodeAt(0)});
expect(editorHolder.is(':visible')).toBe(true);
});
it("should open editor after pressing a printable character with shift key", function () {
var hot = handsontable({
data: Handsontable.helper.createSpreadsheetData(3, 3)
});
selectCell(0, 0);
var editorHolder = $('.handsontableInputHolder');
// var editorInput = editorHolder.find('.handsontableInput');
expect(editorHolder.is(':visible')).toBe(false);
/**
* To reliably mimic SHIFT+SOME_KEY combination we have to trigger two events.
* First we need to trigger keydown event with SHIFT keyCode (16)
* and then trigger a keydown event with keyCode of SOME_KEY and shiftKey property set to true
*/
// var shiftKeyboardEvent = $.Event('keydown', {
// keyCode: 16, //shift
// shiftKey: true
// });
//
// var keyboardEvent = $.Event('keydown', {
// keyCode: 'a'.charCodeAt(0),
// shiftKey: true
// });
this.$container.simulate('keydown',
{
keyCode: 'a'.charCodeAt(0),
shiftKey: true
});
// this.$container.trigger(shiftKeyboardEvent);
// this.$container.trigger(keyboardEvent);
expect(editorHolder.is(':visible')).toBe(true);
});
it("should be able to open editor after clearing cell data with DELETE", function () {
var hot = handsontable({
data: Handsontable.helper.createSpreadsheetData(3, 3)
});
selectCell(0, 0);
var editorHolder = $('.handsontableInputHolder');
expect(editorHolder.is(':visible')).toBe(false);
this.$container.simulate('keydown',{
keyCode: 46
});
this.$container.simulate('keydown',{
keyCode: 'a'.charCodeAt(0)
});
expect(editorHolder.is(':visible')).toBe(true);
});
it("should be able to open editor after clearing cell data with BACKSPACE", function () {
var hot = handsontable({
data: Handsontable.helper.createSpreadsheetData(3, 3)
});
selectCell(0, 0);
var editorHolder = $('.handsontableInputHolder');
expect(editorHolder.is(':visible')).toBe(false);
this.$container.simulate('keydown', {
keyCode: 8 //backspace
});
this.$container.simulate('keydown', {
keyCode: 'a'.charCodeAt(0)
});
expect(editorHolder.is(':visible')).toBe(true);
});
it("should scroll editor to a cell, if trying to edit cell that is outside of the viewport", function () {
var hot = handsontable({
data: Handsontable.helper.createSpreadsheetData(20, 20),
width: 100,
height: 50
});
selectCell(0, 0);
expect(getCell(0, 0)).not.toBeNull();
expect(getCell(19, 19)).toBeNull();
hot.view.scrollViewport(new WalkontableCellCoords(19, 19));
hot.render();
expect(getCell(0, 0)).toBeNull();
expect(getCell(19, 19)).not.toBeNull();
keyDown('enter');
expect(getCell(0, 0)).not.toBeNull();
expect(getCell(19, 19)).toBeNull();
});
it("should open empty editor after clearing cell value width BACKSPACE", function () {
var hot = handsontable({
data: Handsontable.helper.createSpreadsheetData(4, 4)
});
expect(getDataAtCell(0, 0)).toEqual('A1');
selectCell(0, 0);
keyDown(Handsontable.helper.KEY_CODES.BACKSPACE);
expect(getDataAtCell(0, 0)).toEqual('');
expect(hot.getActiveEditor().isOpened()).toBe(false);
keyDown(Handsontable.helper.KEY_CODES.ENTER);
expect(hot.getActiveEditor().isOpened()).toBe(true);
expect(hot.getActiveEditor().getValue()).toEqual('');
});
it("should open empty editor after clearing cell value width DELETE", function () {
var hot = handsontable({
data: Handsontable.helper.createSpreadsheetData(4, 4)
});
expect(getDataAtCell(0, 0)).toEqual('A1');
selectCell(0, 0);
keyDown(Handsontable.helper.KEY_CODES.DELETE);
expect(getDataAtCell(0, 0)).toEqual('');
expect(hot.getActiveEditor().isOpened()).toBe(false);
keyDown(Handsontable.helper.KEY_CODES.ENTER);
expect(hot.getActiveEditor().isOpened()).toBe(true);
expect(hot.getActiveEditor().getValue()).toEqual('');
});
it("should not open editor after hitting ALT (#1239)", function () {
var hot = handsontable({
data: Handsontable.helper.createSpreadsheetData(4, 4)
});
expect(getDataAtCell(0, 0)).toEqual('A1');
selectCell(0, 0);
keyDown(Handsontable.helper.KEY_CODES.ALT);
expect(hot.getActiveEditor().isOpened()).toBe(false);
});
it("should open editor at the same coordinates as the edited cell", function() {
var hot = handsontable({
data: Handsontable.helper.createSpreadsheetData(16, 8),
fixedColumnsLeft: 2,
fixedRowsTop: 2
});
var mainHolder = hot.view.wt.wtTable.holder;
// corner
selectCell(1, 1);
keyDown(Handsontable.helper.KEY_CODES.ENTER);
var $inputHolder = $('.handsontableInputHolder');
expect($(getCell(1,1)).offset().left).toEqual($inputHolder.offset().left + 1);
expect($(getCell(1,1)).offset().top).toEqual($inputHolder.offset().top + 1);
// top
selectCell(1, 4);
keyDown(Handsontable.helper.KEY_CODES.ENTER);
expect($(getCell(1,4)).offset().left).toEqual($inputHolder.offset().left + 1);
expect($(getCell(1,4)).offset().top).toEqual($inputHolder.offset().top + 1);
// left
selectCell(4, 1);
keyDown(Handsontable.helper.KEY_CODES.ENTER);
expect($(getCell(4,1)).offset().left).toEqual($inputHolder.offset().left + 1);
expect($(getCell(4,1)).offset().top).toEqual($inputHolder.offset().top + 1);
// non-fixed
selectCell(4, 4);
keyDown(Handsontable.helper.KEY_CODES.ENTER);
expect($(getCell(4,4)).offset().left).toEqual($inputHolder.offset().left + 1);
expect($(getCell(4,4)).offset().top).toEqual($inputHolder.offset().top + 1);
$(mainHolder).scrollTop(1000);
});
it("should open editor at the same coordinates as the edited cell after the table had been scrolled (corner)", function() {
var hot = handsontable({
data: Handsontable.helper.createSpreadsheetData(16, 8),
fixedColumnsLeft: 2,
fixedRowsTop: 2
});
var $holder = $(hot.view.wt.wtTable.holder);
$holder.scrollTop(100);
$holder.scrollLeft(100);
hot.render();
// corner
selectCell(1, 1);
var currentCell = hot.getCell(1, 1, true);
var left = $(currentCell).offset().left;
var top = $(currentCell).offset().top;
var $inputHolder = $('.handsontableInputHolder');
keyDown(Handsontable.helper.KEY_CODES.ENTER);
expect(left).toEqual($inputHolder.offset().left + 1);
expect(top).toEqual($inputHolder.offset().top + 1);
});
it("should open editor at the same coordinates as the edited cell after the table had been scrolled (top)", function() {
var hot = handsontable({
data: Handsontable.helper.createSpreadsheetData(50, 50),
fixedColumnsLeft: 2,
fixedRowsTop: 2
});
var $holder = $(hot.view.wt.wtTable.holder);
$holder[0].scrollTop = 500;
waits(100);
runs(function () {
$holder[0].scrollLeft = 500;
});
waits(100);
runs(function () {
// top
selectCell(1, 6);
});
waits(100);
runs(function () {
var currentCell = hot.getCell(1, 6, true);
var left = $(currentCell).offset().left;
var top = $(currentCell).offset().top;
var $inputHolder = $('.handsontableInputHolder');
keyDown(Handsontable.helper.KEY_CODES.ENTER);
expect(left).toEqual($inputHolder.offset().left + 1);
expect(top).toEqual($inputHolder.offset().top + 1);
});
});
it("should open editor at the same coordinates as the edited cell after the table had been scrolled (left)", function() {
var hot = handsontable({
data: Handsontable.helper.createSpreadsheetData(50, 50),
fixedColumnsLeft: 2,
fixedRowsTop: 2
});
var $holder = $(hot.view.wt.wtTable.holder);
$holder.scrollTop(500);
$holder.scrollLeft(500);
hot.render();
// left
selectCell(6, 1);
var currentCell = hot.getCell(6, 1, true);
var left = $(currentCell).offset().left;
var top = $(currentCell).offset().top;
var $inputHolder = $('.handsontableInputHolder');
keyDown(Handsontable.helper.KEY_CODES.ENTER);
expect(left).toEqual($inputHolder.offset().left + 1);
expect(top).toEqual($inputHolder.offset().top + 1);
});
it("should open editor at the same coordinates as the edited cell after the table had been scrolled (non-fixed)", function() {
var hot = handsontable({
data: Handsontable.helper.createSpreadsheetData(50, 50),
fixedColumnsLeft: 2,
fixedRowsTop: 2
});
var $holder = $(hot.view.wt.wtTable.holder);
$holder.scrollTop(500);
$holder.scrollLeft(500);
hot.render();
// non-fixed
selectCell(7, 7);
var currentCell = hot.getCell(7, 7, true);
var left = $(currentCell).offset().left;
var top = $(currentCell).offset().top;
var $inputHolder = $('.handsontableInputHolder');
keyDown(Handsontable.helper.KEY_CODES.ENTER);
expect(left).toEqual($inputHolder.offset().left + 1);
expect(top).toEqual($inputHolder.offset().top + 1);
});
it("should display editor with the proper size, when the edited column is beyond the tables container", function() {
this.$container.css('overflow','');
var hot = handsontable({
data: Handsontable.helper.createSpreadsheetData(3, 9)
});
selectCell(0,7);
keyDown(Handsontable.helper.KEY_CODES.ENTER);
expect(Handsontable.Dom.outerWidth(hot.getActiveEditor().TEXTAREA)).toBeAroundValue(Handsontable.Dom.outerWidth(hot.getCell(0,7)));
});
it("should display editor with the proper size, when editing a last row after the table is scrolled to the bottom", function() {
var hot = handsontable({
data: Handsontable.helper.createSpreadsheetData(3, 8),
minSpareRows: 1,
height: 100
});
selectCell(0,2);
keyDown(Handsontable.helper.KEY_CODES.ENTER);
var regularHeight = Handsontable.Dom.outerHeight(hot.getActiveEditor().TEXTAREA);
selectCell(3,2);
keyDown(Handsontable.helper.KEY_CODES.ENTER);
keyDown(Handsontable.helper.KEY_CODES.ENTER);
keyDown(Handsontable.helper.KEY_CODES.ENTER);
// lame check, needs investigating why sometimes it leaves 2px error
if(Handsontable.Dom.outerHeight(hot.getActiveEditor().TEXTAREA) == regularHeight) {
expect(Handsontable.Dom.outerHeight(hot.getActiveEditor().TEXTAREA)).toEqual(regularHeight);
} else {
expect(Handsontable.Dom.outerHeight(hot.getActiveEditor().TEXTAREA)).toEqual(regularHeight - 2);
}
});
it("should render the text without trimming out the whitespace, if trimWhitespace is set to false", function () {
this.$container.css('overflow','');
var hot = handsontable({
data: Handsontable.helper.createSpreadsheetData(3, 9),
trimWhitespace: false
});
selectCell(0,2);
keyDown(Handsontable.helper.KEY_CODES.ENTER);
hot.getActiveEditor().TEXTAREA.value = " test of whitespace ";
keyDown(Handsontable.helper.KEY_CODES.ENTER);
expect(getDataAtCell(0,2).length).toEqual(37);
});
it('should insert new line on caret position when pressing ALT + ENTER', function () {
var data = [
["Maserati", "Mazda"],
["Honda", "Mini"]
];
var hot = handsontable({
data: data
});
selectCell(0, 0);
keyDown(Handsontable.helper.KEY_CODES.ENTER);
var $editorInput = $('.handsontableInput');
Handsontable.Dom.setCaretPosition($editorInput[0], 2);
$editorInput.simulate('keydown', {altKey: true, keyCode: Handsontable.helper.KEY_CODES.ENTER});
expect(hot.getActiveEditor().TEXTAREA.value).toEqual("Ma\nserati");
});
});
| bjorkegeek/handsontable | test/jasmine/spec/editors/textEditorSpec.js | JavaScript | mit | 25,037 |
/**
* angular-strap
* @version v2.0.0 - 2014-04-07
* @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.dropdown', ['mgcrea.ngStrap.tooltip']).provider('$dropdown', function () {
var defaults = this.defaults = {
animation: 'am-fade',
prefixClass: 'dropdown',
placement: 'bottom-left',
template: 'dropdown/dropdown.tpl.html',
trigger: 'click',
container: false,
keyboard: true,
html: false,
delay: 0
};
this.$get = [
'$window',
'$rootScope',
'$tooltip',
function ($window, $rootScope, $tooltip) {
var bodyEl = angular.element($window.document.body);
var matchesSelector = Element.prototype.matchesSelector || Element.prototype.webkitMatchesSelector || Element.prototype.mozMatchesSelector || Element.prototype.msMatchesSelector || Element.prototype.oMatchesSelector;
function DropdownFactory(element, config) {
var $dropdown = {};
// Common vars
var options = angular.extend({}, defaults, config);
var scope = $dropdown.$scope = options.scope && options.scope.$new() || $rootScope.$new();
$dropdown = $tooltip(element, options);
// Protected methods
$dropdown.$onKeyDown = function (evt) {
if (!/(38|40)/.test(evt.keyCode))
return;
evt.preventDefault();
evt.stopPropagation();
// Retrieve focused index
var items = angular.element($dropdown.$element[0].querySelectorAll('li:not(.divider) a'));
if (!items.length)
return;
var index;
angular.forEach(items, function (el, i) {
if (matchesSelector && matchesSelector.call(el, ':focus'))
index = i;
});
// Navigate with keyboard
if (evt.keyCode === 38 && index > 0)
index--;
else if (evt.keyCode === 40 && index < items.length - 1)
index++;
else if (angular.isUndefined(index))
index = 0;
items.eq(index)[0].focus();
};
// Overrides
var show = $dropdown.show;
$dropdown.show = function () {
show();
setTimeout(function () {
options.keyboard && $dropdown.$element.on('keydown', $dropdown.$onKeyDown);
bodyEl.on('click', onBodyClick);
});
};
var hide = $dropdown.hide;
$dropdown.hide = function () {
options.keyboard && $dropdown.$element.off('keydown', $dropdown.$onKeyDown);
bodyEl.off('click', onBodyClick);
hide();
};
// Private functions
function onBodyClick(evt) {
if (evt.target === element[0])
return;
return evt.target !== element[0] && $dropdown.hide();
}
return $dropdown;
}
return DropdownFactory;
}
];
}).directive('bsDropdown', [
'$window',
'$location',
'$sce',
'$dropdown',
function ($window, $location, $sce, $dropdown) {
return {
restrict: 'EAC',
scope: true,
link: function postLink(scope, element, attr, transclusion) {
// Directive options
var options = { scope: scope };
angular.forEach([
'placement',
'container',
'delay',
'trigger',
'keyboard',
'html',
'animation',
'template'
], function (key) {
if (angular.isDefined(attr[key]))
options[key] = attr[key];
});
// Support scope as an object
attr.bsDropdown && scope.$watch(attr.bsDropdown, function (newValue, oldValue) {
scope.content = newValue;
}, true);
// Initialize dropdown
var dropdown = $dropdown(element, options);
// Garbage collection
scope.$on('$destroy', function () {
dropdown.destroy();
options = null;
dropdown = null;
});
}
};
}
]); | wormful/cdnjs | ajax/libs/angular-strap/2.0.0/modules/dropdown.js | JavaScript | mit | 4,123 |
<?php
/*
* Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
*
* 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.
*/
namespace CG\Generator;
/**
* Represents a PHP function.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
class PhpFunction
{
private $name;
private $namespace;
private $parameters = array();
private $body = '';
private $referenceReturned = false;
private $docblock;
public static function create($name = null)
{
return new static($name);
}
public function __construct($name = null)
{
$this->name = $name;
}
public function setName($name)
{
$this->name = $name;
return $this;
}
public function setNamespace($namespace)
{
$this->namespace = $namespace;
return $this;
}
public function setParameters(array $parameters)
{
$this->parameters = $parameters;
return $this;
}
public function setReferenceReturned($bool)
{
$this->referenceReturned = (Boolean) $bool;
return $this;
}
public function replaceParameter($position, PhpParameter $parameter)
{
if ($position < 0 || $position > count($this->parameters)) {
throw new \InvalidArgumentException(sprintf('$position must be in the range [0, %d].', count($this->parameters)));
}
$this->parameters[$position] = $parameter;
return $this;
}
public function addParameter(PhpParameter $parameter)
{
$this->parameters[] = $parameter;
return $this;
}
public function removeParameter($position)
{
if (!isset($this->parameters[$position])) {
throw new \InvalidArgumentException(sprintf('There is not parameter at position %d.', $position));
}
unset($this->parameters[$position]);
$this->parameters = array_values($this->parameters);
return $this;
}
public function setBody($body)
{
$this->body = $body;
return $this;
}
public function setDocblock($docBlock)
{
$this->docblock = $docBlock;
return $this;
}
public function getName()
{
return $this->name;
}
public function getNamespace()
{
return $this->namespace;
}
public function getParameters()
{
return $this->parameters;
}
public function getBody()
{
return $this->body;
}
public function getDocblock()
{
return $this->docblock;
}
public function isReferenceReturned()
{
return $this->referenceReturned;
}
} | fmartinnicesoft/Zerg | vendor/jms/cg/src/CG/Generator/PhpFunction.php | PHP | mit | 3,168 |
/* iCheck plugin Flat skin
----------------------------------- */
.icheckbox_flat,
.iradio_flat {
display: inline-block;
*display: inline;
vertical-align: middle;
margin: 0;
padding: 0;
width: 20px;
height: 20px;
background: url(flat.png) no-repeat;
border: none;
cursor: pointer;
}
.icheckbox_flat {
background-position: 0 0;
}
.icheckbox_flat.checked {
background-position: -22px 0;
}
.icheckbox_flat.disabled {
background-position: -44px 0;
cursor: default;
}
.icheckbox_flat.checked.disabled {
background-position: -66px 0;
}
.iradio_flat {
background-position: -88px 0;
}
.iradio_flat.checked {
background-position: -110px 0;
}
.iradio_flat.disabled {
background-position: -132px 0;
cursor: default;
}
.iradio_flat.checked.disabled {
background-position: -154px 0;
}
/* HiDPI support */
@media (-o-min-device-pixel-ratio: 5/4), (-webkit-min-device-pixel-ratio: 1.25), (min-resolution: 120dpi) {
.icheckbox_flat,
.iradio_flat {
background-image: url(flat@2x.png);
-webkit-background-size: 176px 22px;
background-size: 176px 22px;
}
}
/* red */
.icheckbox_flat-red,
.iradio_flat-red {
display: inline-block;
*display: inline;
vertical-align: middle;
margin: 0;
padding: 0;
width: 20px;
height: 20px;
background: url(red.png) no-repeat;
border: none;
cursor: pointer;
}
.icheckbox_flat-red {
background-position: 0 0;
}
.icheckbox_flat-red.checked {
background-position: -22px 0;
}
.icheckbox_flat-red.disabled {
background-position: -44px 0;
cursor: default;
}
.icheckbox_flat-red.checked.disabled {
background-position: -66px 0;
}
.iradio_flat-red {
background-position: -88px 0;
}
.iradio_flat-red.checked {
background-position: -110px 0;
}
.iradio_flat-red.disabled {
background-position: -132px 0;
cursor: default;
}
.iradio_flat-red.checked.disabled {
background-position: -154px 0;
}
/* HiDPI support */
@media (-o-min-device-pixel-ratio: 5/4), (-webkit-min-device-pixel-ratio: 1.25), (min-resolution: 120dpi) {
.icheckbox_flat-red,
.iradio_flat-red {
background-image: url(red@2x.png);
-webkit-background-size: 176px 22px;
background-size: 176px 22px;
}
}
/* green */
.icheckbox_flat-green,
.iradio_flat-green {
display: inline-block;
*display: inline;
vertical-align: middle;
margin: 0;
padding: 0;
width: 20px;
height: 20px;
background: url(green.png) no-repeat;
border: none;
cursor: pointer;
}
.icheckbox_flat-green {
background-position: 0 0;
}
.icheckbox_flat-green.checked {
background-position: -22px 0;
}
.icheckbox_flat-green.disabled {
background-position: -44px 0;
cursor: default;
}
.icheckbox_flat-green.checked.disabled {
background-position: -66px 0;
}
.iradio_flat-green {
background-position: -88px 0;
}
.iradio_flat-green.checked {
background-position: -110px 0;
}
.iradio_flat-green.disabled {
background-position: -132px 0;
cursor: default;
}
.iradio_flat-green.checked.disabled {
background-position: -154px 0;
}
/* HiDPI support */
@media (-o-min-device-pixel-ratio: 5/4), (-webkit-min-device-pixel-ratio: 1.25), (min-resolution: 120dpi) {
.icheckbox_flat-green,
.iradio_flat-green {
background-image: url(green@2x.png);
-webkit-background-size: 176px 22px;
background-size: 176px 22px;
}
}
/* blue */
.icheckbox_flat-blue,
.iradio_flat-blue {
display: inline-block;
*display: inline;
vertical-align: middle;
margin: 0;
padding: 0;
width: 20px;
height: 20px;
background: url(blue.png) no-repeat;
border: none;
cursor: pointer;
}
.icheckbox_flat-blue {
background-position: 0 0;
}
.icheckbox_flat-blue.checked {
background-position: -22px 0;
}
.icheckbox_flat-blue.disabled {
background-position: -44px 0;
cursor: default;
}
.icheckbox_flat-blue.checked.disabled {
background-position: -66px 0;
}
.iradio_flat-blue {
background-position: -88px 0;
}
.iradio_flat-blue.checked {
background-position: -110px 0;
}
.iradio_flat-blue.disabled {
background-position: -132px 0;
cursor: default;
}
.iradio_flat-blue.checked.disabled {
background-position: -154px 0;
}
/* HiDPI support */
@media (-o-min-device-pixel-ratio: 5/4), (-webkit-min-device-pixel-ratio: 1.25), (min-resolution: 120dpi) {
.icheckbox_flat-blue,
.iradio_flat-blue {
background-image: url(blue@2x.png);
-webkit-background-size: 176px 22px;
background-size: 176px 22px;
}
}
/* aero */
.icheckbox_flat-aero,
.iradio_flat-aero {
display: inline-block;
*display: inline;
vertical-align: middle;
margin: 0;
padding: 0;
width: 20px;
height: 20px;
background: url(aero.png) no-repeat;
border: none;
cursor: pointer;
}
.icheckbox_flat-aero {
background-position: 0 0;
}
.icheckbox_flat-aero.checked {
background-position: -22px 0;
}
.icheckbox_flat-aero.disabled {
background-position: -44px 0;
cursor: default;
}
.icheckbox_flat-aero.checked.disabled {
background-position: -66px 0;
}
.iradio_flat-aero {
background-position: -88px 0;
}
.iradio_flat-aero.checked {
background-position: -110px 0;
}
.iradio_flat-aero.disabled {
background-position: -132px 0;
cursor: default;
}
.iradio_flat-aero.checked.disabled {
background-position: -154px 0;
}
/* HiDPI support */
@media (-o-min-device-pixel-ratio: 5/4), (-webkit-min-device-pixel-ratio: 1.25), (min-resolution: 120dpi) {
.icheckbox_flat-aero,
.iradio_flat-aero {
background-image: url(aero@2x.png);
-webkit-background-size: 176px 22px;
background-size: 176px 22px;
}
}
/* grey */
.icheckbox_flat-grey,
.iradio_flat-grey {
display: inline-block;
*display: inline;
vertical-align: middle;
margin: 0;
padding: 0;
width: 20px;
height: 20px;
background: url(grey.png) no-repeat;
border: none;
cursor: pointer;
}
.icheckbox_flat-grey {
background-position: 0 0;
}
.icheckbox_flat-grey.checked {
background-position: -22px 0;
}
.icheckbox_flat-grey.disabled {
background-position: -44px 0;
cursor: default;
}
.icheckbox_flat-grey.checked.disabled {
background-position: -66px 0;
}
.iradio_flat-grey {
background-position: -88px 0;
}
.iradio_flat-grey.checked {
background-position: -110px 0;
}
.iradio_flat-grey.disabled {
background-position: -132px 0;
cursor: default;
}
.iradio_flat-grey.checked.disabled {
background-position: -154px 0;
}
/* HiDPI support */
@media (-o-min-device-pixel-ratio: 5/4), (-webkit-min-device-pixel-ratio: 1.25), (min-resolution: 120dpi) {
.icheckbox_flat-grey,
.iradio_flat-grey {
background-image: url(grey@2x.png);
-webkit-background-size: 176px 22px;
background-size: 176px 22px;
}
}
/* orange */
.icheckbox_flat-orange,
.iradio_flat-orange {
display: inline-block;
*display: inline;
vertical-align: middle;
margin: 0;
padding: 0;
width: 20px;
height: 20px;
background: url(orange.png) no-repeat;
border: none;
cursor: pointer;
}
.icheckbox_flat-orange {
background-position: 0 0;
}
.icheckbox_flat-orange.checked {
background-position: -22px 0;
}
.icheckbox_flat-orange.disabled {
background-position: -44px 0;
cursor: default;
}
.icheckbox_flat-orange.checked.disabled {
background-position: -66px 0;
}
.iradio_flat-orange {
background-position: -88px 0;
}
.iradio_flat-orange.checked {
background-position: -110px 0;
}
.iradio_flat-orange.disabled {
background-position: -132px 0;
cursor: default;
}
.iradio_flat-orange.checked.disabled {
background-position: -154px 0;
}
/* HiDPI support */
@media (-o-min-device-pixel-ratio: 5/4), (-webkit-min-device-pixel-ratio: 1.25), (min-resolution: 120dpi) {
.icheckbox_flat-orange,
.iradio_flat-orange {
background-image: url(orange@2x.png);
-webkit-background-size: 176px 22px;
background-size: 176px 22px;
}
}
/* yellow */
.icheckbox_flat-yellow,
.iradio_flat-yellow {
display: inline-block;
*display: inline;
vertical-align: middle;
margin: 0;
padding: 0;
width: 20px;
height: 20px;
background: url(yellow.png) no-repeat;
border: none;
cursor: pointer;
}
.icheckbox_flat-yellow {
background-position: 0 0;
}
.icheckbox_flat-yellow.checked {
background-position: -22px 0;
}
.icheckbox_flat-yellow.disabled {
background-position: -44px 0;
cursor: default;
}
.icheckbox_flat-yellow.checked.disabled {
background-position: -66px 0;
}
.iradio_flat-yellow {
background-position: -88px 0;
}
.iradio_flat-yellow.checked {
background-position: -110px 0;
}
.iradio_flat-yellow.disabled {
background-position: -132px 0;
cursor: default;
}
.iradio_flat-yellow.checked.disabled {
background-position: -154px 0;
}
/* HiDPI support */
@media (-o-min-device-pixel-ratio: 5/4), (-webkit-min-device-pixel-ratio: 1.25), (min-resolution: 120dpi) {
.icheckbox_flat-yellow,
.iradio_flat-yellow {
background-image: url(yellow@2x.png);
-webkit-background-size: 176px 22px;
background-size: 176px 22px;
}
}
/* pink */
.icheckbox_flat-pink,
.iradio_flat-pink {
display: inline-block;
*display: inline;
vertical-align: middle;
margin: 0;
padding: 0;
width: 20px;
height: 20px;
background: url(pink.png) no-repeat;
border: none;
cursor: pointer;
}
.icheckbox_flat-pink {
background-position: 0 0;
}
.icheckbox_flat-pink.checked {
background-position: -22px 0;
}
.icheckbox_flat-pink.disabled {
background-position: -44px 0;
cursor: default;
}
.icheckbox_flat-pink.checked.disabled {
background-position: -66px 0;
}
.iradio_flat-pink {
background-position: -88px 0;
}
.iradio_flat-pink.checked {
background-position: -110px 0;
}
.iradio_flat-pink.disabled {
background-position: -132px 0;
cursor: default;
}
.iradio_flat-pink.checked.disabled {
background-position: -154px 0;
}
/* HiDPI support */
@media (-o-min-device-pixel-ratio: 5/4), (-webkit-min-device-pixel-ratio: 1.25), (min-resolution: 120dpi) {
.icheckbox_flat-pink,
.iradio_flat-pink {
background-image: url(pink@2x.png);
-webkit-background-size: 176px 22px;
background-size: 176px 22px;
}
}
/* purple */
.icheckbox_flat-purple,
.iradio_flat-purple {
display: inline-block;
*display: inline;
vertical-align: middle;
margin: 0;
padding: 0;
width: 20px;
height: 20px;
background: url(purple.png) no-repeat;
border: none;
cursor: pointer;
}
.icheckbox_flat-purple {
background-position: 0 0;
}
.icheckbox_flat-purple.checked {
background-position: -22px 0;
}
.icheckbox_flat-purple.disabled {
background-position: -44px 0;
cursor: default;
}
.icheckbox_flat-purple.checked.disabled {
background-position: -66px 0;
}
.iradio_flat-purple {
background-position: -88px 0;
}
.iradio_flat-purple.checked {
background-position: -110px 0;
}
.iradio_flat-purple.disabled {
background-position: -132px 0;
cursor: default;
}
.iradio_flat-purple.checked.disabled {
background-position: -154px 0;
}
/* HiDPI support */
@media (-o-min-device-pixel-ratio: 5/4), (-webkit-min-device-pixel-ratio: 1.25), (min-resolution: 120dpi) {
.icheckbox_flat-purple,
.iradio_flat-purple {
background-image: url(purple@2x.png);
-webkit-background-size: 176px 22px;
background-size: 176px 22px;
}
} | danangnurfauzi/simatek | assets/example page/style1/vendors/iCheck/skins/flat/all.css | CSS | mit | 12,513 |
<?php
/*
* This file is part of Twig.
*
* (c) 2009 Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Imports macros.
*
* <pre>
* {% import 'forms.html' as forms %}
* </pre>
*/
class Twig_TokenParser_Import extends Twig_TokenParser
{
/**
* Parses a token and returns a node.
*
* @param Twig_Token $token A Twig_Token instance
*
* @return Twig_NodeInterface A Twig_NodeInterface instance
*/
public function parse(Twig_Token $token)
{
$macro = $this->parser->getExpressionParser()->parseExpression();
$this->parser->getStream()->expect('as');
$var = new Twig_Node_Expression_AssignName($this->parser->getStream()->expect(Twig_Token::NAME_TYPE)->getValue(), $token->getLine());
$this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE);
$this->parser->addImportedSymbol('template', $var->getAttribute('name'));
return new Twig_Node_Import($macro, $var, $token->getLine(), $this->getTag());
}
/**
* Gets the tag name associated with this token parser.
*
* @return string The tag name
*/
public function getTag()
{
return 'import';
}
}
| vunnu/sym_framework | vendor/twig/twig/lib/Twig/TokenParser/Import.php | PHP | mit | 1,296 |
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang("a11yhelp","tr",{title:"Erişilebilirlik Talimatları",contents:"Yardım içeriği. Bu pencereyi kapatmak için ESC tuşuna basın.",legend:[{name:"Genel",items:[{name:"Düzenleyici Araç Çubuğu",legend:"Araç çubuğunda gezinmek için ${toolbarFocus} basın. TAB ve SHIFT-TAB ile önceki ve sonraki araç çubuğu grubuna taşıyın. SAĞ OK veya SOL OK ile önceki ve sonraki bir araç çubuğu düğmesini hareket ettirin. SPACE tuşuna basın veya araç çubuğu düğmesini etkinleştirmek için ENTER tuşna basın."},
{name:"Diyalog Düzenleyici",legend:"Dialog penceresi içinde, sonraki iletişim alanına gitmek için SEKME tuşuna basın, önceki alana geçmek için SHIFT + TAB tuşuna basın, pencereyi göndermek için ENTER tuşuna basın, dialog penceresini iptal etmek için ESC tuşuna basın. Birden çok sekme sayfaları olan diyalogların, sekme listesine gitmek için ALT + F10 tuşlarına basın. Sonra TAB veya SAĞ OK sonraki sekmeye taşıyın. SHIFT + TAB veya SOL OK ile önceki sekmeye geçin. Sekme sayfayı seçmek için SPACE veya ENTER tuşuna basın."},
{name:"İçerik Menü Editörü",legend:"İçerik menüsünü açmak için ${contextMenu} veya UYGULAMA TUŞU'na basın. Daha sonra SEKME veya AŞAĞI OK ile bir sonraki menü seçeneği taşıyın. SHIFT + TAB veya YUKARI OK ile önceki seçeneğe gider. Menü seçeneğini seçmek için SPACE veya ENTER tuşuna basın. Seçili seçeneğin alt menüsünü SPACE ya da ENTER veya SAĞ OK açın. Üst menü öğesini geçmek için ESC veya SOL OK ile geri dönün. ESC ile bağlam menüsünü kapatın."},{name:"Liste Kutusu Editörü",legend:"Liste kutusu içinde, bir sonraki liste öğesine SEKME VEYA AŞAĞI OK ile taşıyın. SHIFT + TAB veya YUKARI önceki liste öğesi taşıyın. Liste seçeneği seçmek için SPACE veya ENTER tuşuna basın. Liste kutusunu kapatmak için ESC tuşuna basın."},
{name:"Element Yol Çubuğu Editörü",legend:"Elementlerin yol çubuğunda gezinmek için ${ElementsPathFocus} basın. SEKME veya SAĞ OK ile sonraki element düğmesine taşıyın. SHIFT + TAB veya SOL OK önceki düğmeye hareket ettirin. Editör içindeki elementi seçmek için ENTER veya SPACE tuşuna basın."}]},{name:"Komutlar",items:[{name:"Komutu geri al",legend:"$(undo)'ya basın"},{name:"Komutu geri al",legend:"${redo} basın"},{name:" Kalın komut",legend:"${bold} basın"},{name:" İtalik komutu",legend:"${italic} basın"},
{name:" Alttan çizgi komutu",legend:"${underline} basın"},{name:" Bağlantı komutu",legend:"${link} basın"},{name:" Araç çubuğu Toplama komutu",legend:"${toolbarCollapse} basın"},{name:"Önceki komut alanına odaklan",legend:"Düzeltme imleçinden önce, en yakın uzaktaki alana erişmek için ${accessPreviousSpace} basın, örneğin: iki birleşik HR elementleri. Aynı tuş kombinasyonu tekrarıyla diğer alanlarada ulaşın."},{name:"Sonraki komut alanına odaklan",legend:"Düzeltme imleçinden sonra, en yakın uzaktaki alana erişmek için ${accessNextSpace} basın, örneğin: iki birleşik HR elementleri. Aynı tuş kombinasyonu tekrarıyla diğer alanlarada ulaşın."},
{name:"Erişilebilirlik Yardımı",legend:"${a11yHelp}'e basın"}]}]}); | RavindraGkm/classic-soft | assets/js/plugin/ckeditor/plugins/a11yhelp/dialogs/lang/tr.js | JavaScript | mit | 3,377 |
/*
Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang("specialchar","cy",{euro:"Arwydd yr Ewro",lsquo:"Dyfynnod chwith unigol",rsquo:"Dyfynnod dde unigol",ldquo:"Dyfynnod chwith dwbl",rdquo:"Dyfynnod dde dwbl",ndash:"Cysylltnod en",mdash:"Cysylltnod em",iexcl:"Ebychnod gwrthdro",cent:"Arwydd sent",pound:"Arwydd punt",curren:"Arwydd arian cyfred",yen:"Arwydd yen",brvbar:"Bar toriedig",sect:"Arwydd adran",uml:"Didolnod",copy:"Arwydd hawlfraint",ordf:"Dangosydd benywaidd",laquo:"Dyfynnod dwbl ar ongl i'r chwith",not:"Arwydd Nid",
reg:"Arwydd cofrestredig",macr:"Macron",deg:"Arwydd gradd",sup2:"Dau uwchsgript",sup3:"Tri uwchsgript",acute:"Acen ddyrchafedig",micro:"Arwydd micro",para:"Arwydd pilcrow",middot:"Dot canol",cedil:"Sedila",sup1:"Un uwchsgript",ordm:"Dangosydd gwrywaidd",raquo:"Dyfynnod dwbl ar ongl i'r dde",frac14:"Ffracsiwn cyffredin un cwarter",frac12:"Ffracsiwn cyffredin un hanner",frac34:"Ffracsiwn cyffredin tri chwarter",iquest:"Marc cwestiwn gwrthdroëdig",Agrave:"Priflythyren A Lladinaidd gydag acen ddisgynedig",
Aacute:"Priflythyren A Lladinaidd gydag acen ddyrchafedig",Acirc:"Priflythyren A Lladinaidd gydag acen grom",Atilde:"Priflythyren A Lladinaidd gyda thild",Auml:"Priflythyren A Lladinaidd gyda didolnod",Aring:"Priflythyren A Lladinaidd gyda chylch uwchben",AElig:"Priflythyren Æ Lladinaidd",Ccedil:"Priflythyren C Lladinaidd gyda sedila",Egrave:"Priflythyren E Lladinaidd gydag acen ddisgynedig",Eacute:"Priflythyren E Lladinaidd gydag acen ddyrchafedig",Ecirc:"Priflythyren E Lladinaidd gydag acen grom",
Euml:"Priflythyren E Lladinaidd gyda didolnod",Igrave:"Priflythyren I Lladinaidd gydag acen ddisgynedig",Iacute:"Priflythyren I Lladinaidd gydag acen ddyrchafedig",Icirc:"Priflythyren I Lladinaidd gydag acen grom",Iuml:"Priflythyren I Lladinaidd gyda didolnod",ETH:"Priflythyren Eth",Ntilde:"Priflythyren N Lladinaidd gyda thild",Ograve:"Priflythyren O Lladinaidd gydag acen ddisgynedig",Oacute:"Priflythyren O Lladinaidd gydag acen ddyrchafedig",Ocirc:"Priflythyren O Lladinaidd gydag acen grom",Otilde:"Priflythyren O Lladinaidd gyda thild",
Ouml:"Priflythyren O Lladinaidd gyda didolnod",times:"Arwydd lluosi",Oslash:"Priflythyren O Lladinaidd gyda strôc",Ugrave:"Priflythyren U Lladinaidd gydag acen ddisgynedig",Uacute:"Priflythyren U Lladinaidd gydag acen ddyrchafedig",Ucirc:"Priflythyren U Lladinaidd gydag acen grom",Uuml:"Priflythyren U Lladinaidd gyda didolnod",Yacute:"Priflythyren Y Lladinaidd gydag acen ddyrchafedig",THORN:"Priflythyren Thorn",szlig:"Llythyren s fach Lladinaidd siarp ",agrave:"Llythyren a fach Lladinaidd gydag acen ddisgynedig",
aacute:"Llythyren a fach Lladinaidd gydag acen ddyrchafedig",acirc:"Llythyren a fach Lladinaidd gydag acen grom",atilde:"Llythyren a fach Lladinaidd gyda thild",auml:"Llythyren a fach Lladinaidd gyda didolnod",aring:"Llythyren a fach Lladinaidd gyda chylch uwchben",aelig:"Llythyren æ fach Lladinaidd",ccedil:"Llythyren c fach Lladinaidd gyda sedila",egrave:"Llythyren e fach Lladinaidd gydag acen ddisgynedig",eacute:"Llythyren e fach Lladinaidd gydag acen ddyrchafedig",ecirc:"Llythyren e fach Lladinaidd gydag acen grom",
euml:"Llythyren e fach Lladinaidd gyda didolnod",igrave:"Llythyren i fach Lladinaidd gydag acen ddisgynedig",iacute:"Llythyren i fach Lladinaidd gydag acen ddyrchafedig",icirc:"Llythyren i fach Lladinaidd gydag acen grom",iuml:"Llythyren i fach Lladinaidd gyda didolnod",eth:"Llythyren eth fach",ntilde:"Llythyren n fach Lladinaidd gyda thild",ograve:"Llythyren o fach Lladinaidd gydag acen ddisgynedig",oacute:"Llythyren o fach Lladinaidd gydag acen ddyrchafedig",ocirc:"Llythyren o fach Lladinaidd gydag acen grom",
otilde:"Llythyren o fach Lladinaidd gyda thild",ouml:"Llythyren o fach Lladinaidd gyda didolnod",divide:"Arwydd rhannu",oslash:"Llythyren o fach Lladinaidd gyda strôc",ugrave:"Llythyren u fach Lladinaidd gydag acen ddisgynedig",uacute:"Llythyren u fach Lladinaidd gydag acen ddyrchafedig",ucirc:"Llythyren u fach Lladinaidd gydag acen grom",uuml:"Llythyren u fach Lladinaidd gyda didolnod",yacute:"Llythyren y fach Lladinaidd gydag acen ddisgynedig",thorn:"Llythyren o fach Lladinaidd gyda strôc",yuml:"Llythyren y fach Lladinaidd gyda didolnod",
OElig:"Priflythyren cwlwm OE Lladinaidd ",oelig:"Priflythyren cwlwm oe Lladinaidd ",372:"Priflythyren W gydag acen grom",374:"Priflythyren Y gydag acen grom",373:"Llythyren w fach gydag acen grom",375:"Llythyren y fach gydag acen grom",sbquo:"Dyfynnod sengl 9-isel",8219:"Dyfynnod sengl 9-uchel cildro",bdquo:"Dyfynnod dwbl 9-isel",hellip:"Coll geiriau llorweddol",trade:"Arwydd marc masnachol",9658:"Pwyntydd du i'r dde",bull:"Bwled",rarr:"Saeth i'r dde",rArr:"Saeth ddwbl i'r dde",hArr:"Saeth ddwbl i'r chwith",
diams:"Siwt diemwnt du",asymp:"Bron yn hafal iddo"}); | kitcambridge/cdnjs | ajax/libs/ckeditor/4.4.1/plugins/specialchar/dialogs/lang/cy.js | JavaScript | mit | 4,891 |
YUI.add('yui-log', function (Y, NAME) {
/**
* Provides console log capability and exposes a custom event for
* console implementations. This module is a `core` YUI module,
* <a href="../classes/YUI.html#method_log">it's documentation is located under the YUI class</a>.
*
* @module yui
* @submodule yui-log
*/
var INSTANCE = Y,
LOGEVENT = 'yui:log',
UNDEFINED = 'undefined',
LEVELS = { debug: 1,
info: 2,
warn: 4,
error: 8 };
/**
* If the 'debug' config is true, a 'yui:log' event will be
* dispatched, which the Console widget and anything else
* can consume. If the 'useBrowserConsole' config is true, it will
* write to the browser console if available. YUI-specific log
* messages will only be present in the -debug versions of the
* JS files. The build system is supposed to remove log statements
* from the raw and minified versions of the files.
*
* @method log
* @for YUI
* @param {String} msg The message to log.
* @param {String} cat The log category for the message. Default
* categories are "info", "warn", "error", time".
* Custom categories can be used as well. (opt).
* @param {String} src The source of the the message (opt).
* @param {boolean} silent If true, the log event won't fire.
* @return {YUI} YUI instance.
*/
INSTANCE.log = function(msg, cat, src, silent) {
var bail, excl, incl, m, f, minlevel,
Y = INSTANCE,
c = Y.config,
publisher = (Y.fire) ? Y : YUI.Env.globalEvents;
// suppress log message if the config is off or the event stack
// or the event call stack contains a consumer of the yui:log event
if (c.debug) {
// apply source filters
src = src || "";
if (typeof src !== "undefined") {
excl = c.logExclude;
incl = c.logInclude;
if (incl && !(src in incl)) {
bail = 1;
} else if (incl && (src in incl)) {
bail = !incl[src];
} else if (excl && (src in excl)) {
bail = excl[src];
}
// Determine the current minlevel as defined in configuration
Y.config.logLevel = Y.config.logLevel || 'debug';
minlevel = LEVELS[Y.config.logLevel.toLowerCase()];
if (cat in LEVELS && LEVELS[cat] < minlevel) {
// Skip this message if the we don't meet the defined minlevel
bail = 1;
}
}
if (!bail) {
if (c.useBrowserConsole) {
m = (src) ? src + ': ' + msg : msg;
if (Y.Lang.isFunction(c.logFn)) {
c.logFn.call(Y, msg, cat, src);
} else if (typeof console !== UNDEFINED && console.log) {
f = (cat && console[cat] && (cat in LEVELS)) ? cat : 'log';
console[f](m);
} else if (typeof opera !== UNDEFINED) {
opera.postError(m);
}
}
if (publisher && !silent) {
if (publisher === Y && (!publisher.getEvent(LOGEVENT))) {
publisher.publish(LOGEVENT, {
broadcast: 2
});
}
publisher.fire(LOGEVENT, {
msg: msg,
cat: cat,
src: src
});
}
}
}
return Y;
};
/**
* Write a system message. This message will be preserved in the
* minified and raw versions of the YUI files, unlike log statements.
* @method message
* @for YUI
* @param {String} msg The message to log.
* @param {String} cat The log category for the message. Default
* categories are "info", "warn", "error", time".
* Custom categories can be used as well. (opt).
* @param {String} src The source of the the message (opt).
* @param {boolean} silent If true, the log event won't fire.
* @return {YUI} YUI instance.
*/
INSTANCE.message = function() {
return INSTANCE.log.apply(INSTANCE, arguments);
};
}, '@VERSION@', {"requires": ["yui-base"]});
| emijrp/cdnjs | ajax/libs/yui/3.10.1/yui-log/yui-log.js | JavaScript | mit | 4,249 |
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react"),require("react-dom")):"function"==typeof define&&define.amd?define(["react","react-dom"],t):"object"==typeof exports?exports.ReactModal=t(require("react"),require("react-dom")):e.ReactModal=t(e.React,e.ReactDOM)}(this,function(e,t){return function(e){function t(o){if(n[o])return n[o].exports;var r=n[o]={exports:{},id:o,loaded:!1};return e[o].call(r.exports,r,r.exports,t),r.loaded=!0,r.exports}var n={};return t.m=e,t.c=n,t.p="/",t(0)}([function(e,t,n){"use strict";e.exports=n(1)},function(e,t,n){"use strict";function o(e){return e()}var r=n(2),s=n(3),i=n(4),u=r.createFactory(n(5)),a=n(10),c=n(11),l=n(3).unstable_renderSubtreeIntoContainer,p=n(9),f=i.canUseDOM?window.HTMLElement:{},d=i.canUseDOM?document.body:{appendChild:function(){}},h=r.createClass({displayName:"Modal",statics:{setAppElement:function(e){d=a.setElement(e)},injectCSS:function(){console.warn("React-Modal: injectCSS has been deprecated and no longer has any effect. It will be removed in a later version")}},propTypes:{isOpen:r.PropTypes.bool.isRequired,style:r.PropTypes.shape({content:r.PropTypes.object,overlay:r.PropTypes.object}),portalClassName:r.PropTypes.string,appElement:r.PropTypes.instanceOf(f),onAfterOpen:r.PropTypes.func,onRequestClose:r.PropTypes.func,closeTimeoutMS:r.PropTypes.number,ariaHideApp:r.PropTypes.bool,shouldCloseOnOverlayClick:r.PropTypes.bool,parentSelector:r.PropTypes.func,role:r.PropTypes.string,contentLabel:r.PropTypes.string.isRequired},getDefaultProps:function(){return{isOpen:!1,portalClassName:"ReactModalPortal",ariaHideApp:!0,closeTimeoutMS:0,shouldCloseOnOverlayClick:!0,parentSelector:function(){return document.body}}},componentDidMount:function(){this.node=document.createElement("div"),this.node.className=this.props.portalClassName;var e=o(this.props.parentSelector);e.appendChild(this.node),this.renderPortal(this.props)},componentWillReceiveProps:function(e){var t=o(this.props.parentSelector),n=o(e.parentSelector);n!==t&&(t.removeChild(this.node),n.appendChild(this.node)),this.renderPortal(e)},componentWillUnmount:function(){this.props.ariaHideApp&&a.show(this.props.appElement),s.unmountComponentAtNode(this.node);var e=o(this.props.parentSelector);e.removeChild(this.node),c(document.body).remove("ReactModal__Body--open")},renderPortal:function(e){e.isOpen?c(document.body).add("ReactModal__Body--open"):c(document.body).remove("ReactModal__Body--open"),e.ariaHideApp&&a.toggle(e.isOpen,e.appElement),this.portal=l(this,u(p({},e,{defaultStyles:h.defaultStyles})),this.node)},render:function(){return r.DOM.noscript()}});h.defaultStyles={overlay:{position:"fixed",top:0,left:0,right:0,bottom:0,backgroundColor:"rgba(255, 255, 255, 0.75)"},content:{position:"absolute",top:"40px",left:"40px",right:"40px",bottom:"40px",border:"1px solid #ccc",background:"#fff",overflow:"auto",WebkitOverflowScrolling:"touch",borderRadius:"4px",outline:"none",padding:"20px"}},e.exports=h},function(t,n){t.exports=e},function(e,n){e.exports=t},function(e,t,n){var o;/*!
Copyright (c) 2015 Jed Watson.
Based on code that is Copyright 2013-2015, Facebook, Inc.
All rights reserved.
*/
!function(){"use strict";var r=!("undefined"==typeof window||!window.document||!window.document.createElement),s={canUseDOM:r,canUseWorkers:"undefined"!=typeof Worker,canUseEventListeners:r&&!(!window.addEventListener&&!window.attachEvent),canUseViewport:r&&!!window.screen};o=function(){return s}.call(t,n,t,e),!(void 0!==o&&(e.exports=o))}()},function(e,t,n){"use strict";var o=n(2),r=o.DOM.div,s=n(6),i=n(8),u=n(9),a={overlay:{base:"ReactModal__Overlay",afterOpen:"ReactModal__Overlay--after-open",beforeClose:"ReactModal__Overlay--before-close"},content:{base:"ReactModal__Content",afterOpen:"ReactModal__Content--after-open",beforeClose:"ReactModal__Content--before-close"}};e.exports=o.createClass({displayName:"ModalPortal",shouldClose:null,getDefaultProps:function(){return{style:{overlay:{},content:{}}}},getInitialState:function(){return{afterOpen:!1,beforeClose:!1}},componentDidMount:function(){this.props.isOpen&&(this.setFocusAfterRender(!0),this.open())},componentWillUnmount:function(){clearTimeout(this.closeTimer)},componentWillReceiveProps:function(e){!this.props.isOpen&&e.isOpen?(this.setFocusAfterRender(!0),this.open()):this.props.isOpen&&!e.isOpen&&this.close()},componentDidUpdate:function(){this.focusAfterRender&&(this.focusContent(),this.setFocusAfterRender(!1))},setFocusAfterRender:function(e){this.focusAfterRender=e},open:function(){this.state.afterOpen&&this.state.beforeClose?(clearTimeout(this.closeTimer),this.setState({beforeClose:!1})):(s.setupScopedFocus(this.node),s.markForFocusLater(),this.setState({isOpen:!0},function(){this.setState({afterOpen:!0}),this.props.isOpen&&this.props.onAfterOpen&&this.props.onAfterOpen()}.bind(this)))},close:function(){this.props.closeTimeoutMS>0?this.closeWithTimeout():this.closeWithoutTimeout()},focusContent:function(){this.contentHasFocus()||this.refs.content.focus()},closeWithTimeout:function(){this.setState({beforeClose:!0},function(){this.closeTimer=setTimeout(this.closeWithoutTimeout,this.props.closeTimeoutMS)}.bind(this))},closeWithoutTimeout:function(){this.setState({beforeClose:!1,isOpen:!1,afterOpen:!1},this.afterClose)},afterClose:function(){s.returnFocus(),s.teardownScopedFocus()},handleKeyDown:function(e){9==e.keyCode&&i(this.refs.content,e),27==e.keyCode&&(e.preventDefault(),this.requestClose(e))},handleOverlayMouseDown:function(e){null===this.shouldClose&&(this.shouldClose=!0)},handleOverlayMouseUp:function(e){this.shouldClose&&this.props.shouldCloseOnOverlayClick&&(this.ownerHandlesClose()?this.requestClose(e):this.focusContent()),this.shouldClose=null},handleContentMouseDown:function(e){this.shouldClose=!1},handleContentMouseUp:function(e){this.shouldClose=!1},requestClose:function(e){this.ownerHandlesClose()&&this.props.onRequestClose(e)},ownerHandlesClose:function(){return this.props.onRequestClose},shouldBeClosed:function(){return!this.props.isOpen&&!this.state.beforeClose},contentHasFocus:function(){return document.activeElement===this.refs.content||this.refs.content.contains(document.activeElement)},buildClassName:function(e,t){var n=a[e].base;return this.state.afterOpen&&(n+=" "+a[e].afterOpen),this.state.beforeClose&&(n+=" "+a[e].beforeClose),t?n+" "+t:n},render:function(){var e=this.props.className?{}:this.props.defaultStyles.content,t=this.props.overlayClassName?{}:this.props.defaultStyles.overlay;return this.shouldBeClosed()?r():r({ref:"overlay",className:this.buildClassName("overlay",this.props.overlayClassName),style:u({},t,this.props.style.overlay||{}),onMouseDown:this.handleOverlayMouseDown,onMouseUp:this.handleOverlayMouseUp},r({ref:"content",style:u({},e,this.props.style.content||{}),className:this.buildClassName("content",this.props.className),tabIndex:"-1",onKeyDown:this.handleKeyDown,onMouseDown:this.handleContentMouseDown,onMouseUp:this.handleContentMouseUp,role:this.props.role,"aria-label":this.props.contentLabel},this.props.children))}})},function(e,t,n){"use strict";function o(e){a=!0}function r(e){if(a){if(a=!1,!i)return;setTimeout(function(){if(!i.contains(document.activeElement)){var e=s(i)[0]||i;e.focus()}},0)}}var s=n(7),i=null,u=null,a=!1;t.markForFocusLater=function(){u=document.activeElement},t.returnFocus=function(){try{u.focus()}catch(e){console.warn("You tried to return focus to "+u+" but it is not in the DOM anymore")}u=null},t.setupScopedFocus=function(e){i=e,window.addEventListener?(window.addEventListener("blur",o,!1),document.addEventListener("focus",r,!0)):(window.attachEvent("onBlur",o),document.attachEvent("onFocus",r))},t.teardownScopedFocus=function(){i=null,window.addEventListener?(window.removeEventListener("blur",o),document.removeEventListener("focus",r)):(window.detachEvent("onBlur",o),document.detachEvent("onFocus",r))}},function(e,t){"use strict";/*!
* Adapted from jQuery UI core
*
* http://jqueryui.com
*
* Copyright 2014 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/category/ui-core/
*/
function n(e,t){var n=e.nodeName.toLowerCase();return(/input|select|textarea|button|object/.test(n)?!e.disabled:"a"===n?e.href||t:t)&&r(e)}function o(e){return e.offsetWidth<=0&&e.offsetHeight<=0||"none"===e.style.display}function r(e){for(;e&&e!==document.body;){if(o(e))return!1;e=e.parentNode}return!0}function s(e){var t=e.getAttribute("tabindex");null===t&&(t=void 0);var o=isNaN(t);return(o||t>=0)&&n(e,!o)}function i(e){return[].slice.call(e.querySelectorAll("*"),0).filter(function(e){return s(e)})}e.exports=i},function(e,t,n){"use strict";var o=n(7);e.exports=function(e,t){var n=o(e);if(!n.length)return void t.preventDefault();var r=n[t.shiftKey?0:n.length-1],s=r===document.activeElement||e===document.activeElement;if(s){t.preventDefault();var i=n[t.shiftKey?n.length-1:0];i.focus()}}},function(e,t){function n(e,t,n){switch(n.length){case 0:return e.call(t);case 1:return e.call(t,n[0]);case 2:return e.call(t,n[0],n[1]);case 3:return e.call(t,n[0],n[1],n[2])}return e.apply(t,n)}function o(e,t){for(var n=-1,o=Array(e);++n<e;)o[n]=t(n);return o}function r(e,t){return function(n){return e(t(n))}}function s(e,t){var n=_(e)||m(e)?o(e.length,String):[],r=n.length,s=!!r;for(var i in e)!t&&!N.call(e,i)||s&&("length"==i||p(i,r))||n.push(i);return n}function i(e,t,n){var o=e[t];N.call(e,t)&&h(o,n)&&(void 0!==n||t in e)||(e[t]=n)}function u(e){if(!d(e))return P(e);var t=[];for(var n in Object(e))N.call(e,n)&&"constructor"!=n&&t.push(n);return t}function a(e,t){return t=F(void 0===t?e.length-1:t,0),function(){for(var o=arguments,r=-1,s=F(o.length-t,0),i=Array(s);++r<s;)i[r]=o[t+r];r=-1;for(var u=Array(t+1);++r<t;)u[r]=o[r];return u[t]=i,n(e,this,u)}}function c(e,t,n,o){n||(n={});for(var r=-1,s=t.length;++r<s;){var u=t[r],a=o?o(n[u],e[u],u,n,e):void 0;i(n,u,void 0===a?e[u]:a)}return n}function l(e){return a(function(t,n){var o=-1,r=n.length,s=r>1?n[r-1]:void 0,i=r>2?n[2]:void 0;for(s=e.length>3&&"function"==typeof s?(r--,s):void 0,i&&f(n[0],n[1],i)&&(s=r<3?void 0:s,r=1),t=Object(t);++o<r;){var u=n[o];u&&e(t,u,o,s)}return t})}function p(e,t){return t=null==t?M:t,!!t&&("number"==typeof e||E.test(e))&&e>-1&&e%1==0&&e<t}function f(e,t,n){if(!w(n))return!1;var o=typeof t;return!!("number"==o?v(n)&&p(t,n.length):"string"==o&&t in n)&&h(n[t],e)}function d(e){var t=e&&e.constructor,n="function"==typeof t&&t.prototype||R;return e===n}function h(e,t){return e===t||e!==e&&t!==t}function m(e){return y(e)&&N.call(e,"callee")&&(!D.call(e,"callee")||A.call(e)==S)}function v(e){return null!=e&&C(e.length)&&!b(e)}function y(e){return O(e)&&v(e)}function b(e){var t=w(e)?A.call(e):"";return t==T||t==x}function C(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=M}function w(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function O(e){return!!e&&"object"==typeof e}function g(e){return v(e)?s(e):u(e)}var M=9007199254740991,S="[object Arguments]",T="[object Function]",x="[object GeneratorFunction]",E=/^(?:0|[1-9]\d*)$/,R=Object.prototype,N=R.hasOwnProperty,A=R.toString,D=R.propertyIsEnumerable,P=r(Object.keys,Object),F=Math.max,j=!D.call({valueOf:1},"valueOf"),_=Array.isArray,q=l(function(e,t){if(j||d(t)||v(t))return void c(t,g(t),e);for(var n in t)N.call(t,n)&&i(e,n,t[n])});e.exports=q},function(e,t){"use strict";function n(e){if("string"==typeof e){var t=document.querySelectorAll(e);e="length"in t?t[0]:t}return a=e||a}function o(e){i(e),(e||a).setAttribute("aria-hidden","true")}function r(e){i(e),(e||a).removeAttribute("aria-hidden")}function s(e,t){e?o(t):r(t)}function i(e){if(!e&&!a)throw new Error("react-modal: You must set an element with `Modal.setAppElement(el)` to make this accessible")}function u(){a=document.body}var a="undefined"!=typeof document?document.body:null;t.toggle=s,t.setElement=n,t.show=r,t.hide=o,t.resetForTesting=u},function(e,t){function n(e,t){if(e.indexOf)return e.indexOf(t);for(var n=0,o=e.length;n<o;n++)if(e[n]===t)return n;return-1}function o(e){if(!(this instanceof o))return new o(e);e||(e={}),e.nodeType&&(e={el:e}),this.opts=e,this.el=e.el||document.body,"object"!=typeof this.el&&(this.el=document.querySelector(this.el))}e.exports=function(e){return new o(e)},o.prototype.add=function(e){var t=this.el;if(t){if(""===t.className)return t.className=e;var o=t.className.split(" ");return n(o,e)>-1?o:(o.push(e),t.className=o.join(" "),o)}},o.prototype.remove=function(e){var t=this.el;if(t&&""!==t.className){var o=t.className.split(" "),r=n(o,e);return r>-1&&o.splice(r,1),t.className=o.join(" "),o}},o.prototype.has=function(e){var t=this.el;if(t){var o=t.className.split(" ");return n(o,e)>-1}},o.prototype.toggle=function(e){var t=this.el;t&&(this.has(e)?this.remove(e):this.add(e))}}])}); | dlueth/cdnjs | ajax/libs/react-modal/1.6.5/react-modal.min.js | JavaScript | mit | 12,878 |
# frozen_string_literal: true
require "strscan"
module ActiveSupport
class Duration
# Parses a string formatted according to ISO 8601 Duration into the hash.
#
# See {ISO 8601}[https://en.wikipedia.org/wiki/ISO_8601#Durations] for more information.
#
# This parser allows negative parts to be present in pattern.
class ISO8601Parser # :nodoc:
class ParsingError < ::ArgumentError; end
PERIOD_OR_COMMA = /\.|,/
PERIOD = "."
COMMA = ","
SIGN_MARKER = /\A\-|\+|/
DATE_MARKER = /P/
TIME_MARKER = /T/
DATE_COMPONENT = /(\-?\d+(?:[.,]\d+)?)(Y|M|D|W)/
TIME_COMPONENT = /(\-?\d+(?:[.,]\d+)?)(H|M|S)/
DATE_TO_PART = { "Y" => :years, "M" => :months, "W" => :weeks, "D" => :days }
TIME_TO_PART = { "H" => :hours, "M" => :minutes, "S" => :seconds }
DATE_COMPONENTS = [:years, :months, :days]
TIME_COMPONENTS = [:hours, :minutes, :seconds]
attr_reader :parts, :scanner
attr_accessor :mode, :sign
def initialize(string)
@scanner = StringScanner.new(string)
@parts = {}
@mode = :start
@sign = 1
end
def parse!
while !finished?
case mode
when :start
if scan(SIGN_MARKER)
self.sign = (scanner.matched == "-") ? -1 : 1
self.mode = :sign
else
raise_parsing_error
end
when :sign
if scan(DATE_MARKER)
self.mode = :date
else
raise_parsing_error
end
when :date
if scan(TIME_MARKER)
self.mode = :time
elsif scan(DATE_COMPONENT)
parts[DATE_TO_PART[scanner[2]]] = number * sign
else
raise_parsing_error
end
when :time
if scan(TIME_COMPONENT)
parts[TIME_TO_PART[scanner[2]]] = number * sign
else
raise_parsing_error
end
end
end
validate!
parts
end
private
def finished?
scanner.eos?
end
# Parses number which can be a float with either comma or period.
def number
PERIOD_OR_COMMA.match?(scanner[1]) ? scanner[1].tr(COMMA, PERIOD).to_f : scanner[1].to_i
end
def scan(pattern)
scanner.scan(pattern)
end
def raise_parsing_error(reason = nil)
raise ParsingError, "Invalid ISO 8601 duration: #{scanner.string.inspect} #{reason}".strip
end
# Checks for various semantic errors as stated in ISO 8601 standard.
def validate!
raise_parsing_error("is empty duration") if parts.empty?
# Mixing any of Y, M, D with W is invalid.
if parts.key?(:weeks) && (parts.keys & DATE_COMPONENTS).any?
raise_parsing_error("mixing weeks with other date parts not allowed")
end
# Specifying an empty T part is invalid.
if mode == :time && (parts.keys & TIME_COMPONENTS).empty?
raise_parsing_error("time part marker is present but time part is empty")
end
fractions = parts.values.reject(&:zero?).select { |a| (a % 1) != 0 }
unless fractions.empty? || (fractions.size == 1 && fractions.last == @parts.values.reject(&:zero?).last)
raise_parsing_error "(only last part can be fractional)"
end
true
end
end
end
end
| arunagw/rails | activesupport/lib/active_support/duration/iso8601_parser.rb | Ruby | mit | 3,535 |
# encoding: utf-8
module Mongoid
module Relations
module Referenced
# This class defines the behaviour for all relations that are a
# many-to-many between documents in different collections.
class ManyToMany < Many
# Appends a document or array of documents to the relation. Will set
# the parent and update the index in the process.
#
# @example Append a document.
# person.posts << post
#
# @example Push a document.
# person.posts.push(post)
#
# @example Concat with other documents.
# person.posts.concat([ post_one, post_two ])
#
# @param [ Document, Array<Document> ] *args Any number of documents.
#
# @return [ Array<Document> ] The loaded docs.
#
# @since 2.0.0.beta.1
def <<(*args)
docs = args.flatten
return concat(docs) if docs.size > 1
if doc = docs.first
append(doc)
base.add_to_set(foreign_key => doc.send(metadata.primary_key))
if child_persistable?(doc)
doc.save
end
end
unsynced(base, foreign_key) and self
end
alias :push :<<
# Appends an array of documents to the relation. Performs a batch
# insert of the documents instead of persisting one at a time.
#
# @example Concat with other documents.
# person.posts.concat([ post_one, post_two ])
#
# @param [ Array<Document> ] documents The docs to add.
#
# @return [ Array<Document> ] The documents.
#
# @since 2.4.0
def concat(documents)
ids, docs, inserts = {}, [], []
documents.each do |doc|
next unless doc
append(doc)
if persistable? || _creating?
ids[doc.id] = true
save_or_delay(doc, docs, inserts)
else
existing = base.send(foreign_key)
unless existing.include?(doc.id)
existing.push(doc.id) and unsynced(base, foreign_key)
end
end
end
if persistable? || _creating?
base.push(foreign_key => ids.keys)
end
persist_delayed(docs, inserts)
self
end
# Build a new document from the attributes and append it to this
# relation without saving.
#
# @example Build a new document on the relation.
# person.posts.build(:title => "A new post")
#
# @overload build(attributes = {}, type = nil)
# @param [ Hash ] attributes The attributes of the new document.
# @param [ Class ] type The optional subclass to build.
#
# @overload build(attributes = {}, type = nil)
# @param [ Hash ] attributes The attributes of the new document.
# @param [ Class ] type The optional subclass to build.
#
# @return [ Document ] The new document.
#
# @since 2.0.0.beta.1
def build(attributes = {}, type = nil)
doc = Factory.build(type || klass, attributes)
base.send(foreign_key).push(doc.id)
append(doc)
doc.apply_post_processed_defaults
unsynced(doc, inverse_foreign_key)
yield(doc) if block_given?
doc
end
alias :new :build
# Delete the document from the relation. This will set the foreign key
# on the document to nil. If the dependent options on the relation are
# :delete or :destroy the appropriate removal will occur.
#
# @example Delete the document.
# person.posts.delete(post)
#
# @param [ Document ] document The document to remove.
#
# @return [ Document ] The matching document.
#
# @since 2.1.0
def delete(document)
doc = super
if doc && persistable?
base.pull(foreign_key => doc.send(metadata.primary_key))
target._unloaded = criteria
unsynced(base, foreign_key)
end
doc
end
# Removes all associations between the base document and the target
# documents by deleting the foreign keys and the references, orphaning
# the target documents in the process.
#
# @example Nullify the relation.
# person.preferences.nullify
#
# @since 2.0.0.rc.1
def nullify
target.each do |doc|
execute_callback :before_remove, doc
end
unless metadata.forced_nil_inverse?
criteria.pull(inverse_foreign_key => base.id)
end
if persistable?
base.set(foreign_key => base.send(foreign_key).clear)
end
after_remove_error = nil
many_to_many = target.clear do |doc|
unbind_one(doc)
unless metadata.forced_nil_inverse?
doc.changed_attributes.delete(inverse_foreign_key)
end
begin
execute_callback :after_remove, doc
rescue => e
after_remove_error = e
end
end
raise after_remove_error if after_remove_error
many_to_many
end
alias :nullify_all :nullify
alias :clear :nullify
alias :purge :nullify
# Substitutes the supplied target documents for the existing documents
# in the relation. If the new target is nil, perform the necessary
# deletion.
#
# @example Replace the relation.
# person.preferences.substitute([ new_post ])
#
# @param [ Array<Document> ] replacement The replacement target.
#
# @return [ Many ] The relation.
#
# @since 2.0.0.rc.1
def substitute(replacement)
purge
unless replacement.blank?
push(replacement.compact.uniq)
else
reset_unloaded
end
self
end
# Get a criteria for the documents without the default scoping
# applied.
#
# @example Get the unscoped criteria.
# person.preferences.unscoped
#
# @return [ Criteria ] The unscoped criteria.
#
# @since 2.4.0
def unscoped
klass.unscoped.any_in(_id: base.send(foreign_key))
end
private
# Appends the document to the target array, updating the index on the
# document at the same time.
#
# @example Append the document to the relation.
# relation.append(document)
#
# @param [ Document ] document The document to append to the target.
#
# @since 2.0.0.rc.1
def append(document)
execute_callback :before_add, document
target.push(document)
characterize_one(document)
bind_one(document)
execute_callback :after_add, document
end
# Instantiate the binding associated with this relation.
#
# @example Get the binding.
# relation.binding([ address ])
#
# @return [ Binding ] The binding.
#
# @since 2.0.0.rc.1
def binding
Bindings::Referenced::ManyToMany.new(base, target, metadata)
end
# Determine if the child document should be persisted.
#
# @api private
#
# @example Is the child persistable?
# relation.child_persistable?(doc)
#
# @param [ Document ] doc The document.
#
# @return [ true, false ] If the document can be persisted.
#
# @since 3.0.20
def child_persistable?(doc)
(persistable? || _creating?) &&
!(doc.persisted? && metadata.forced_nil_inverse?)
end
# Returns the criteria object for the target class with its documents set
# to target.
#
# @example Get a criteria for the relation.
# relation.criteria
#
# @return [ Criteria ] A new criteria.
def criteria
ManyToMany.criteria(metadata, base.send(foreign_key))
end
# Flag the base as unsynced with respect to the foreign key.
#
# @api private
#
# @example Flag as unsynced.
# relation.unsynced(doc, :preference_ids)
#
# @param [ Document ] doc The document to flag.
# @param [ Symbol ] key The key to flag on the document.
#
# @return [ true ] true.
#
# @since 3.0.0
def unsynced(doc, key)
doc.synced[key] = false
true
end
class << self
# Return the builder that is responsible for generating the documents
# that will be used by this relation.
#
# @example Get the builder.
# Referenced::ManyToMany.builder(meta, object)
#
# @param [ Document ] base The base document.
# @param [ Metadata ] meta The metadata of the relation.
# @param [ Document, Hash ] object A document or attributes to build
# with.
#
# @return [ Builder ] A new builder object.
#
# @since 2.0.0.rc.1
def builder(base, meta, object)
Builders::Referenced::ManyToMany.new(base, meta, object)
end
# Create the standard criteria for this relation given the supplied
# metadata and object.
#
# @example Get the criteria.
# Proxy.criteria(meta, object)
#
# @param [ Metadata ] metadata The relation metadata.
# @param [ Object ] object The object for the criteria.
# @param [ Class ] type The criteria class.
#
# @return [ Criteria ] The criteria.
#
# @since 2.1.0
def criteria(metadata, object, type = nil)
apply_ordering(
metadata.klass.all_of(
metadata.primary_key => { "$in" => object || [] }
), metadata
)
end
# Get the criteria that is used to eager load a relation of this
# type.
#
# @example Get the eager load criteria.
# Proxy.eager_load(metadata, criteria)
#
# @param [ Metadata ] metadata The relation metadata.
# @param [ Array<Object> ] ids The ids of the documents to load.
#
# @return [ Criteria ] The criteria to eager load the relation.
#
# @since 2.2.0
def eager_load(metadata, ids)
metadata.klass.any_in(_id: ids).each do |doc|
IdentityMap.set(doc)
end
end
# Returns true if the relation is an embedded one. In this case
# always false.
#
# @example Is this relation embedded?
# Referenced::ManyToMany.embedded?
#
# @return [ false ] Always false.
#
# @since 2.0.0.rc.1
def embedded?
false
end
# Get the foreign key for the provided name.
#
# @example Get the foreign key.
# Referenced::ManyToMany.foreign_key(:person)
#
# @param [ Symbol ] name The name.
#
# @return [ String ] The foreign key.
#
# @since 3.0.0
def foreign_key(name)
"#{name.to_s.singularize}#{foreign_key_suffix}"
end
# Get the default value for the foreign key.
#
# @example Get the default.
# Referenced::ManyToMany.foreign_key_default
#
# @return [ Array ] Always an empty array.
#
# @since 2.0.0.rc.1
def foreign_key_default
[]
end
# Returns the suffix of the foreign key field, either "_id" or "_ids".
#
# @example Get the suffix for the foreign key.
# Referenced::ManyToMany.foreign_key_suffix
#
# @return [ String ] "_ids"
#
# @since 2.0.0.rc.1
def foreign_key_suffix
"_ids"
end
# Returns the macro for this relation. Used mostly as a helper in
# reflection.
#
# @example Get the macro.
# Referenced::ManyToMany.macro
#
# @return [ Symbol ] :has_and_belongs_to_many
def macro
:has_and_belongs_to_many
end
# Return the nested builder that is responsible for generating the documents
# that will be used by this relation.
#
# @example Get the nested builder.
# Referenced::ManyToMany.builder(attributes, options)
#
# @param [ Metadata ] metadata The relation metadata.
# @param [ Hash ] attributes The attributes to build with.
# @param [ Hash ] options The options for the builder.
#
# @option options [ true, false ] :allow_destroy Can documents be
# deleted?
# @option options [ Integer ] :limit Max number of documents to
# create at once.
# @option options [ Proc, Symbol ] :reject_if If documents match this
# option then they are ignored.
# @option options [ true, false ] :update_only Only existing documents
# can be modified.
#
# @return [ NestedBuilder ] A newly instantiated nested builder object.
#
# @since 2.0.0.rc.1
def nested_builder(metadata, attributes, options)
Builders::NestedAttributes::Many.new(metadata, attributes, options)
end
# Get the path calculator for the supplied document.
#
# @example Get the path calculator.
# Proxy.path(document)
#
# @param [ Document ] document The document to calculate on.
#
# @return [ Root ] The root atomic path calculator.
#
# @since 2.1.0
def path(document)
Mongoid::Atomic::Paths::Root.new(document)
end
# Tells the caller if this relation is one that stores the foreign
# key on its own objects.
#
# @example Does this relation store a foreign key?
# Referenced::Many.stores_foreign_key?
#
# @return [ true ] Always true.
#
# @since 2.0.0.rc.1
def stores_foreign_key?
true
end
# Get the valid options allowed with this relation.
#
# @example Get the valid options.
# Relation.valid_options
#
# @return [ Array<Symbol> ] The valid options.
#
# @since 2.1.0
def valid_options
[
:after_add,
:after_remove,
:autosave,
:before_add,
:before_remove,
:dependent,
:foreign_key,
:index,
:order,
:primary_key
]
end
# Get the default validation setting for the relation. Determines if
# by default a validates associated will occur.
#
# @example Get the validation default.
# Proxy.validation_default
#
# @return [ true, false ] The validation default.
#
# @since 2.1.9
def validation_default
true
end
end
end
end
end
end
| bglusman/mongoid | lib/mongoid/relations/referenced/many_to_many.rb | Ruby | mit | 15,852 |
require File.expand_path('../helper', __FILE__)
class WebTest < Service::TestCase
def setup
@stubs = Faraday::Adapter::Test::Stubs.new
end
def test_push
svc = service({
'url' => 'http://monkey:secret@abc.com/foo/?a=1',
'secret' => ''
}, payload)
@stubs.post "/foo/" do |env|
assert_equal 'push', env[:request_headers]['x-github-event']
assert_match /^guid\-0\.\d+$/, env[:request_headers]['x-github-delivery']
assert_equal 'Basic bW9ua2V5OnNlY3JldA==', env[:request_headers]['authorization']
assert_match /form/, env[:request_headers]['content-type']
assert_equal 'abc.com', env[:url].host
params = Faraday::Utils.parse_nested_query(env[:url].query)
assert_equal({'a' => '1'}, params)
body = Faraday::Utils.parse_nested_query(env[:body])
assert_equal '1', body['a']
recv = JSON.parse(body['payload'])
assert_equal payload, recv
assert_nil env[:request_headers]['X-Hub-Signature']
assert_equal '1', body['a']
[200, {}, '']
end
svc.receive_event
end
def test_push_without_scheme
svc = service({
'url' => 'abc.com/foo/?a=1',
'secret' => ''
}, payload)
@stubs.post "/foo/" do |env|
assert_equal 'abc.com', env[:url].host
[200, {}, '']
end
svc.receive_event
end
def test_push_with_secret
svc = service({
'url' => 'http://abc.com/foo',
'secret' => 'monkey'
}, payload)
@stubs.post "/foo" do |env|
assert_nil env[:request_headers]['authorization']
assert_match /form/, env[:request_headers]['content-type']
assert_equal 'abc.com', env[:url].host
assert_equal 'sha1='+OpenSSL::HMAC.hexdigest(Service::Web::HMAC_DIGEST,
'monkey', env[:body]),
env[:request_headers]['X-Hub-Signature']
body = Faraday::Utils.parse_nested_query(env[:body])
recv = JSON.parse(body['payload'])
assert_equal payload, recv
[200, {}, '']
end
svc.receive_event
end
def test_push_as_json
svc = service({
'url' => 'http://monkey:secret@abc.com/foo?a=1',
'content_type' => 'json'
}, payload)
@stubs.post "/foo" do |env|
assert_equal 'Basic bW9ua2V5OnNlY3JldA==', env[:request_headers]['authorization']
params = Faraday::Utils.parse_nested_query(env[:url].query)
assert_equal({'a' => '1'}, params)
assert_match /json/, env[:request_headers]['content-type']
assert_equal 'abc.com', env[:url].host
assert_nil env[:request_headers]['X-Hub-Signature']
assert_equal payload, JSON.parse(env[:body])
[200, {}, '']
end
svc.receive_event
end
def test_push_as_json_with_secret
svc = service({
'url' => 'http://abc.com/foo',
'secret' => 'monkey',
'content_type' => 'json'
}, payload)
@stubs.post "/foo" do |env|
assert_nil env[:request_headers]['authorization']
assert_match /json/, env[:request_headers]['content-type']
assert_equal 'abc.com', env[:url].host
assert_equal 'sha1='+OpenSSL::HMAC.hexdigest(Service::Web::HMAC_DIGEST,
'monkey', env[:body]),
env[:request_headers]['X-Hub-Signature']
assert_equal payload, JSON.parse(env[:body])
[200, {}, '']
end
svc.receive_event
end
def test_log_data
data = {
'url' => 'http://user:pass@abc.com/def',
'secret' => 'monkey',
'content_type' => 'json'
}
svc = service(data, payload)
assert_equal 2, svc.log_data.size, svc.log_data.inspect
assert_equal 'http://user:********@abc.com/def', svc.log_data['url']
assert_equal data['content_type'], svc.log_data['content_type']
end
def test_log_message
data = {
'url' => 'http://abc.com/def',
'secret' => 'monkey',
'content_type' => 'json'
}
svc = service(data, payload)
assert_match /^\[[^\]]+\] 200 web\/push \{/, svc.log_message(200)
end
def service(*args)
super Service::Web, *args
end
end
| illan/github-services | test/web_test.rb | Ruby | mit | 4,120 |
// go run mksyscall.go -tags darwin,amd64,!go1.12 syscall_bsd.go syscall_darwin.go syscall_darwin_amd64.go
// Code generated by the command above; see README.md. DO NOT EDIT.
// +build darwin,amd64,!go1.12
package unix
import (
"syscall"
"unsafe"
)
var _ syscall.Errno
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func getgroups(ngid int, gid *_Gid_t) (n int, err error) {
r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0)
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func setgroups(ngid int, gid *_Gid_t) (err error) {
_, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) {
r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0)
wpid = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) {
r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)))
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) {
_, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) {
_, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func socket(domain int, typ int, proto int) (fd int, err error) {
r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto))
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) {
_, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) {
_, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) {
_, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) {
_, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Shutdown(s int, how int) (err error) {
_, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) {
_, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) {
var _p0 unsafe.Pointer
if len(p) > 0 {
_p0 = unsafe.Pointer(&p[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) {
var _p0 unsafe.Pointer
if len(buf) > 0 {
_p0 = unsafe.Pointer(&buf[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
_, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) {
r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) {
r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) {
r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) {
var _p0 unsafe.Pointer
if len(mib) > 0 {
_p0 = unsafe.Pointer(&mib[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
_, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func utimes(path string, timeval *[2]Timeval) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func futimes(fd int, timeval *[2]Timeval) (err error) {
_, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func fcntl(fd int, cmd int, arg int) (val int, err error) {
r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg))
val = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func poll(fds *PollFd, nfds int, timeout int) (n int, err error) {
r0, _, e1 := Syscall(SYS_POLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Madvise(b []byte, behav int) (err error) {
var _p0 unsafe.Pointer
if len(b) > 0 {
_p0 = unsafe.Pointer(&b[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
_, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mlock(b []byte) (err error) {
var _p0 unsafe.Pointer
if len(b) > 0 {
_p0 = unsafe.Pointer(&b[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
_, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mlockall(flags int) (err error) {
_, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mprotect(b []byte, prot int) (err error) {
var _p0 unsafe.Pointer
if len(b) > 0 {
_p0 = unsafe.Pointer(&b[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
_, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Msync(b []byte, flags int) (err error) {
var _p0 unsafe.Pointer
if len(b) > 0 {
_p0 = unsafe.Pointer(&b[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
_, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Munlock(b []byte) (err error) {
var _p0 unsafe.Pointer
if len(b) > 0 {
_p0 = unsafe.Pointer(&b[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
_, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Munlockall() (err error) {
_, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) {
_, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func getattrlist(path *byte, list unsafe.Pointer, buf unsafe.Pointer, size uintptr, options int) (err error) {
_, _, e1 := Syscall6(SYS_GETATTRLIST, uintptr(unsafe.Pointer(path)), uintptr(list), uintptr(buf), uintptr(size), uintptr(options), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func pipe() (r int, w int, err error) {
r0, r1, e1 := RawSyscall(SYS_PIPE, 0, 0, 0)
r = int(r0)
w = int(r1)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func getxattr(path string, attr string, dest *byte, size int, position uint32, options int) (sz int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(attr)
if err != nil {
return
}
r0, _, e1 := Syscall6(SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(dest)), uintptr(size), uintptr(position), uintptr(options))
sz = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func fgetxattr(fd int, attr string, dest *byte, size int, position uint32, options int) (sz int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(attr)
if err != nil {
return
}
r0, _, e1 := Syscall6(SYS_FGETXATTR, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(dest)), uintptr(size), uintptr(position), uintptr(options))
sz = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func setxattr(path string, attr string, data *byte, size int, position uint32, options int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(attr)
if err != nil {
return
}
_, _, e1 := Syscall6(SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(data)), uintptr(size), uintptr(position), uintptr(options))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func fsetxattr(fd int, attr string, data *byte, size int, position uint32, options int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(attr)
if err != nil {
return
}
_, _, e1 := Syscall6(SYS_FSETXATTR, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(data)), uintptr(size), uintptr(position), uintptr(options))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func removexattr(path string, attr string, options int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(attr)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_REMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(options))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func fremovexattr(fd int, attr string, options int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(attr)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_FREMOVEXATTR, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(options))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func listxattr(path string, dest *byte, size int, options int) (sz int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
r0, _, e1 := Syscall6(SYS_LISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(dest)), uintptr(size), uintptr(options), 0, 0)
sz = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func flistxattr(fd int, dest *byte, size int, options int) (sz int, err error) {
r0, _, e1 := Syscall6(SYS_FLISTXATTR, uintptr(fd), uintptr(unsafe.Pointer(dest)), uintptr(size), uintptr(options), 0, 0)
sz = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func setattrlist(path *byte, list unsafe.Pointer, buf unsafe.Pointer, size uintptr, options int) (err error) {
_, _, e1 := Syscall6(SYS_SETATTRLIST, uintptr(unsafe.Pointer(path)), uintptr(list), uintptr(buf), uintptr(size), uintptr(options), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func kill(pid int, signum int, posix int) (err error) {
_, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), uintptr(posix))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func ioctl(fd int, req uint, arg uintptr) (err error) {
_, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func sendfile(infd int, outfd int, offset int64, len *int64, hdtr unsafe.Pointer, flags int) (err error) {
_, _, e1 := Syscall6(SYS_SENDFILE, uintptr(infd), uintptr(outfd), uintptr(offset), uintptr(unsafe.Pointer(len)), uintptr(hdtr), uintptr(flags))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Access(path string, mode uint32) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Adjtime(delta *Timeval, olddelta *Timeval) (err error) {
_, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Chdir(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Chflags(path string, flags int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Chmod(path string, mode uint32) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Chown(path string, uid int, gid int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Chroot(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Close(fd int) (err error) {
_, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Dup(fd int) (nfd int, err error) {
r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0)
nfd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Dup2(from int, to int) (err error) {
_, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Exchangedata(path1 string, path2 string, options int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path1)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(path2)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_EXCHANGEDATA, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(options))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Exit(code int) {
Syscall(SYS_EXIT, uintptr(code), 0, 0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fchdir(fd int) (err error) {
_, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fchflags(fd int, flags int) (err error) {
_, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fchmod(fd int, mode uint32) (err error) {
_, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fchown(fd int, uid int, gid int) (err error) {
_, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Flock(fd int, how int) (err error) {
_, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fpathconf(fd int, name int) (val int, err error) {
r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0)
val = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fsync(fd int) (err error) {
_, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Ftruncate(fd int, length int64) (err error) {
_, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getdtablesize() (size int) {
r0, _, _ := Syscall(SYS_GETDTABLESIZE, 0, 0, 0)
size = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getegid() (egid int) {
r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0)
egid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Geteuid() (uid int) {
r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0)
uid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getgid() (gid int) {
r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0)
gid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getpgid(pid int) (pgid int, err error) {
r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0)
pgid = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getpgrp() (pgrp int) {
r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0)
pgrp = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getpid() (pid int) {
r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0)
pid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getppid() (ppid int) {
r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0)
ppid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getpriority(which int, who int) (prio int, err error) {
r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0)
prio = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getrlimit(which int, lim *Rlimit) (err error) {
_, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getrusage(who int, rusage *Rusage) (err error) {
_, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getsid(pid int) (sid int, err error) {
r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0)
sid = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getuid() (uid int) {
r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0)
uid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Issetugid() (tainted bool) {
r0, _, _ := RawSyscall(SYS_ISSETUGID, 0, 0, 0)
tainted = bool(r0 != 0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Kqueue() (fd int, err error) {
r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0)
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Lchown(path string, uid int, gid int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Link(path string, link string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(link)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(link)
if err != nil {
return
}
_, _, e1 := Syscall6(SYS_LINKAT, uintptr(pathfd), uintptr(unsafe.Pointer(_p0)), uintptr(linkfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Listen(s int, backlog int) (err error) {
_, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mkdir(path string, mode uint32) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mkdirat(dirfd int, path string, mode uint32) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mkfifo(path string, mode uint32) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mknod(path string, mode uint32, dev int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Open(path string, mode int, perm uint32) (fd int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm))
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Openat(dirfd int, path string, mode int, perm uint32) (fd int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm), 0, 0)
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Pathconf(path string, name int) (val int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0)
val = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Pread(fd int, p []byte, offset int64) (n int, err error) {
var _p0 unsafe.Pointer
if len(p) > 0 {
_p0 = unsafe.Pointer(&p[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0)
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Pwrite(fd int, p []byte, offset int64) (n int, err error) {
var _p0 unsafe.Pointer
if len(p) > 0 {
_p0 = unsafe.Pointer(&p[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0)
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func read(fd int, p []byte) (n int, err error) {
var _p0 unsafe.Pointer
if len(p) > 0 {
_p0 = unsafe.Pointer(&p[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Readlink(path string, buf []byte) (n int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
var _p1 unsafe.Pointer
if len(buf) > 0 {
_p1 = unsafe.Pointer(&buf[0])
} else {
_p1 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
var _p1 unsafe.Pointer
if len(buf) > 0 {
_p1 = unsafe.Pointer(&buf[0])
} else {
_p1 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0)
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Rename(from string, to string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(from)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(to)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Renameat(fromfd int, from string, tofd int, to string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(from)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(to)
if err != nil {
return
}
_, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Revoke(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Rmdir(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Seek(fd int, offset int64, whence int) (newoffset int64, err error) {
r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence))
newoffset = int64(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) {
_, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setegid(egid int) (err error) {
_, _, e1 := Syscall(SYS_SETEGID, uintptr(egid), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Seteuid(euid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setgid(gid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setlogin(name string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(name)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setpgid(pid int, pgid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setpriority(which int, who int, prio int) (err error) {
_, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setprivexec(flag int) (err error) {
_, _, e1 := Syscall(SYS_SETPRIVEXEC, uintptr(flag), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setregid(rgid int, egid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setreuid(ruid int, euid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setrlimit(which int, lim *Rlimit) (err error) {
_, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setsid() (pid int, err error) {
r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0)
pid = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Settimeofday(tp *Timeval) (err error) {
_, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setuid(uid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Symlink(path string, link string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(link)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(oldpath)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(newpath)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Sync() (err error) {
_, _, e1 := Syscall(SYS_SYNC, 0, 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Truncate(path string, length int64) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Umask(newmask int) (oldmask int) {
r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0)
oldmask = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Undelete(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_UNDELETE, uintptr(unsafe.Pointer(_p0)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Unlink(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Unlinkat(dirfd int, path string, flags int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Unmount(path string, flags int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func write(fd int, p []byte) (n int, err error) {
var _p0 unsafe.Pointer
if len(p) > 0 {
_p0 = unsafe.Pointer(&p[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) {
r0, _, e1 := Syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos))
ret = uintptr(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func munmap(addr uintptr, length uintptr) (err error) {
_, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func readlen(fd int, buf *byte, nbuf int) (n int, err error) {
r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func writelen(fd int, buf *byte, nbuf int) (n int, err error) {
r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func gettimeofday(tp *Timeval) (sec int64, usec int32, err error) {
r0, r1, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0)
sec = int64(r0)
usec = int32(r1)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fstat(fd int, stat *Stat_t) (err error) {
_, _, e1 := Syscall(SYS_FSTAT64, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall6(SYS_FSTATAT64, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fstatfs(fd int, stat *Statfs_t) (err error) {
_, _, e1 := Syscall(SYS_FSTATFS64, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) {
var _p0 unsafe.Pointer
if len(buf) > 0 {
_p0 = unsafe.Pointer(&buf[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall6(SYS_GETDIRENTRIES64, uintptr(fd), uintptr(_p0), uintptr(len(buf)), uintptr(unsafe.Pointer(basep)), 0, 0)
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func getfsstat(buf unsafe.Pointer, size uintptr, flags int) (n int, err error) {
r0, _, e1 := Syscall(SYS_GETFSSTAT64, uintptr(buf), uintptr(size), uintptr(flags))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Lstat(path string, stat *Stat_t) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_LSTAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Stat(path string, stat *Stat_t) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_STAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Statfs(path string, stat *Statfs_t) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_STATFS64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
| olihey/rclone | vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.1_11.go | GO | mit | 43,816 |
/* Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.*/
(function(a){function b(){if(this.isDisposed)throw new Error(fb)}function c(a,b){if(gb&&b.stack&&"object"==typeof a&&null!==a&&a.stack&&-1===a.stack.indexOf(kb)){for(var c=[],e=b;e;e=e.source)e.stack&&c.unshift(e.stack);c.unshift(a.stack);var f=c.join("\n"+kb+"\n");a.stack=d(f)}}function d(a){for(var b=a.split("\n"),c=[],d=0,g=b.length;g>d;d++){var h=b[d];e(h)||f(h)||!h||c.push(h)}return c.join("\n")}function e(a){var b=h(a);if(!b)return!1;var c=b[0],d=b[1];return c===ib&&d>=jb&&bd>=d}function f(a){return-1!==a.indexOf("(module.js:")||-1!==a.indexOf("(node.js:")}function g(){if(gb)try{throw new Error}catch(a){var b=a.stack.split("\n"),c=b[0].indexOf("@")>0?b[1]:b[2],d=h(c);if(!d)return;return ib=d[0],d[1]}}function h(a){var b=/at .+ \((.+):(\d+):(?:\d+)\)$/.exec(a);if(b)return[b[1],Number(b[2])];var c=/at ([^ ]+):(\d+):(?:\d+)$/.exec(a);if(c)return[c[1],Number(c[2])];var d=/.*@(.+):(\d+)$/.exec(a);return d?[d[1],Number(d[2])]:void 0}function i(a){var b=typeof a;return a&&("function"==b||"object"==b)||!1}function j(a){var b=[];if(!i(a))return b;Kb.nonEnumArgs&&a.length&&Lb(a)&&(a=Nb.call(a));var c=Kb.enumPrototypes&&"function"==typeof a,d=Kb.enumErrorProps&&(a===Eb||a instanceof Error);for(var e in a)c&&"prototype"==e||d&&("message"==e||"name"==e)||b.push(e);if(Kb.nonEnumShadows&&a!==Fb){var f=a.constructor,g=-1,h=Ib.length;if(a===(f&&f.prototype))var j=a===Gb?Ab:a===Eb?vb:Bb.call(a),k=Jb[j];for(;++g<h;)e=Ib[g],k&&k[e]||!Cb.call(a,e)||b.push(e)}return b}function k(a,b,c){for(var d=-1,e=c(a),f=e.length;++d<f;){var g=e[d];if(b(a[g],g,a)===!1)break}return a}function l(a,b){return k(a,b,j)}function m(a){return"function"!=typeof a.toString&&"string"==typeof(a+"")}function n(a,b,c,d){if(a===b)return 0!==a||1/a==1/b;var e=typeof a,f=typeof b;if(a===a&&(null==a||null==b||"function"!=e&&"object"!=e&&"function"!=f&&"object"!=f))return!1;var g=Bb.call(a),h=Bb.call(b);if(g==rb&&(g=yb),h==rb&&(h=yb),g!=h)return!1;switch(g){case tb:case ub:return+a==+b;case xb:return a!=+a?b!=+b:0==a?1/a==1/b:a==+b;case zb:case Ab:return a==String(b)}var i=g==sb;if(!i){if(g!=yb||!Kb.nodeClass&&(m(a)||m(b)))return!1;var j=!Kb.argsObject&&Lb(a)?Object:a.constructor,k=!Kb.argsObject&&Lb(b)?Object:b.constructor;if(!(j==k||Cb.call(a,"constructor")&&Cb.call(b,"constructor")||db(j)&&j instanceof j&&db(k)&&k instanceof k||!("constructor"in a&&"constructor"in b)))return!1}c||(c=[]),d||(d=[]);for(var o=c.length;o--;)if(c[o]==a)return d[o]==b;var p=0,q=!0;if(c.push(a),d.push(b),i){if(o=a.length,p=b.length,q=p==o)for(;p--;){var r=b[p];if(!(q=n(a[p],r,c,d)))break}}else l(b,function(b,e,f){return Cb.call(f,e)?(p++,q=Cb.call(a,e)&&n(a[e],b,c,d)):void 0}),q&&l(a,function(a,b,c){return Cb.call(c,b)?q=--p>-1:void 0});return c.pop(),d.pop(),q}function o(a,b){return 1===a.length&&Array.isArray(a[b])?a[b]:Nb.call(a)}function p(a,b){for(var c=new Array(a),d=0;a>d;d++)c[d]=b();return c}function q(a,b){this.id=a,this.value=b}function r(){this._s=s}function t(){this._s=s,this._l=s.length,this._i=0}function u(a){this._a=a}function v(a){this._a=a,this._l=z(a),this._i=0}function w(a){return"number"==typeof a&&R.isFinite(a)}function x(b){var c,d=b[lb];if(!d&&"string"==typeof b)return c=new r(b),c[lb]();if(!d&&b.length!==a)return c=new u(b),c[lb]();if(!d)throw new TypeError("Object is not iterable");return b[lb]()}function y(a){var b=+a;return 0===b?b:isNaN(b)?b:0>b?-1:1}function z(a){var b=+a.length;return isNaN(b)?0:0!==b&&w(b)?(b=y(b)*Math.floor(Math.abs(b)),0>=b?0:b>Bc?Bc:b):b}function A(a,b){return Y(a)||(a=ec),new Vc(function(c){var d=0,e=b.length;return a.scheduleRecursive(function(a){e>d?(c.onNext(b[d++]),a()):c.onCompleted()})})}function B(a,b){return new Vc(function(c){var d=new Zb,e=new $b;return e.setDisposable(d),d.setDisposable(a.subscribe(c.onNext.bind(c),function(a){var d,f;try{f=b(a)}catch(g){return void c.onError(g)}cb(f)&&(f=Oc(f)),d=new Zb,e.setDisposable(d),d.setDisposable(f.subscribe(c))},c.onCompleted.bind(c))),e},a)}function C(a,b){var c=this;return new Vc(function(d){var e=0,f=a.length;return c.subscribe(function(c){if(f>e){var g,h=a[e++];try{g=b(c,h)}catch(i){return void d.onError(i)}d.onNext(g)}else d.onCompleted()},d.onError.bind(d),d.onCompleted.bind(d))},c)}function D(a,b,c){return a.map(function(d,e){var f=b.call(c,d,e,a);return cb(f)&&(f=Oc(f)),(ob(f)||nb(f))&&(f=Cc(f)),f}).concatAll()}function E(a,b,c){return a.map(function(d,e){var f=b.call(c,d,e,a);return cb(f)&&(f=Oc(f)),(ob(f)||nb(f))&&(f=Cc(f)),f}).mergeAll()}function F(a){var b=function(){this.cancelBubble=!0},c=function(){if(this.bubbledKeyCode=this.keyCode,this.ctrlKey)try{this.keyCode=0}catch(a){}this.defaultPrevented=!0,this.returnValue=!1,this.modified=!0};if(a||(a=R.event),!a.target)switch(a.target=a.target||a.srcElement,"mouseover"==a.type&&(a.relatedTarget=a.fromElement),"mouseout"==a.type&&(a.relatedTarget=a.toElement),a.stopPropagation||(a.stopPropagation=b,a.preventDefault=c),a.type){case"keypress":var d="charCode"in a?a.charCode:a.keyCode;10==d?(d=0,a.keyCode=13):13==d||27==d?d=0:3==d&&(d=99),a.charCode=d,a.keyChar=a.charCode?String.fromCharCode(a.charCode):""}return a}function G(a,b,c){if(a.addEventListener)return a.addEventListener(b,c,!1),Xb(function(){a.removeEventListener(b,c,!1)});if(a.attachEvent){var d=function(a){c(F(a))};return a.attachEvent("on"+b,d),Xb(function(){a.detachEvent("on"+b,d)})}return a["on"+b]=c,Xb(function(){a["on"+b]=null})}function H(a,b,c){var d=new Ub;if("[object NodeList]"===Object.prototype.toString.call(a))for(var e=0,f=a.length;f>e;e++)d.add(H(a.item(e),b,c));else a&&d.add(G(a,b,c));return d}function I(a,b){return new Vc(function(c){return b.scheduleWithAbsolute(a,function(){c.onNext(0),c.onCompleted()})})}function J(a,b,c){return new Vc(function(d){var e=0,f=a,g=bc(b);return c.scheduleRecursiveWithAbsolute(f,function(a){if(g>0){var b=c.now();f+=g,b>=f&&(f=b+g)}d.onNext(e++),a(f)})})}function K(a,b){return new Vc(function(c){return b.scheduleWithRelative(bc(a),function(){c.onNext(0),c.onCompleted()})})}function L(a,b,c){return a===b?new Vc(function(a){return c.schedulePeriodicWithState(0,b,function(b){return a.onNext(b),b+1})}):zc(function(){return J(c.now()+a,b,c)})}function M(a,b,c){return new Vc(function(d){var e,f=!1,g=new $b,h=null,i=[],j=!1;return e=a.materialize().timestamp(c).subscribe(function(a){var e,k;"E"===a.value.kind?(i=[],i.push(a),h=a.value.exception,k=!j):(i.push({value:a.value,timestamp:a.timestamp+b}),k=!f,f=!0),k&&(null!==h?d.onError(h):(e=new Zb,g.setDisposable(e),e.setDisposable(c.scheduleRecursiveWithRelative(b,function(a){var b,e,g,k;if(null===h){j=!0;do g=null,i.length>0&&i[0].timestamp-c.now()<=0&&(g=i.shift().value),null!==g&&g.accept(d);while(null!==g);k=!1,e=0,i.length>0?(k=!0,e=Math.max(0,i[0].timestamp-c.now())):f=!1,b=h,j=!1,null!==b?d.onError(b):k&&a(e)}}))))}),new Ub(e,g)},a)}function N(a,b,c){return zc(function(){return M(a,b-c.now(),c)})}function O(a,b){return new Vc(function(c){function d(){g&&(g=!1,c.onNext(f)),e&&c.onCompleted()}var e,f,g;return new Ub(a.subscribe(function(a){g=!0,f=a},c.onError.bind(c),function(){e=!0}),b.subscribe(d,c.onError.bind(c),d))},a)}function P(a,b,c){return new Vc(function(d){function e(a,b){j[b]=a;var e;if(g[b]=!0,h||(h=g.every(Z))){if(f)return void d.onError(f);try{e=c.apply(null,j)}catch(k){return void d.onError(k)}d.onNext(e)}i&&j[1]&&d.onCompleted()}var f,g=[!1,!1],h=!1,i=!1,j=new Array(2);return new Ub(a.subscribe(function(a){e(a,0)},function(a){j[1]?d.onError(a):f=a},function(){i=!0,j[1]&&d.onCompleted()}),b.subscribe(function(a){e(a,1)},d.onError.bind(d),function(){i=!0,e(!0,1)}))},a)}var Q={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},R=Q[typeof window]&&window||this,S=Q[typeof exports]&&exports&&!exports.nodeType&&exports,T=Q[typeof module]&&module&&!module.nodeType&&module,U=T&&T.exports===S&&S,V=Q[typeof global]&&global;!V||V.global!==V&&V.window!==V||(R=V);var W={internals:{},config:{Promise:R.Promise},helpers:{}},X=W.helpers.noop=function(){},Y=(W.helpers.notDefined=function(a){return"undefined"==typeof a},W.helpers.isScheduler=function(a){return a instanceof W.Scheduler}),Z=W.helpers.identity=function(a){return a},$=(W.helpers.pluck=function(a){return function(b){return b[a]}},W.helpers.just=function(a){return function(){return a}},W.helpers.defaultNow=function(){return Date.now?Date.now:function(){return+new Date}}()),_=W.helpers.defaultComparer=function(a,b){return Mb(a,b)},ab=W.helpers.defaultSubComparer=function(a,b){return a>b?1:b>a?-1:0},bb=(W.helpers.defaultKeySerializer=function(a){return a.toString()},W.helpers.defaultError=function(a){throw a}),cb=W.helpers.isPromise=function(a){return!!a&&"function"==typeof a.then},db=(W.helpers.asArray=function(){return Array.prototype.slice.call(arguments)},W.helpers.not=function(a){return!a},W.helpers.isFunction=function(){var a=function(a){return"function"==typeof a||!1};return a(/x/)&&(a=function(a){return"function"==typeof a&&"[object Function]"==Bb.call(a)}),a}()),eb="Argument out of range",fb="Object has been disposed";W.config.longStackSupport=!1;var gb=!1;try{throw new Error}catch(hb){gb=!!hb.stack}var ib,jb=g(),kb="From previous event:",lb="function"==typeof Symbol&&Symbol.iterator||"_es6shim_iterator_";R.Set&&"function"==typeof(new R.Set)["@@iterator"]&&(lb="@@iterator");var mb=W.doneEnumerator={done:!0,value:a},nb=W.helpers.isIterable=function(b){return b[lb]!==a},ob=W.helpers.isArrayLike=function(b){return b&&b.length!==a};W.helpers.iterator=lb;var pb,qb=W.helpers.deprecate=function(){},rb="[object Arguments]",sb="[object Array]",tb="[object Boolean]",ub="[object Date]",vb="[object Error]",wb="[object Function]",xb="[object Number]",yb="[object Object]",zb="[object RegExp]",Ab="[object String]",Bb=Object.prototype.toString,Cb=Object.prototype.hasOwnProperty,Db=Bb.call(arguments)==rb,Eb=Error.prototype,Fb=Object.prototype,Gb=String.prototype,Hb=Fb.propertyIsEnumerable;Hb||(Hb=Fb.propertyIsEnumerable=function(a){for(var b in this)if(b===a)return!0;return!1});try{pb=!(Bb.call(document)==yb&&!({toString:0}+""))}catch(hb){pb=!0}var Ib=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Jb={};Jb[sb]=Jb[ub]=Jb[xb]={constructor:!0,toLocaleString:!0,toString:!0,valueOf:!0},Jb[tb]=Jb[Ab]={constructor:!0,toString:!0,valueOf:!0},Jb[vb]=Jb[wb]=Jb[zb]={constructor:!0,toString:!0},Jb[yb]={constructor:!0};var Kb={};!function(){var a=function(){this.x=1},b=[];a.prototype={valueOf:1,y:1};for(var c in new a)b.push(c);for(c in arguments);Kb.enumErrorProps=Hb.call(Eb,"message")||Hb.call(Eb,"name"),Kb.enumPrototypes=Hb.call(a,"prototype"),Kb.nonEnumArgs=0!=c,Kb.nonEnumShadows=!/valueOf/.test(b)}(1);var Lb=function(a){return a&&"object"==typeof a?Bb.call(a)==rb:!1};Db||(Lb=function(a){return a&&"object"==typeof a?Cb.call(a,"callee"):!1});{var Mb=W.internals.isEqual=function(a,b){return n(a,b,[],[])},Nb=Array.prototype.slice,Ob=({}.hasOwnProperty,this.inherits=W.internals.inherits=function(a,b){function c(){this.constructor=a}c.prototype=b.prototype,a.prototype=new c}),Pb=W.internals.addProperties=function(a){for(var b=Nb.call(arguments,1),c=0,d=b.length;d>c;c++){var e=b[c];for(var f in e)a[f]=e[f]}};W.internals.addRef=function(a,b){return new Vc(function(c){return new Ub(b.getDisposable(),a.subscribe(c))})}}Function.prototype.bind||(Function.prototype.bind=function(a){var b=this,c=Nb.call(arguments,1),d=function(){function e(){}if(this instanceof d){e.prototype=b.prototype;var f=new e,g=b.apply(f,c.concat(Nb.call(arguments)));return Object(g)===g?g:f}return b.apply(a,c.concat(Nb.call(arguments)))};return d}),Array.prototype.forEach||(Array.prototype.forEach=function(a,b){var c,d;if(null==this)throw new TypeError(" this is null or not defined");var e=Object(this),f=e.length>>>0;if("function"!=typeof a)throw new TypeError(a+" is not a function");for(arguments.length>1&&(c=b),d=0;f>d;){var g;d in e&&(g=e[d],a.call(c,g,d,e)),d++}});var Qb=Object("a"),Rb="a"!=Qb[0]||!(0 in Qb);Array.prototype.every||(Array.prototype.every=function(a){var b=Object(this),c=Rb&&{}.toString.call(this)==Ab?this.split(""):b,d=c.length>>>0,e=arguments[1];if({}.toString.call(a)!=wb)throw new TypeError(a+" is not a function");for(var f=0;d>f;f++)if(f in c&&!a.call(e,c[f],f,b))return!1;return!0}),Array.prototype.map||(Array.prototype.map=function(a){var b=Object(this),c=Rb&&{}.toString.call(this)==Ab?this.split(""):b,d=c.length>>>0,e=Array(d),f=arguments[1];if({}.toString.call(a)!=wb)throw new TypeError(a+" is not a function");for(var g=0;d>g;g++)g in c&&(e[g]=a.call(f,c[g],g,b));return e}),Array.prototype.filter||(Array.prototype.filter=function(a){for(var b,c=[],d=new Object(this),e=0,f=d.length>>>0;f>e;e++)b=d[e],e in d&&a.call(arguments[1],b,e,d)&&c.push(b);return c}),Array.isArray||(Array.isArray=function(a){return{}.toString.call(a)==sb}),Array.prototype.indexOf||(Array.prototype.indexOf=function(a){var b=Object(this),c=b.length>>>0;if(0===c)return-1;var d=0;if(arguments.length>1&&(d=Number(arguments[1]),d!==d?d=0:0!==d&&1/0!=d&&d!==-1/0&&(d=(d>0||-1)*Math.floor(Math.abs(d)))),d>=c)return-1;for(var e=d>=0?d:Math.max(c-Math.abs(d),0);c>e;e++)if(e in b&&b[e]===a)return e;return-1}),q.prototype.compareTo=function(a){var b=this.value.compareTo(a.value);return 0===b&&(b=this.id-a.id),b};var Sb=W.internals.PriorityQueue=function(a){this.items=new Array(a),this.length=0},Tb=Sb.prototype;Tb.isHigherPriority=function(a,b){return this.items[a].compareTo(this.items[b])<0},Tb.percolate=function(a){if(!(a>=this.length||0>a)){var b=a-1>>1;if(!(0>b||b===a)&&this.isHigherPriority(a,b)){var c=this.items[a];this.items[a]=this.items[b],this.items[b]=c,this.percolate(b)}}},Tb.heapify=function(a){if(+a||(a=0),!(a>=this.length||0>a)){var b=2*a+1,c=2*a+2,d=a;if(b<this.length&&this.isHigherPriority(b,d)&&(d=b),c<this.length&&this.isHigherPriority(c,d)&&(d=c),d!==a){var e=this.items[a];this.items[a]=this.items[d],this.items[d]=e,this.heapify(d)}}},Tb.peek=function(){return this.items[0].value},Tb.removeAt=function(a){this.items[a]=this.items[--this.length],delete this.items[this.length],this.heapify()},Tb.dequeue=function(){var a=this.peek();return this.removeAt(0),a},Tb.enqueue=function(a){var b=this.length++;this.items[b]=new q(Sb.count++,a),this.percolate(b)},Tb.remove=function(a){for(var b=0;b<this.length;b++)if(this.items[b].value===a)return this.removeAt(b),!0;return!1},Sb.count=0;var Ub=W.CompositeDisposable=function(){this.disposables=o(arguments,0),this.isDisposed=!1,this.length=this.disposables.length},Vb=Ub.prototype;Vb.add=function(a){this.isDisposed?a.dispose():(this.disposables.push(a),this.length++)},Vb.remove=function(a){var b=!1;if(!this.isDisposed){var c=this.disposables.indexOf(a);-1!==c&&(b=!0,this.disposables.splice(c,1),this.length--,a.dispose())}return b},Vb.dispose=function(){if(!this.isDisposed){this.isDisposed=!0;var a=this.disposables.slice(0);this.disposables=[],this.length=0;for(var b=0,c=a.length;c>b;b++)a[b].dispose()}},Vb.toArray=function(){return this.disposables.slice(0)};var Wb=W.Disposable=function(a){this.isDisposed=!1,this.action=a||X};Wb.prototype.dispose=function(){this.isDisposed||(this.action(),this.isDisposed=!0)};var Xb=Wb.create=function(a){return new Wb(a)},Yb=Wb.empty={dispose:X},Zb=W.SingleAssignmentDisposable=function(){function a(){this.isDisposed=!1,this.current=null}var b=a.prototype;return b.getDisposable=function(){return this.current},b.setDisposable=function(a){var b,c=this.isDisposed;c||(b=this.current,this.current=a),b&&b.dispose(),c&&a&&a.dispose()},b.dispose=function(){var a;this.isDisposed||(this.isDisposed=!0,a=this.current,this.current=null),a&&a.dispose()},a}(),$b=W.SerialDisposable=Zb,_b=(W.RefCountDisposable=function(){function a(a){this.disposable=a,this.disposable.count++,this.isInnerDisposed=!1}function b(a){this.underlyingDisposable=a,this.isDisposed=!1,this.isPrimaryDisposed=!1,this.count=0}return a.prototype.dispose=function(){this.disposable.isDisposed||this.isInnerDisposed||(this.isInnerDisposed=!0,this.disposable.count--,0===this.disposable.count&&this.disposable.isPrimaryDisposed&&(this.disposable.isDisposed=!0,this.disposable.underlyingDisposable.dispose()))},b.prototype.dispose=function(){this.isDisposed||this.isPrimaryDisposed||(this.isPrimaryDisposed=!0,0===this.count&&(this.isDisposed=!0,this.underlyingDisposable.dispose()))},b.prototype.getDisposable=function(){return this.isDisposed?Yb:new a(this)},b}(),W.internals.ScheduledItem=function(a,b,c,d,e){this.scheduler=a,this.state=b,this.action=c,this.dueTime=d,this.comparer=e||ab,this.disposable=new Zb});_b.prototype.invoke=function(){this.disposable.setDisposable(this.invokeCore())},_b.prototype.compareTo=function(a){return this.comparer(this.dueTime,a.dueTime)},_b.prototype.isCancelled=function(){return this.disposable.isDisposed},_b.prototype.invokeCore=function(){return this.action(this.scheduler,this.state)};var ac=W.Scheduler=function(){function a(a,b,c,d){this.now=a,this._schedule=b,this._scheduleRelative=c,this._scheduleAbsolute=d}function b(a,b){return b(),Yb}var c=a.prototype;return c.schedule=function(a){return this._schedule(a,b)},c.scheduleWithState=function(a,b){return this._schedule(a,b)},c.scheduleWithRelative=function(a,c){return this._scheduleRelative(c,a,b)},c.scheduleWithRelativeAndState=function(a,b,c){return this._scheduleRelative(a,b,c)},c.scheduleWithAbsolute=function(a,c){return this._scheduleAbsolute(c,a,b)},c.scheduleWithAbsoluteAndState=function(a,b,c){return this._scheduleAbsolute(a,b,c)},a.now=$,a.normalize=function(a){return 0>a&&(a=0),a},a}(),bc=ac.normalize;!function(a){function b(a,b){var c=b.first,d=b.second,e=new Ub,f=function(b){d(b,function(b){var c=!1,d=!1,g=a.scheduleWithState(b,function(a,b){return c?e.remove(g):d=!0,f(b),Yb});d||(e.add(g),c=!0)})};return f(c),e}function c(a,b,c){var d=b.first,e=b.second,f=new Ub,g=function(b){e(b,function(b,d){var e=!1,h=!1,i=a[c].call(a,b,d,function(a,b){return e?f.remove(i):h=!0,g(b),Yb});h||(f.add(i),e=!0)})};return g(d),f}function d(a,b){a(function(c){b(a,c)})}a.scheduleRecursive=function(a){return this.scheduleRecursiveWithState(a,function(a,b){a(function(){b(a)})})},a.scheduleRecursiveWithState=function(a,c){return this.scheduleWithState({first:a,second:c},b)},a.scheduleRecursiveWithRelative=function(a,b){return this.scheduleRecursiveWithRelativeAndState(b,a,d)},a.scheduleRecursiveWithRelativeAndState=function(a,b,d){return this._scheduleRelative({first:a,second:d},b,function(a,b){return c(a,b,"scheduleWithRelativeAndState")})},a.scheduleRecursiveWithAbsolute=function(a,b){return this.scheduleRecursiveWithAbsoluteAndState(b,a,d)},a.scheduleRecursiveWithAbsoluteAndState=function(a,b,d){return this._scheduleAbsolute({first:a,second:d},b,function(a,b){return c(a,b,"scheduleWithAbsoluteAndState")})}}(ac.prototype),function(){ac.prototype.schedulePeriodic=function(a,b){return this.schedulePeriodicWithState(null,a,b)},ac.prototype.schedulePeriodicWithState=function(a,b,c){if("undefined"==typeof R.setInterval)throw new Error("Periodic scheduling not supported.");var d=a,e=R.setInterval(function(){d=c(d)},b);return Xb(function(){R.clearInterval(e)})}}(ac.prototype);var cc,dc=ac.immediate=function(){function a(a,b){return b(this,a)}function b(a,b,c){for(var d=bc(b);d-this.now()>0;);return c(this,a)}function c(a,b,c){return this.scheduleWithRelativeAndState(a,b-this.now(),c)}return new ac($,a,b,c)}(),ec=ac.currentThread=function(){function a(a){for(var b;a.length>0;)if(b=a.dequeue(),!b.isCancelled()){for(;b.dueTime-ac.now()>0;);b.isCancelled()||b.invoke()}}function b(a,b){return this.scheduleWithRelativeAndState(a,0,b)}function c(b,c,d){var f=this.now()+ac.normalize(c),g=new _b(this,b,d,f);if(e)e.enqueue(g);else{e=new Sb(4),e.enqueue(g);try{a(e)}catch(h){throw h}finally{e=null}}return g.disposable}function d(a,b,c){return this.scheduleWithRelativeAndState(a,b-this.now(),c)}var e,f=new ac($,b,c,d);return f.scheduleRequired=function(){return!e},f.ensureTrampoline=function(a){e?a():this.schedule(a)},f}(),fc=(W.internals.SchedulePeriodicRecursive=function(){function a(a,b){b(0,this._period);try{this._state=this._action(this._state)}catch(c){throw this._cancel.dispose(),c}}function b(a,b,c,d){this._scheduler=a,this._state=b,this._period=c,this._action=d}return b.prototype.start=function(){var b=new Zb;return this._cancel=b,b.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0,this._period,a.bind(this))),b},b}(),X),gc=function(){var a,b=X;if("WScript"in this)a=function(a,b){WScript.Sleep(b),a()};else{if(!R.setTimeout)throw new Error("No concurrency detected!");a=R.setTimeout,b=R.clearTimeout}return{setTimeout:a,clearTimeout:b}}(),hc=gc.setTimeout,ic=gc.clearTimeout;!function(){function a(){if(!R.postMessage||R.importScripts)return!1;var a=!1,b=R.onmessage;return R.onmessage=function(){a=!0},R.postMessage("","*"),R.onmessage=b,a}var b=RegExp("^"+String(Bb).replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/toString| for [^\]]+/g,".*?")+"$"),c="function"==typeof(c=V&&U&&V.setImmediate)&&!b.test(c)&&c,d="function"==typeof(d=V&&U&&V.clearImmediate)&&!b.test(d)&&d;if("function"==typeof c)cc=c,fc=d;else if("undefined"!=typeof process&&"[object process]"==={}.toString.call(process))cc=process.nextTick;else if(a()){var e="ms.rx.schedule"+Math.random(),f={},g=0,h=function(a){if("string"==typeof a.data&&a.data.substring(0,e.length)===e){var b=a.data.substring(e.length),c=f[b];c(),delete f[b]}};R.addEventListener?R.addEventListener("message",h,!1):R.attachEvent("onmessage",h,!1),cc=function(a){var b=g++;f[b]=a,R.postMessage(e+b,"*")}}else if(R.MessageChannel){var i=new R.MessageChannel,j={},k=0;i.port1.onmessage=function(a){var b=a.data,c=j[b];c(),delete j[b]},cc=function(a){var b=k++;j[b]=a,i.port2.postMessage(b)}}else"document"in R&&"onreadystatechange"in R.document.createElement("script")?cc=function(a){var b=R.document.createElement("script");b.onreadystatechange=function(){a(),b.onreadystatechange=null,b.parentNode.removeChild(b),b=null},R.document.documentElement.appendChild(b)}:(cc=function(a){return hc(a,0)},fc=ic)}();var jc=ac.timeout=function(){function a(a,b){var c=this,d=new Zb,e=cc(function(){d.isDisposed||d.setDisposable(b(c,a))});return new Ub(d,Xb(function(){fc(e)}))}function b(a,b,c){var d=this,e=ac.normalize(b);if(0===e)return d.scheduleWithState(a,c);var f=new Zb,g=hc(function(){f.isDisposed||f.setDisposable(c(d,a))},e);return new Ub(f,Xb(function(){ic(g)}))}function c(a,b,c){return this.scheduleWithRelativeAndState(a,b-this.now(),c)}return new ac($,a,b,c)}(),kc=W.Notification=function(){function a(a,b){this.hasValue=null==b?!1:b,this.kind=a}return a.prototype.accept=function(a,b,c){return a&&"object"==typeof a?this._acceptObservable(a):this._accept(a,b,c)},a.prototype.toObservable=function(a){var b=this;return Y(a)||(a=dc),new Vc(function(c){return a.schedule(function(){b._acceptObservable(c),"N"===b.kind&&c.onCompleted()})})},a}(),lc=kc.createOnNext=function(){function a(a){return a(this.value)}function b(a){return a.onNext(this.value)}function c(){return"OnNext("+this.value+")"}return function(d){var e=new kc("N",!0);return e.value=d,e._accept=a,e._acceptObservable=b,e.toString=c,e}}(),mc=kc.createOnError=function(){function a(a,b){return b(this.exception)}function b(a){return a.onError(this.exception)}function c(){return"OnError("+this.exception+")"}return function(d){var e=new kc("E");return e.exception=d,e._accept=a,e._acceptObservable=b,e.toString=c,e}}(),nc=kc.createOnCompleted=function(){function a(a,b,c){return c()}function b(a){return a.onCompleted()}function c(){return"OnCompleted()"}return function(){var d=new kc("C");return d._accept=a,d._acceptObservable=b,d.toString=c,d}}(),oc=W.internals.Enumerator=function(a){this._next=a};oc.prototype.next=function(){return this._next()},oc.prototype[lb]=function(){return this};var pc=W.internals.Enumerable=function(a){this._iterator=a};pc.prototype[lb]=function(){return this._iterator()},pc.prototype.concat=function(){var a=this;return new Vc(function(b){var c;try{c=a[lb]()}catch(d){return void b.onError(d)}var e,f=new $b,g=dc.scheduleRecursive(function(a){var d;if(!e){try{d=c.next()}catch(g){return void b.onError(g)}if(d.done)return void b.onCompleted();var h=d.value;cb(h)&&(h=Oc(h));var i=new Zb;f.setDisposable(i),i.setDisposable(h.subscribe(b.onNext.bind(b),b.onError.bind(b),function(){a()}))}});return new Ub(f,g,Xb(function(){e=!0}))})},pc.prototype.catchError=function(){var a=this;return new Vc(function(b){var c;try{c=a[lb]()}catch(d){return void b.onError(d)}var e,f,g=new $b,h=dc.scheduleRecursive(function(a){if(!e){var d;try{d=c.next()}catch(h){return void b.onError(h)}if(d.done)return void(f?b.onError(f):b.onCompleted());var i=d.value;cb(i)&&(i=Oc(i));var j=new Zb;g.setDisposable(j),j.setDisposable(i.subscribe(b.onNext.bind(b),function(b){f=b,a()},b.onCompleted.bind(b)))}});return new Ub(g,h,Xb(function(){e=!0}))})};var qc=pc.repeat=function(a,b){return null==b&&(b=-1),new pc(function(){var c=b;return new oc(function(){return 0===c?mb:(c>0&&c--,{done:!1,value:a})})})},rc=pc.of=function(a,b,c){return b||(b=Z),new pc(function(){var d=-1;return new oc(function(){return++d<a.length?{done:!1,value:b.call(c,a[d],d,a)}:mb})})},sc=W.Observer=function(){};sc.prototype.toNotifier=function(){var a=this;return function(b){return b.accept(a)}},sc.prototype.asObserver=function(){return new wc(this.onNext.bind(this),this.onError.bind(this),this.onCompleted.bind(this))};var tc=sc.create=function(a,b,c){return a||(a=X),b||(b=bb),c||(c=X),new wc(a,b,c)};sc.fromNotifier=function(a,b){return new wc(function(c){return a.call(b,lc(c))},function(c){return a.call(b,mc(c))},function(){return a.call(b,nc())})};var uc,vc=W.internals.AbstractObserver=function(a){function b(){this.isStopped=!1,a.call(this)}return Ob(b,a),b.prototype.onNext=function(a){this.isStopped||this.next(a)},b.prototype.onError=function(a){this.isStopped||(this.isStopped=!0,this.error(a))},b.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.completed())},b.prototype.dispose=function(){this.isStopped=!0},b.prototype.fail=function(a){return this.isStopped?!1:(this.isStopped=!0,this.error(a),!0)},b}(sc),wc=W.AnonymousObserver=function(a){function b(b,c,d){a.call(this),this._onNext=b,this._onError=c,this._onCompleted=d}return Ob(b,a),b.prototype.next=function(a){this._onNext(a)},b.prototype.error=function(a){this._onError(a)},b.prototype.completed=function(){this._onCompleted()},b}(vc),xc=W.Observable=function(){function a(a){if(W.config.longStackSupport&&gb){try{throw new Error}catch(b){this.stack=b.stack.substring(b.stack.indexOf("\n")+1)}var d=this;this._subscribe=function(b){var e=b.onError.bind(b);return b.onError=function(a){c(a,d),e(a)},a(b)}}else this._subscribe=a}return uc=a.prototype,uc.subscribe=uc.forEach=function(a,b,c){return this._subscribe("object"==typeof a?a:tc(a,b,c))},uc.subscribeOnNext=function(a,b){return this._subscribe(tc(2===arguments.length?function(c){a.call(b,c)}:a))},uc.subscribeOnError=function(a,b){return this._subscribe(tc(null,2===arguments.length?function(c){a.call(b,c)}:a))},uc.subscribeOnCompleted=function(a,b){return this._subscribe(tc(null,null,2===arguments.length?function(){a.call(b)}:a))},a}(),yc=W.internals.ScheduledObserver=function(a){function b(b,c){a.call(this),this.scheduler=b,this.observer=c,this.isAcquired=!1,this.hasFaulted=!1,this.queue=[],this.disposable=new $b}return Ob(b,a),b.prototype.next=function(a){var b=this;this.queue.push(function(){b.observer.onNext(a)})},b.prototype.error=function(a){var b=this;this.queue.push(function(){b.observer.onError(a)})},b.prototype.completed=function(){var a=this;this.queue.push(function(){a.observer.onCompleted()})},b.prototype.ensureActive=function(){var a=!1,b=this;!this.hasFaulted&&this.queue.length>0&&(a=!this.isAcquired,this.isAcquired=!0),a&&this.disposable.setDisposable(this.scheduler.scheduleRecursive(function(a){var c;if(!(b.queue.length>0))return void(b.isAcquired=!1);c=b.queue.shift();try{c()}catch(d){throw b.queue=[],b.hasFaulted=!0,d}a()}))},b.prototype.dispose=function(){a.prototype.dispose.call(this),this.disposable.dispose()},b}(vc);uc.toArray=function(){var a=this;return new Vc(function(b){var c=[];return a.subscribe(c.push.bind(c),b.onError.bind(b),function(){b.onNext(c),b.onCompleted()})},a)},xc.create=xc.createWithDisposable=function(a,b){return new Vc(a,b)};var zc=xc.defer=function(a){return new Vc(function(b){var c;try{c=a()}catch(d){return Fc(d).subscribe(b)}return cb(c)&&(c=Oc(c)),c.subscribe(b)})},Ac=xc.empty=function(a){return Y(a)||(a=dc),new Vc(function(b){return a.schedule(function(){b.onCompleted()})})},Bc=Math.pow(2,53)-1;r.prototype[lb]=function(){return new t(this._s)},t.prototype[lb]=function(){return this},t.prototype.next=function(){if(this._i<this._l){var a=this._s.charAt(this._i++);return{done:!1,value:a}}return mb},u.prototype[lb]=function(){return new v(this._a)},v.prototype[lb]=function(){return this},v.prototype.next=function(){if(this._i<this._l){var a=this._a[this._i++];return{done:!1,value:a}}return mb};{var Cc=xc.from=function(a,b,c,d){if(null==a)throw new Error("iterable cannot be null.");if(b&&!db(b))throw new Error("mapFn when provided must be a function");Y(d)||(d=ec);var e=Object(a),f=x(e);return new Vc(function(a){var e=0;return d.scheduleRecursive(function(d){var g;try{g=f.next()}catch(h){return void a.onError(h)}if(g.done)return void a.onCompleted();var i=g.value;if(b&&db(b))try{i=b.call(c,i,e)}catch(h){return void a.onError(h)}a.onNext(i),e++,d()})})},Dc=xc.fromArray=function(a,b){return qb("fromArray","from"),Y(b)||(b=ec),new Vc(function(c){var d=0,e=a.length;return b.scheduleRecursive(function(b){e>d?(c.onNext(a[d++]),b()):c.onCompleted()})})};xc.never=function(){return new Vc(function(){return Yb})}}xc.of=function(){return A(null,arguments)},xc.ofWithScheduler=function(a){return A(a,Nb.call(arguments,1))},xc.range=function(a,b,c){return Y(c)||(c=ec),new Vc(function(d){return c.scheduleRecursiveWithState(0,function(c,e){b>c?(d.onNext(a+c),e(c+1)):d.onCompleted()})})},xc.repeat=function(a,b,c){return Y(c)||(c=ec),Ec(a,c).repeat(null==b?-1:b)};var Ec=xc["return"]=xc.just=function(a,b){return Y(b)||(b=dc),new Vc(function(c){return b.schedule(function(){c.onNext(a),c.onCompleted()})})};xc.returnValue=function(){return qb("returnValue","return or just"),Ec.apply(null,arguments)};var Fc=xc["throw"]=xc.throwException=xc.throwError=function(a,b){return Y(b)||(b=dc),new Vc(function(c){return b.schedule(function(){c.onError(a)})})};uc["catch"]=uc.catchError=function(a){return"function"==typeof a?B(this,a):Gc([this,a])},uc.catchException=function(a){return qb("catchException","catch or catchError"),this.catchError(a)};var Gc=xc.catchError=xc["catch"]=function(){return rc(o(arguments,0)).catchError()};xc.catchException=function(){return qb("catchException","catch or catchError"),Gc.apply(null,arguments)},uc.combineLatest=function(){var a=Nb.call(arguments);return Array.isArray(a[0])?a[0].unshift(this):a.unshift(this),Hc.apply(this,a)};var Hc=xc.combineLatest=function(){var a=Nb.call(arguments),b=a.pop();return Array.isArray(a[0])&&(a=a[0]),new Vc(function(c){function d(a){var d;if(h[a]=!0,i||(i=h.every(Z))){try{d=b.apply(null,k)}catch(e){return void c.onError(e)}c.onNext(d)}else j.filter(function(b,c){return c!==a}).every(Z)&&c.onCompleted()}function e(a){j[a]=!0,j.every(Z)&&c.onCompleted()}for(var f=function(){return!1},g=a.length,h=p(g,f),i=!1,j=p(g,f),k=new Array(g),l=new Array(g),m=0;g>m;m++)!function(b){var f=a[b],g=new Zb;cb(f)&&(f=Oc(f)),g.setDisposable(f.subscribe(function(a){k[b]=a,d(b)},c.onError.bind(c),function(){e(b)})),l[b]=g}(m);return new Ub(l)},this)};uc.concat=function(){var a=Nb.call(arguments,0);return a.unshift(this),Ic.apply(this,a)};var Ic=xc.concat=function(){return rc(o(arguments,0)).concat()};uc.concatAll=function(){return this.merge(1)},uc.concatObservable=function(){return qb("concatObservable","concatAll"),this.merge(1)},uc.merge=function(a){if("number"!=typeof a)return Jc(this,a);
var b=this;return new Vc(function(c){function d(a){var b=new Zb;f.add(b),cb(a)&&(a=Oc(a)),b.setDisposable(a.subscribe(c.onNext.bind(c),c.onError.bind(c),function(){f.remove(b),h.length>0?d(h.shift()):(e--,g&&0===e&&c.onCompleted())}))}var e=0,f=new Ub,g=!1,h=[];return f.add(b.subscribe(function(b){a>e?(e++,d(b)):h.push(b)},c.onError.bind(c),function(){g=!0,0===e&&c.onCompleted()})),f},b)};var Jc=xc.merge=function(){var a,b;return arguments[0]?Y(arguments[0])?(a=arguments[0],b=Nb.call(arguments,1)):(a=dc,b=Nb.call(arguments,0)):(a=dc,b=Nb.call(arguments,1)),Array.isArray(b[0])&&(b=b[0]),A(a,b).mergeAll()};uc.mergeAll=function(){var a=this;return new Vc(function(b){var c=new Ub,d=!1,e=new Zb;return c.add(e),e.setDisposable(a.subscribe(function(a){var e=new Zb;c.add(e),cb(a)&&(a=Oc(a)),e.setDisposable(a.subscribe(b.onNext.bind(b),b.onError.bind(b),function(){c.remove(e),d&&1===c.length&&b.onCompleted()}))},b.onError.bind(b),function(){d=!0,1===c.length&&b.onCompleted()})),c},a)},uc.mergeObservable=function(){return qb("mergeObservable","mergeAll"),this.mergeAll.apply(this,arguments)},uc.skipUntil=function(a){var b=this;return new Vc(function(c){var d=!1,e=new Ub(b.subscribe(function(a){d&&c.onNext(a)},c.onError.bind(c),function(){d&&c.onCompleted()}));cb(a)&&(a=Oc(a));var f=new Zb;return e.add(f),f.setDisposable(a.subscribe(function(){d=!0,f.dispose()},c.onError.bind(c),function(){f.dispose()})),e},b)},uc["switch"]=uc.switchLatest=function(){var a=this;return new Vc(function(b){var c=!1,d=new $b,e=!1,f=0,g=a.subscribe(function(a){var g=new Zb,h=++f;c=!0,d.setDisposable(g),cb(a)&&(a=Oc(a)),g.setDisposable(a.subscribe(function(a){f===h&&b.onNext(a)},function(a){f===h&&b.onError(a)},function(){f===h&&(c=!1,e&&b.onCompleted())}))},b.onError.bind(b),function(){e=!0,!c&&b.onCompleted()});return new Ub(g,d)},a)},uc.takeUntil=function(a){var b=this;return new Vc(function(c){return cb(a)&&(a=Oc(a)),new Ub(b.subscribe(c),a.subscribe(c.onCompleted.bind(c),c.onError.bind(c),X))},b)},uc.zip=function(){if(Array.isArray(arguments[0]))return C.apply(this,arguments);var a=this,b=Nb.call(arguments),c=b.pop();return b.unshift(a),new Vc(function(d){function e(b){var e,f;if(h.every(function(a){return a.length>0})){try{f=h.map(function(a){return a.shift()}),e=c.apply(a,f)}catch(g){return void d.onError(g)}d.onNext(e)}else i.filter(function(a,c){return c!==b}).every(Z)&&d.onCompleted()}function f(a){i[a]=!0,i.every(function(a){return a})&&d.onCompleted()}for(var g=b.length,h=p(g,function(){return[]}),i=p(g,function(){return!1}),j=new Array(g),k=0;g>k;k++)!function(a){var c=b[a],g=new Zb;cb(c)&&(c=Oc(c)),g.setDisposable(c.subscribe(function(b){h[a].push(b),e(a)},d.onError.bind(d),function(){f(a)})),j[a]=g}(k);return new Ub(j)},a)},xc.zip=function(){var a=Nb.call(arguments,0),b=a.shift();return b.zip.apply(b,a)},xc.zipArray=function(){var a=o(arguments,0);return new Vc(function(b){function c(a){if(f.every(function(a){return a.length>0})){var c=f.map(function(a){return a.shift()});b.onNext(c)}else if(g.filter(function(b,c){return c!==a}).every(Z))return void b.onCompleted()}function d(a){return g[a]=!0,g.every(Z)?void b.onCompleted():void 0}for(var e=a.length,f=p(e,function(){return[]}),g=p(e,function(){return!1}),h=new Array(e),i=0;e>i;i++)!function(e){h[e]=new Zb,h[e].setDisposable(a[e].subscribe(function(a){f[e].push(a),c(e)},b.onError.bind(b),function(){d(e)}))}(i);var j=new Ub(h);return j.add(Xb(function(){for(var a=0,b=f.length;b>a;a++)f[a]=[]})),j})},uc.asObservable=function(){return new Vc(this.subscribe.bind(this),this)},uc.dematerialize=function(){var a=this;return new Vc(function(b){return a.subscribe(function(a){return a.accept(b)},b.onError.bind(b),b.onCompleted.bind(b))},this)},uc.distinctUntilChanged=function(a,b){var c=this;return a||(a=Z),b||(b=_),new Vc(function(d){var e,f=!1;return c.subscribe(function(c){var g,h=!1;try{g=a(c)}catch(i){return void d.onError(i)}if(f)try{h=b(e,g)}catch(i){return void d.onError(i)}f&&h||(f=!0,e=g,d.onNext(c))},d.onError.bind(d),d.onCompleted.bind(d))},this)},uc["do"]=uc.tap=function(a,b,c){var d,e=this;return"function"==typeof a?d=a:(d=a.onNext.bind(a),b=a.onError.bind(a),c=a.onCompleted.bind(a)),new Vc(function(a){return e.subscribe(function(b){try{d(b)}catch(c){a.onError(c)}a.onNext(b)},function(c){if(b)try{b(c)}catch(d){a.onError(d)}a.onError(c)},function(){if(c)try{c()}catch(b){a.onError(b)}a.onCompleted()})},this)},uc.doAction=function(){return qb("doAction","do or tap"),this.tap.apply(this,arguments)},uc.doOnNext=uc.tapOnNext=function(a,b){return this.tap(2===arguments.length?function(c){a.call(b,c)}:a)},uc.doOnError=uc.tapOnError=function(a,b){return this.tap(X,2===arguments.length?function(c){a.call(b,c)}:a)},uc.doOnCompleted=uc.tapOnCompleted=function(a,b){return this.tap(X,null,2===arguments.length?function(){a.call(b)}:a)},uc["finally"]=uc.ensure=function(a){var b=this;return new Vc(function(c){var d;try{d=b.subscribe(c)}catch(e){throw a(),e}return Xb(function(){try{d.dispose()}catch(b){throw b}finally{a()}})},this)},uc.finallyAction=function(a){return qb("finallyAction","finally or ensure"),this.ensure(a)},uc.ignoreElements=function(){var a=this;return new Vc(function(b){return a.subscribe(X,b.onError.bind(b),b.onCompleted.bind(b))},a)},uc.materialize=function(){var a=this;return new Vc(function(b){return a.subscribe(function(a){b.onNext(lc(a))},function(a){b.onNext(mc(a)),b.onCompleted()},function(){b.onNext(nc()),b.onCompleted()})},a)},uc.repeat=function(a){return qc(this,a).concat()},uc.retry=function(a){return qc(this,a).catchError()},uc.scan=function(){var a,b,c=!1,d=this;return 2===arguments.length?(c=!0,a=arguments[0],b=arguments[1]):b=arguments[0],new Vc(function(e){var f,g,h;return d.subscribe(function(d){!h&&(h=!0);try{f?g=b(g,d):(g=c?b(a,d):d,f=!0)}catch(i){return void e.onError(i)}e.onNext(g)},e.onError.bind(e),function(){!h&&c&&e.onNext(a),e.onCompleted()})},d)},uc.skipLast=function(a){var b=this;return new Vc(function(c){var d=[];return b.subscribe(function(b){d.push(b),d.length>a&&c.onNext(d.shift())},c.onError.bind(c),c.onCompleted.bind(c))},b)},uc.startWith=function(){var a,b,c=0;return arguments.length&&Y(arguments[0])?(b=arguments[0],c=1):b=dc,a=Nb.call(arguments,c),rc([Dc(a,b),this]).concat()},uc.takeLast=function(a){var b=this;return new Vc(function(c){var d=[];return b.subscribe(function(b){d.push(b),d.length>a&&d.shift()},c.onError.bind(c),function(){for(;d.length>0;)c.onNext(d.shift());c.onCompleted()})},b)},uc.selectConcat=uc.concatMap=function(a,b,c){return db(a)&&db(b)?this.concatMap(function(c,d){var e=a(c,d);return cb(e)&&(e=Oc(e)),(ob(e)||nb(e))&&(e=Cc(e)),e.map(function(a,e){return b(c,a,d,e)})}):db(a)?D(this,a,c):D(this,function(){return a})},uc.select=uc.map=function(a,b){var c=db(a)?a:function(){return a},d=this;return new Vc(function(a){var e=0;return d.subscribe(function(f){var g;try{g=c.call(b,f,e++,d)}catch(h){return void a.onError(h)}a.onNext(g)},a.onError.bind(a),a.onCompleted.bind(a))},d)},uc.pluck=function(a){return this.map(function(b){return b[a]})},uc.selectMany=uc.flatMap=function(a,b,c){return db(a)&&db(b)?this.flatMap(function(c,d){var e=a(c,d);return cb(e)&&(e=Oc(e)),(ob(e)||nb(e))&&(e=Cc(e)),e.map(function(a,e){return b(c,a,d,e)})},c):db(a)?E(this,a,c):E(this,function(){return a})},uc.selectSwitch=uc.flatMapLatest=uc.switchMap=function(a,b){return this.select(a,b).switchLatest()},uc.skip=function(a){if(0>a)throw new Error(eb);var b=this;return new Vc(function(c){var d=a;return b.subscribe(function(a){0>=d?c.onNext(a):d--},c.onError.bind(c),c.onCompleted.bind(c))},b)},uc.skipWhile=function(a,b){var c=this;return new Vc(function(d){var e=0,f=!1;return c.subscribe(function(g){if(!f)try{f=!a.call(b,g,e++,c)}catch(h){return void d.onError(h)}f&&d.onNext(g)},d.onError.bind(d),d.onCompleted.bind(d))},c)},uc.take=function(a,b){if(0>a)throw new RangeError(eb);if(0===a)return Ac(b);var c=this;return new Vc(function(b){var d=a;return c.subscribe(function(a){d-->0&&(b.onNext(a),0===d&&b.onCompleted())},b.onError.bind(b),b.onCompleted.bind(b))},c)},uc.takeWhile=function(a,b){var c=this;return new Vc(function(d){var e=0,f=!0;return c.subscribe(function(g){if(f){try{f=a.call(b,g,e++,c)}catch(h){return void d.onError(h)}f?d.onNext(g):d.onCompleted()}},d.onError.bind(d),d.onCompleted.bind(d))},c)},uc.where=uc.filter=function(a,b){var c=this;return new Vc(function(d){var e=0;return c.subscribe(function(f){var g;try{g=a.call(b,f,e++,c)}catch(h){return void d.onError(h)}g&&d.onNext(f)},d.onError.bind(d),d.onCompleted.bind(d))},c)},xc.fromCallback=function(a,b,c){return function(){var d=Nb.call(arguments,0);return new Vc(function(e){function f(){var a=arguments;if(c){try{a=c(a)}catch(b){return void e.onError(b)}e.onNext(a)}else a.length<=1?e.onNext.apply(e,a):e.onNext(a);e.onCompleted()}d.push(f),a.apply(b,d)}).publishLast().refCount()}},xc.fromNodeCallback=function(a,b,c){return function(){var d=Nb.call(arguments,0);return new Vc(function(e){function f(a){if(a)return void e.onError(a);var b=Nb.call(arguments,1);if(c){try{b=c(b)}catch(d){return void e.onError(d)}e.onNext(b)}else b.length<=1?e.onNext.apply(e,b):e.onNext(b);e.onCompleted()}d.push(f),a.apply(b,d)}).publishLast().refCount()}},W.config.useNativeEvents=!1;var Kc=R.angular&&angular.element?angular.element:R.jQuery?R.jQuery:R.Zepto?R.Zepto:null,Lc=!!R.Ember&&"function"==typeof R.Ember.addListener,Mc=!!R.Backbone&&!!R.Backbone.Marionette;xc.fromEvent=function(a,b,c){if(a.addListener)return Nc(function(c){a.addListener(b,c)},function(c){a.removeListener(b,c)},c);if(!W.config.useNativeEvents){if(Mc)return Nc(function(c){a.on(b,c)},function(c){a.off(b,c)},c);if(Lc)return Nc(function(c){Ember.addListener(a,b,c)},function(c){Ember.removeListener(a,b,c)},c);if(Kc){var d=Kc(a);return Nc(function(a){d.on(b,a)},function(a){d.off(b,a)},c)}}return new Vc(function(d){return H(a,b,function(a){var b=a;if(c)try{b=c(arguments)}catch(e){return void d.onError(e)}d.onNext(b)})}).publish().refCount()};var Nc=xc.fromEventPattern=function(a,b,c){return new Vc(function(d){function e(a){var b=a;if(c)try{b=c(arguments)}catch(e){return void d.onError(e)}d.onNext(b)}var f=a(e);return Xb(function(){b&&b(e,f)})}).publish().refCount()},Oc=xc.fromPromise=function(a){return zc(function(){var b=new W.AsyncSubject;return a.then(function(a){b.onNext(a),b.onCompleted()},b.onError.bind(b)),b})};uc.toPromise=function(a){if(a||(a=W.config.Promise),!a)throw new TypeError("Promise type not provided nor in Rx.config.Promise");var b=this;return new a(function(a,c){var d,e=!1;b.subscribe(function(a){d=a,e=!0},c,function(){e&&a(d)})})},xc.startAsync=function(a){var b;try{b=a()}catch(c){return Fc(c)}return Oc(b)},uc.multicast=function(a,b){var c=this;return"function"==typeof a?new Vc(function(d){var e=c.multicast(a());return new Ub(b(e).subscribe(d),e.connect())},c):new Pc(c,a)},uc.publish=function(a){return a&&db(a)?this.multicast(function(){return new Yc},a):this.multicast(new Yc)},uc.share=function(){return this.publish().refCount()},uc.publishLast=function(a){return a&&db(a)?this.multicast(function(){return new Zc},a):this.multicast(new Zc)},uc.publishValue=function(a,b){return 2===arguments.length?this.multicast(function(){return new _c(b)},a):this.multicast(new _c(a))},uc.shareValue=function(a){return this.publishValue(a).refCount()},uc.replay=function(a,b,c,d){return a&&db(a)?this.multicast(function(){return new ad(b,c,d)},a):this.multicast(new ad(b,c,d))},uc.shareReplay=function(a,b,c){return this.replay(null,a,b,c).refCount()};{var Pc=W.ConnectableObservable=function(a){function b(b,c){var d,e=!1,f=b.asObservable();this.connect=function(){return e||(e=!0,d=new Ub(f.subscribe(c),Xb(function(){e=!1}))),d},a.call(this,c.subscribe.bind(c))}return Ob(b,a),b.prototype.refCount=function(){var a,b=0,c=this;return new Vc(function(d){var e=1===++b,f=c.subscribe(d);return e&&(a=c.connect()),function(){f.dispose(),0===--b&&a.dispose()}})},b}(xc),Qc=xc.interval=function(a,b){return L(a,a,Y(b)?b:jc)};xc.timer=function(b,c,d){var e;return Y(d)||(d=jc),c!==a&&"number"==typeof c?e=c:Y(c)&&(d=c),b instanceof Date&&e===a?I(b.getTime(),d):b instanceof Date&&e!==a?(e=c,J(b.getTime(),e,d)):e===a?K(b,d):L(b,e,d)}}uc.delay=function(a,b){return Y(b)||(b=jc),a instanceof Date?N(this,a.getTime(),b):M(this,a,b)},uc.debounce=uc.throttleWithTimeout=function(a,b){Y(b)||(b=jc);var c=this;return new Vc(function(d){var e,f=new $b,g=!1,h=0,i=c.subscribe(function(c){g=!0,e=c,h++;var i=h,j=new Zb;f.setDisposable(j),j.setDisposable(b.scheduleWithRelative(a,function(){g&&h===i&&d.onNext(e),g=!1}))},function(a){f.dispose(),d.onError(a),g=!1,h++},function(){f.dispose(),g&&d.onNext(e),d.onCompleted(),g=!1,h++});return new Ub(i,f)},this)},uc.throttle=function(a,b){return qb("throttle","debounce or throttleWithTimeout"),this.debounce(a,b)},uc.timestamp=function(a){return Y(a)||(a=jc),this.map(function(b){return{value:b,timestamp:a.now()}})},uc.sample=uc.throttleLatest=function(a,b){return Y(b)||(b=jc),"number"==typeof a?O(this,Qc(a,b)):O(this,a)},uc.timeout=function(a,b,c){(null==b||"string"==typeof b)&&(b=Fc(new Error(b||"Timeout"))),Y(c)||(c=jc);var d=this,e=a instanceof Date?"scheduleWithAbsolute":"scheduleWithRelative";return new Vc(function(f){function g(){var d=h;l.setDisposable(c[e](a,function(){h===d&&(cb(b)&&(b=Oc(b)),j.setDisposable(b.subscribe(f)))}))}var h=0,i=new Zb,j=new $b,k=!1,l=new $b;return j.setDisposable(i),g(),i.setDisposable(d.subscribe(function(a){k||(h++,f.onNext(a),g())},function(a){k||(h++,f.onError(a))},function(){k||(h++,f.onCompleted())})),new Ub(j,l)},d)},uc.throttleFirst=function(a,b){Y(b)||(b=jc);var c=+a||0;if(0>=c)throw new RangeError("windowDuration cannot be less or equal zero.");var d=this;return new Vc(function(a){var e=0;return d.subscribe(function(d){var f=b.now();(0===e||f-e>=c)&&(e=f,a.onNext(d))},a.onError.bind(a),a.onCompleted.bind(a))},d)};var Rc=function(a){function b(a){var b=this.source.publish(),c=b.subscribe(a),d=Yb,e=this.pauser.distinctUntilChanged().subscribe(function(a){a?d=b.connect():(d.dispose(),d=Yb)});return new Ub(c,d,e)}function c(c,d){this.source=c,this.controller=new Yc,this.pauser=d&&d.subscribe?this.controller.merge(d):this.controller,a.call(this,b,c)}return Ob(c,a),c.prototype.pause=function(){this.controller.onNext(!1)},c.prototype.resume=function(){this.controller.onNext(!0)},c}(xc);uc.pausable=function(a){return new Rc(this,a)};var Sc=function(b){function c(b){var c,d=[],e=P(this.source,this.pauser.distinctUntilChanged().startWith(!1),function(a,b){return{data:a,shouldFire:b}}).subscribe(function(e){if(c!==a&&e.shouldFire!=c){if(c=e.shouldFire,e.shouldFire)for(;d.length>0;)b.onNext(d.shift())}else c=e.shouldFire,e.shouldFire?b.onNext(e.data):d.push(e.data)},function(a){for(;d.length>0;)b.onNext(d.shift());b.onError(a)},function(){for(;d.length>0;)b.onNext(d.shift());b.onCompleted()});return e}function d(a,d){this.source=a,this.controller=new Yc,this.pauser=d&&d.subscribe?this.controller.merge(d):this.controller,b.call(this,c,a)}return Ob(d,b),d.prototype.pause=function(){this.controller.onNext(!1)},d.prototype.resume=function(){this.controller.onNext(!0)},d}(xc);uc.pausableBuffered=function(a){return new Sc(this,a)};var Tc=function(a){function b(a){return this.source.subscribe(a)}function c(c,d){a.call(this,b,c),this.subject=new Uc(d),this.source=c.multicast(this.subject).refCount()}return Ob(c,a),c.prototype.request=function(a){return null==a&&(a=-1),this.subject.request(a)},c}(xc),Uc=function(a){function b(a){return this.subject.subscribe(a)}function c(c){null==c&&(c=!0),a.call(this,b),this.subject=new Yc,this.enableQueue=c,this.queue=c?[]:null,this.requestedCount=0,this.requestedDisposable=Yb,this.error=null,this.hasFailed=!1,this.hasCompleted=!1,this.controlledDisposable=Yb}return Ob(c,a),Pb(c.prototype,sc,{onCompleted:function(){this.hasCompleted=!0,(!this.enableQueue||0===this.queue.length)&&this.subject.onCompleted()},onError:function(a){this.hasFailed=!0,this.error=a,(!this.enableQueue||0===this.queue.length)&&this.subject.onError(a)},onNext:function(a){var b=!1;0===this.requestedCount?this.enableQueue&&this.queue.push(a):(-1!==this.requestedCount&&0===this.requestedCount--&&this.disposeCurrentRequest(),b=!0),b&&this.subject.onNext(a)},_processRequest:function(a){if(this.enableQueue){for(;this.queue.length>=a&&a>0;)this.subject.onNext(this.queue.shift()),a--;return 0!==this.queue.length?{numberOfItems:a,returnValue:!0}:{numberOfItems:a,returnValue:!1}}return this.hasFailed?(this.subject.onError(this.error),this.controlledDisposable.dispose(),this.controlledDisposable=Yb):this.hasCompleted&&(this.subject.onCompleted(),this.controlledDisposable.dispose(),this.controlledDisposable=Yb),{numberOfItems:a,returnValue:!1}},request:function(a){this.disposeCurrentRequest();var b=this,c=this._processRequest(a),a=c.numberOfItems;return c.returnValue?Yb:(this.requestedCount=a,this.requestedDisposable=Xb(function(){b.requestedCount=0}),this.requestedDisposable)},disposeCurrentRequest:function(){this.requestedDisposable.dispose(),this.requestedDisposable=Yb}}),c}(xc);uc.controlled=function(a){return null==a&&(a=!0),new Tc(this,a)},uc.transduce=function(a){function b(a){return{init:function(){return a},step:function(a,b){return a.onNext(b)},result:function(a){return a.onCompleted()}}}var c=this;return new Vc(function(d){var e=a(b(d));return c.subscribe(function(a){try{e.step(d,a)}catch(b){d.onError(b)}},d.onError.bind(d),function(){e.result(d)})},c)};var Vc=W.AnonymousObservable=function(a){function b(a){return a&&"function"==typeof a.dispose?a:"function"==typeof a?Xb(a):Yb}function c(d,e){function f(a){var c=function(){try{e.setDisposable(b(d(e)))}catch(a){if(!e.fail(a))throw a}},e=new Wc(a);return ec.scheduleRequired()?ec.schedule(c):c(),e}return this.source=e,this instanceof c?void a.call(this,f):new c(d)}return Ob(c,a),c}(xc),Wc=function(a){function b(b){a.call(this),this.observer=b,this.m=new Zb}Ob(b,a);var c=b.prototype;return c.next=function(a){var b=!1;try{this.observer.onNext(a),b=!0}catch(c){throw c}finally{!b&&this.dispose()}},c.error=function(a){try{this.observer.onError(a)}catch(b){throw b}finally{this.dispose()}},c.completed=function(){try{this.observer.onCompleted()}catch(a){throw a}finally{this.dispose()}},c.setDisposable=function(a){this.m.setDisposable(a)},c.getDisposable=function(){return this.m.getDisposable()},c.dispose=function(){a.prototype.dispose.call(this),this.m.dispose()},b}(vc),Xc=function(a,b){this.subject=a,this.observer=b};Xc.prototype.dispose=function(){if(!this.subject.isDisposed&&null!==this.observer){var a=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(a,1),this.observer=null}};var Yc=W.Subject=function(a){function c(a){return b.call(this),this.isStopped?this.exception?(a.onError(this.exception),Yb):(a.onCompleted(),Yb):(this.observers.push(a),new Xc(this,a))}function d(){a.call(this,c),this.isDisposed=!1,this.isStopped=!1,this.observers=[]}return Ob(d,a),Pb(d.prototype,sc,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){if(b.call(this),!this.isStopped){var a=this.observers.slice(0);this.isStopped=!0;for(var c=0,d=a.length;d>c;c++)a[c].onCompleted();this.observers=[]}},onError:function(a){if(b.call(this),!this.isStopped){var c=this.observers.slice(0);this.isStopped=!0,this.exception=a;for(var d=0,e=c.length;e>d;d++)c[d].onError(a);this.observers=[]}},onNext:function(a){if(b.call(this),!this.isStopped)for(var c=this.observers.slice(0),d=0,e=c.length;e>d;d++)c[d].onNext(a)},dispose:function(){this.isDisposed=!0,this.observers=null}}),d.create=function(a,b){return new $c(a,b)},d}(xc),Zc=W.AsyncSubject=function(a){function c(a){if(b.call(this),!this.isStopped)return this.observers.push(a),new Xc(this,a);var c=this.exception,d=this.hasValue,e=this.value;return c?a.onError(c):d?(a.onNext(e),a.onCompleted()):a.onCompleted(),Yb}function d(){a.call(this,c),this.isDisposed=!1,this.isStopped=!1,this.value=null,this.hasValue=!1,this.observers=[],this.exception=null}return Ob(d,a),Pb(d.prototype,sc,{hasObservers:function(){return b.call(this),this.observers.length>0},onCompleted:function(){var a,c,d;if(b.call(this),!this.isStopped){this.isStopped=!0;var e=this.observers.slice(0),f=this.value,g=this.hasValue;if(g)for(c=0,d=e.length;d>c;c++)a=e[c],a.onNext(f),a.onCompleted();else for(c=0,d=e.length;d>c;c++)e[c].onCompleted();this.observers=[]}},onError:function(a){if(b.call(this),!this.isStopped){var c=this.observers.slice(0);this.isStopped=!0,this.exception=a;for(var d=0,e=c.length;e>d;d++)c[d].onError(a);this.observers=[]}},onNext:function(a){b.call(this),this.isStopped||(this.value=a,this.hasValue=!0)},dispose:function(){this.isDisposed=!0,this.observers=null,this.exception=null,this.value=null}}),d}(xc),$c=W.AnonymousSubject=function(a){function b(b,c){this.observer=b,this.observable=c,a.call(this,this.observable.subscribe.bind(this.observable))}return Ob(b,a),Pb(b.prototype,sc,{onCompleted:function(){this.observer.onCompleted()},onError:function(a){this.observer.onError(a)},onNext:function(a){this.observer.onNext(a)}}),b}(xc),_c=W.BehaviorSubject=function(a){function c(a){if(b.call(this),!this.isStopped)return this.observers.push(a),a.onNext(this.value),new Xc(this,a);var c=this.exception;return c?a.onError(c):a.onCompleted(),Yb}function d(b){a.call(this,c),this.value=b,this.observers=[],this.isDisposed=!1,this.isStopped=!1,this.exception=null}return Ob(d,a),Pb(d.prototype,sc,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){if(b.call(this),!this.isStopped){this.isStopped=!0;for(var a=0,c=this.observers.slice(0),d=c.length;d>a;a++)c[a].onCompleted();this.observers=[]}},onError:function(a){if(b.call(this),!this.isStopped){this.isStopped=!0,this.exception=a;for(var c=0,d=this.observers.slice(0),e=d.length;e>c;c++)d[c].onError(a);this.observers=[]}},onNext:function(a){if(b.call(this),!this.isStopped){this.value=a;for(var c=0,d=this.observers.slice(0),e=d.length;e>c;c++)d[c].onNext(a)}},dispose:function(){this.isDisposed=!0,this.observers=null,this.value=null,this.exception=null}}),d}(xc),ad=W.ReplaySubject=function(a){function c(a,b){return Xb(function(){b.dispose(),!a.isDisposed&&a.observers.splice(a.observers.indexOf(b),1)})}function d(a){var d=new yc(this.scheduler,a),e=c(this,d);b.call(this),this._trim(this.scheduler.now()),this.observers.push(d);for(var f=0,g=this.q.length;g>f;f++)d.onNext(this.q[f].value);return this.hasError?d.onError(this.error):this.isStopped&&d.onCompleted(),d.ensureActive(),e}function e(b,c,e){this.bufferSize=null==b?Number.MAX_VALUE:b,this.windowSize=null==c?Number.MAX_VALUE:c,this.scheduler=e||ec,this.q=[],this.observers=[],this.isStopped=!1,this.isDisposed=!1,this.hasError=!1,this.error=null,a.call(this,d)}return Ob(e,a),Pb(e.prototype,sc,{hasObservers:function(){return this.observers.length>0},_trim:function(a){for(;this.q.length>this.bufferSize;)this.q.shift();for(;this.q.length>0&&a-this.q[0].interval>this.windowSize;)this.q.shift()},onNext:function(a){if(b.call(this),!this.isStopped){var c=this.scheduler.now();this.q.push({interval:c,value:a}),this._trim(c);for(var d=this.observers.slice(0),e=0,f=d.length;f>e;e++){var g=d[e];g.onNext(a),g.ensureActive()}}},onError:function(a){if(b.call(this),!this.isStopped){this.isStopped=!0,this.error=a,this.hasError=!0;var c=this.scheduler.now();this._trim(c);for(var d=this.observers.slice(0),e=0,f=d.length;f>e;e++){var g=d[e];g.onError(a),g.ensureActive()}this.observers=[]}},onCompleted:function(){if(b.call(this),!this.isStopped){this.isStopped=!0;var a=this.scheduler.now();this._trim(a);for(var c=this.observers.slice(0),d=0,e=c.length;e>d;d++){var f=c[d];f.onCompleted(),f.ensureActive()}this.observers=[]}},dispose:function(){this.isDisposed=!0,this.observers=null}}),e}(xc);"function"==typeof define&&"object"==typeof define.amd&&define.amd?(R.Rx=W,define(function(){return W})):S&&T?U?(T.exports=W).Rx=W:S.Rx=W:R.Rx=W;var bd=g()}).call(this);
//# sourceMappingURL=rx.lite.compat.map | pulluru/generator-ppcreddy | node_modules/yo/node_modules/insight/node_modules/inquirer/node_modules/rx/dist/rx.lite.compat.min.js | JavaScript | mit | 56,186 |
/*! normalize.css v1.1.2 | MIT License | git.io/normalize */
/* ==========================================================================
HTML5 display definitions
========================================================================== */
/**
* Correct `block` display not defined in IE 6/7/8/9 and Firefox 3.
*/
article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
main,
nav,
section,
summary {
display: block;
}
/**
* Correct `inline-block` display not defined in IE 6/7/8/9 and Firefox 3.
*/
audio,
canvas,
video {
display: inline-block;
*display: inline;
*zoom: 1;
}
/**
* Prevent modern browsers from displaying `audio` without controls.
* Remove excess height in iOS 5 devices.
*/
audio:not([controls]) {
display: none;
height: 0;
}
/**
* Address styling not present in IE 7/8/9, Firefox 3, and Safari 4.
* Known issue: no IE 6 support.
*/
[hidden] {
display: none;
}
/* ==========================================================================
Base
========================================================================== */
/**
* 1. Correct text resizing oddly in IE 6/7 when body `font-size` is set using
* `em` units.
* 2. Prevent iOS text size adjust after orientation change, without disabling
* user zoom.
*/
html {
font-size: 100%; /* 1 */
-ms-text-size-adjust: 100%; /* 2 */
-webkit-text-size-adjust: 100%; /* 2 */
}
/**
* Address `font-family` inconsistency between `textarea` and other form
* elements.
*/
html,
button,
input,
select,
textarea {
font-family: sans-serif;
}
/**
* Address margins handled incorrectly in IE 6/7.
*/
body {
margin: 0;
}
/* ==========================================================================
Links
========================================================================== */
/**
* Address `outline` inconsistency between Chrome and other browsers.
*/
a:focus {
outline: thin dotted;
}
/**
* Improve readability when focused and also mouse hovered in all browsers.
*/
a:active,
a:hover {
outline: 0;
}
/* ==========================================================================
Typography
========================================================================== */
/**
* Address font sizes and margins set differently in IE 6/7.
* Address font sizes within `section` and `article` in Firefox 4+, Safari 5,
* and Chrome.
*/
h1 {
font-size: 2em;
margin: 0.67em 0;
}
h2 {
font-size: 1.5em;
margin: 0.83em 0;
}
h3 {
font-size: 1.17em;
margin: 1em 0;
}
h4 {
font-size: 1em;
margin: 1.33em 0;
}
h5 {
font-size: 0.83em;
margin: 1.67em 0;
}
h6 {
font-size: 0.67em;
margin: 2.33em 0;
}
/**
* Address styling not present in IE 7/8/9, Safari 5, and Chrome.
*/
abbr[title] {
border-bottom: 1px dotted;
}
/**
* Address style set to `bolder` in Firefox 3+, Safari 4/5, and Chrome.
*/
b,
strong {
font-weight: bold;
}
blockquote {
margin: 1em 40px;
}
/**
* Address styling not present in Safari 5 and Chrome.
*/
dfn {
font-style: italic;
}
/**
* Address differences between Firefox and other browsers.
* Known issue: no IE 6/7 normalization.
*/
hr {
-moz-box-sizing: content-box;
box-sizing: content-box;
height: 0;
}
/**
* Address styling not present in IE 6/7/8/9.
*/
mark {
background: #ff0;
color: #000;
}
/**
* Address margins set differently in IE 6/7.
*/
p,
pre {
margin: 1em 0;
}
/**
* Correct font family set oddly in IE 6, Safari 4/5, and Chrome.
*/
code,
kbd,
pre,
samp {
font-family: monospace, serif;
_font-family: 'courier new', monospace;
font-size: 1em;
}
/**
* Improve readability of pre-formatted text in all browsers.
*/
pre {
white-space: pre;
white-space: pre-wrap;
word-wrap: break-word;
}
/**
* Address CSS quotes not supported in IE 6/7.
*/
q {
quotes: none;
}
/**
* Address `quotes` property not supported in Safari 4.
*/
q:before,
q:after {
content: '';
content: none;
}
/**
* Address inconsistent and variable font size in all browsers.
*/
small {
font-size: 80%;
}
/**
* Prevent `sub` and `sup` affecting `line-height` in all browsers.
*/
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sup {
top: -0.5em;
}
sub {
bottom: -0.25em;
}
/* ==========================================================================
Lists
========================================================================== */
/**
* Address margins set differently in IE 6/7.
*/
dl,
menu,
ol,
ul {
margin: 1em 0;
}
dd {
margin: 0 0 0 40px;
}
/**
* Address paddings set differently in IE 6/7.
*/
menu,
ol,
ul {
padding: 0 0 0 40px;
}
/**
* Correct list images handled incorrectly in IE 7.
*/
nav ul,
nav ol {
list-style: none;
list-style-image: none;
}
/* ==========================================================================
Embedded content
========================================================================== */
/**
* 1. Remove border when inside `a` element in IE 6/7/8/9 and Firefox 3.
* 2. Improve image quality when scaled in IE 7.
*/
img {
border: 0; /* 1 */
-ms-interpolation-mode: bicubic; /* 2 */
}
/**
* Correct overflow displayed oddly in IE 9.
*/
svg:not(:root) {
overflow: hidden;
}
/* ==========================================================================
Figures
========================================================================== */
/**
* Address margin not present in IE 6/7/8/9, Safari 5, and Opera 11.
*/
figure {
margin: 0;
}
/* ==========================================================================
Forms
========================================================================== */
/**
* Correct margin displayed oddly in IE 6/7.
*/
form {
margin: 0;
}
/**
* Define consistent border, margin, and padding.
*/
fieldset {
border: 1px solid #c0c0c0;
margin: 0 2px;
padding: 0.35em 0.625em 0.75em;
}
/**
* 1. Correct color not being inherited in IE 6/7/8/9.
* 2. Correct text not wrapping in Firefox 3.
* 3. Correct alignment displayed oddly in IE 6/7.
*/
legend {
border: 0; /* 1 */
padding: 0;
white-space: normal; /* 2 */
*margin-left: -7px; /* 3 */
}
/**
* 1. Correct font size not being inherited in all browsers.
* 2. Address margins set differently in IE 6/7, Firefox 3+, Safari 5,
* and Chrome.
* 3. Improve appearance and consistency in all browsers.
*/
button,
input,
select,
textarea {
font-size: 100%; /* 1 */
margin: 0; /* 2 */
vertical-align: baseline; /* 3 */
*vertical-align: middle; /* 3 */
}
/**
* Address Firefox 3+ setting `line-height` on `input` using `!important` in
* the UA stylesheet.
*/
button,
input {
line-height: normal;
}
/**
* Address inconsistent `text-transform` inheritance for `button` and `select`.
* All other form control elements do not inherit `text-transform` values.
* Correct `button` style inheritance in Chrome, Safari 5+, and IE 6+.
* Correct `select` style inheritance in Firefox 4+ and Opera.
*/
button,
select {
text-transform: none;
}
/**
* 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio`
* and `video` controls.
* 2. Correct inability to style clickable `input` types in iOS.
* 3. Improve usability and consistency of cursor style between image-type
* `input` and others.
* 4. Remove inner spacing in IE 7 without affecting normal text inputs.
* Known issue: inner spacing remains in IE 6.
*/
button,
html input[type="button"], /* 1 */
input[type="reset"],
input[type="submit"] {
-webkit-appearance: button; /* 2 */
cursor: pointer; /* 3 */
*overflow: visible; /* 4 */
}
/**
* Re-set default cursor for disabled elements.
*/
button[disabled],
html input[disabled] {
cursor: default;
}
/**
* 1. Address box sizing set to content-box in IE 8/9.
* 2. Remove excess padding in IE 8/9.
* 3. Remove excess padding in IE 7.
* Known issue: excess padding remains in IE 6.
*/
input[type="checkbox"],
input[type="radio"] {
box-sizing: border-box; /* 1 */
padding: 0; /* 2 */
*height: 13px; /* 3 */
*width: 13px; /* 3 */
}
/**
* 1. Address `appearance` set to `searchfield` in Safari 5 and Chrome.
* 2. Address `box-sizing` set to `border-box` in Safari 5 and Chrome
* (include `-moz` to future-proof).
*/
input[type="search"] {
-webkit-appearance: textfield; /* 1 */
-moz-box-sizing: content-box;
-webkit-box-sizing: content-box; /* 2 */
box-sizing: content-box;
}
/**
* Remove inner padding and search cancel button in Safari 5 and Chrome
* on OS X.
*/
input[type="search"]::-webkit-search-cancel-button,
input[type="search"]::-webkit-search-decoration {
-webkit-appearance: none;
}
/**
* Remove inner padding and border in Firefox 3+.
*/
button::-moz-focus-inner,
input::-moz-focus-inner {
border: 0;
padding: 0;
}
/**
* 1. Remove default vertical scrollbar in IE 6/7/8/9.
* 2. Improve readability and alignment in all browsers.
*/
textarea {
overflow: auto; /* 1 */
vertical-align: top; /* 2 */
}
/* ==========================================================================
Tables
========================================================================== */
/**
* Remove most spacing between table cells.
*/
table {
border-collapse: collapse;
border-spacing: 0;
}
| gf3/cdnjs | ajax/libs/normalize/1.1.2/normalize.css | CSS | mit | 9,559 |
/*!
* VERSION: beta 1.7.0
* DATE: 2013-02-27
* JavaScript
* UPDATES AND DOCS AT: http://www.greensock.com
*
* @license Copyright (c) 2008-2013, GreenSock. All rights reserved.
* This work is subject to the terms in http://www.greensock.com/terms_of_use.html or for
* Club GreenSock members, the software agreement that was issued with your membership.
*
* @author: Jack Doyle, jack@greensock.com
**/
(window._gsQueue||(window._gsQueue=[])).push(function(){"use strict";var a=document.documentElement,b=window,c=function(c,d){var e="x"===d?"Width":"Height",f="scroll"+e,g="client"+e,h=document.body;return c===b||c===a||c===h?Math.max(a[f],h[f])-Math.max(a[g],h[g]):c[f]-c["offset"+e]},d=window._gsDefine.plugin({propName:"scrollTo",API:2,init:function(a,d,e){return this._wdw=a===b,this._target=a,this._tween=e,"object"!=typeof d&&(d={y:d}),this._autoKill=d.autoKill!==!1,this.x=this.xPrev=this.getX(),this.y=this.yPrev=this.getY(),null!=d.x?this._addTween(this,"x",this.x,"max"===d.x?c(a,"x"):d.x,"scrollTo_x",!0):this.skipX=!0,null!=d.y?this._addTween(this,"y",this.y,"max"===d.y?c(a,"y"):d.y,"scrollTo_y",!0):this.skipY=!0,!0},set:function(a){this._super.setRatio.call(this,a);var c=this._wdw||!this.skipX?this.getX():this.xPrev,d=this._wdw||!this.skipY?this.getY():this.yPrev,e=d-this.yPrev,f=c-this.xPrev;this._autoKill&&(!this.skipX&&(f>7||-7>f)&&(this.skipX=!0),!this.skipY&&(e>7||-7>e)&&(this.skipY=!0),this.skipX&&this.skipY&&this._tween.kill()),this._wdw?b.scrollTo(this.skipX?c:this.x,this.skipY?d:this.y):(this.skipY||(this._target.scrollTop=this.y),this.skipX||(this._target.scrollLeft=this.x)),this.xPrev=this.x,this.yPrev=this.y}}),e=d.prototype;d.max=c,e.getX=function(){return this._wdw?null!=b.pageXOffset?b.pageXOffset:null!=a.scrollLeft?a.scrollLeft:document.body.scrollLeft:this._target.scrollLeft},e.getY=function(){return this._wdw?null!=b.pageYOffset?b.pageYOffset:null!=a.scrollTop?a.scrollTop:document.body.scrollTop:this._target.scrollTop},e._kill=function(a){return a.scrollTo_x&&(this.skipX=!0),a.scrollTo_y&&(this.skipY=!0),this._super._kill.call(this,a)}}),window._gsDefine&&window._gsQueue.pop()(); | pombredanne/cdnjs | ajax/libs/gsap/1.9.0/plugins/ScrollToPlugin.min.js | JavaScript | mit | 2,144 |
/**
* SyntaxHighlighter
* http://alexgorbatchev.com/SyntaxHighlighter
*
* SyntaxHighlighter is donationware. If you are using it, please donate.
* http://alexgorbatchev.com/SyntaxHighlighter/donate.html
*
* @version
* 3.0.83 (July 02 2010)
*
* @copyright
* Copyright (C) 2004-2010 Alex Gorbatchev.
*
* @license
* Dual licensed under the MIT and GPL licenses.
*/
;(function()
{
// CommonJS
typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
function Brush()
{
function process(match, regexInfo)
{
var constructor = SyntaxHighlighter.Match,
code = match[0],
tag = new XRegExp('(<|<)[\\s\\/\\?]*(?<name>[:\\w-\\.]+)', 'xg').exec(code),
result = []
;
if (match.attributes != null)
{
var attributes,
regex = new XRegExp('(?<name> [\\w:\\-\\.]+)' +
'\\s*=\\s*' +
'(?<value> ".*?"|\'.*?\'|\\w+)',
'xg');
while ((attributes = regex.exec(code)) != null)
{
result.push(new constructor(attributes.name, match.index + attributes.index, 'color1'));
result.push(new constructor(attributes.value, match.index + attributes.index + attributes[0].indexOf(attributes.value), 'string'));
}
}
if (tag != null)
result.push(
new constructor(tag.name, match.index + tag[0].indexOf(tag.name), 'keyword')
);
return result;
}
this.regexList = [
{ regex: new XRegExp('(\\<|<)\\!\\[[\\w\\s]*?\\[(.|\\s)*?\\]\\](\\>|>)', 'gm'), css: 'color2' }, // <![ ... [ ... ]]>
{ regex: SyntaxHighlighter.regexLib.xmlComments, css: 'comments' }, // <!-- ... -->
{ regex: new XRegExp('(<|<)[\\s\\/\\?]*(\\w+)(?<attributes>.*?)[\\s\\/\\?]*(>|>)', 'sg'), func: process }
];
};
Brush.prototype = new SyntaxHighlighter.Highlighter();
Brush.aliases = ['xml', 'xhtml', 'xslt', 'html'];
SyntaxHighlighter.brushes.Xml = Brush;
// CommonJS
typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
})();
| dryajov/cdnjs | ajax/libs/SyntaxHighlighter/3.0.83/scripts/shBrushXml.js | JavaScript | mit | 1,998 |
test( "Popcorn Google Feed Plugin", function() {
var popped = Popcorn( "#video" ),
expects = 12,
setupId,
count = 0;
expect( expects );
function plus() {
if ( ++count === expects ) {
start();
}
}
stop();
ok ( "googlefeed" in popped, "googlefeed is a method of the popped instance" );
plus();
ok ( document.getElementById( "feed" ).innerHTML === "", "initially, there is nothing inside the feed" );
plus();
ok ( document.getElementById( "feed1" ).innerHTML === "", "initially, there is nothing inside the feed1" );
plus();
popped.googlefeed({
start: 1,
end: 2,
target: "feed",
url: "http://zenit.senecac.on.ca/~chris.tyler/planet/rss20.xml",
title: "Planet Feed"
})
.googlefeed({
start: 2,
end: 3,
target: "feed1",
url: "http://blog.pikimal.com/geek/feed/",
title: "pikiGeek",
orientation: "Horizontal"
})
.volume( 0 );
setupId = popped.getLastTrackEventId();
popped.exec( 1, function() {
ok( google.load, "Google Feed is available" );
plus();
ok( GFdynamicFeedControl, "Dynamic Feed Control Available" );
plus();
ok( document.getElementById( "_feed1" ), "First feed is on the page" );
plus();
equal( document.getElementById( "_feed1" ).offsetParent.id, "feed", "First feed is inside the 'feed' div" );
plus();
equal( popped.data.trackEvents.byStart[ 1 ].orientation, "vertical", "Defaulting to vertical orientation" );
plus();
});
popped.exec( 2, function() {
ok( document.getElementById( "_feed2" ), "Second feed is on the page" );
plus();
equal( document.getElementById( "_feed2" ).offsetParent.id, "feed1", "Second feed is inside the 'feed2' div" );
plus();
});
popped.exec( 3, function() {
ok( document.getElementById( "_feed2" ).style.display === "none" &&
document.getElementById( "_feed1" ).style.display === "none", "Both feeds are no lnger visible" );
plus();
popped.pause().removeTrackEvent( setupId );
ok( !document.getElementById( "feed1" ).children[ 0 ], "removed feed was properly destroyed" );
plus();
});
// empty track events should be safe
Popcorn.plugin.debug = true;
popped.googlefeed({});
popped.play();
});
asyncTest( "Overriding default toString", 2, function() {
var p = Popcorn( "#video" ),
urlText = "http://zenit.senecac.on.ca/~chris.tyler/planet/rss20.xml",
lastEvent;
function testLastEvent( compareText, message ) {
lastEvent = p.getTrackEvent( p.getLastTrackEventId() );
equal( lastEvent.toString(), compareText, message );
}
p.googlefeed({
url: urlText
});
testLastEvent( urlText, "Custom text displayed with toString" );
p.googlefeed({});
testLastEvent( "http://planet.mozilla.org/rss20.xml", "Custom text displayed with toString using default" );
start();
});
| justindelacruz/popcorn-js | plugins/googlefeed/popcorn.googlefeed.unit.js | JavaScript | mit | 2,876 |
<?php
namespace Elastica\Test\QueryBuilder\DSL;
use Elastica\Filter\Exists;
use Elastica\Query\Match;
use Elastica\QueryBuilder\DSL;
class FilterTest extends AbstractDSLTest
{
/**
* @group unit
*/
public function testType()
{
$filterDSL = new DSL\Filter();
$this->assertInstanceOf('Elastica\QueryBuilder\DSL', $filterDSL);
$this->assertEquals(DSL::TYPE_FILTER, $filterDSL->getType());
}
/**
* @group unit
*/
public function testInterface()
{
$filterDSL = new DSL\Filter();
$this->_assertImplemented($filterDSL, 'bool', 'Elastica\Filter\BoolFilter', array());
$this->_assertImplemented($filterDSL, 'bool_and', 'Elastica\Filter\BoolAnd', array(array(new Exists('field'))));
$this->_assertImplemented($filterDSL, 'bool_not', 'Elastica\Filter\BoolNot', array(new Exists('field')));
$this->_assertImplemented($filterDSL, 'bool_or', 'Elastica\Filter\BoolOr', array(array(new Exists('field'))));
$this->_assertImplemented($filterDSL, 'exists', 'Elastica\Filter\Exists', array('field'));
$this->_assertImplemented($filterDSL, 'geo_bounding_box', 'Elastica\Filter\GeoBoundingBox', array('field', array(1, 2)));
$this->_assertImplemented($filterDSL, 'geo_distance', 'Elastica\Filter\GeoDistance', array('key', 'location', 'distance'));
$this->_assertImplemented($filterDSL, 'geo_distance_range', 'Elastica\Filter\GeoDistanceRange', array('key', 'location'));
$this->_assertImplemented($filterDSL, 'geo_polygon', 'Elastica\Filter\GeoPolygon', array('key', array()));
$this->_assertImplemented($filterDSL, 'geo_shape_pre_indexed', 'Elastica\Filter\GeoShapePreIndexed', array('path', 'indexedId', 'indexedType', 'indexedIndex', 'indexedPath'));
$this->_assertImplemented($filterDSL, 'geo_shape_provided', 'Elastica\Filter\GeoShapeProvided', array('path', array()));
$this->_assertImplemented($filterDSL, 'geohash_cell', 'Elastica\Filter\GeohashCell', array('field', 'location'));
$this->_assertImplemented($filterDSL, 'has_child', 'Elastica\Filter\HasChild', array(new Match(), 'type'));
$this->_assertImplemented($filterDSL, 'has_parent', 'Elastica\Filter\HasParent', array(new Match(), 'type'));
$this->_assertImplemented($filterDSL, 'ids', 'Elastica\Filter\Ids', array('type', array()));
$this->_assertImplemented($filterDSL, 'indices', 'Elastica\Filter\Indices', array(new Exists('field'), array()));
$this->_assertImplemented($filterDSL, 'limit', 'Elastica\Filter\Limit', array(1));
$this->_assertImplemented($filterDSL, 'match_all', 'Elastica\Filter\MatchAll', array());
$this->_assertImplemented($filterDSL, 'missing', 'Elastica\Filter\Missing', array('field'));
$this->_assertImplemented($filterDSL, 'nested', 'Elastica\Filter\Nested', array());
$this->_assertImplemented($filterDSL, 'numeric_range', 'Elastica\Filter\NumericRange', array());
$this->_assertImplemented($filterDSL, 'prefix', 'Elastica\Filter\Prefix', array('field', 'prefix'));
$this->_assertImplemented($filterDSL, 'query', 'Elastica\Filter\Query', array(new Match()));
$this->_assertImplemented($filterDSL, 'range', 'Elastica\Filter\Range', array('field', array()));
$this->_assertImplemented($filterDSL, 'regexp', 'Elastica\Filter\Regexp', array('field', 'regex'));
$this->_assertImplemented($filterDSL, 'script', 'Elastica\Filter\Script', array('script'));
$this->_assertImplemented($filterDSL, 'term', 'Elastica\Filter\Term', array());
$this->_assertImplemented($filterDSL, 'terms', 'Elastica\Filter\Terms', array('field', array()));
$this->_assertImplemented($filterDSL, 'type', 'Elastica\Filter\Type', array('type'));
}
}
| Southparkfan/Elastica | test/lib/Elastica/Test/QueryBuilder/DSL/FilterTest.php | PHP | mit | 3,811 |
require File.dirname(__FILE__) + '/test_helper'
class RemoteLoggingTest < Test::Unit::TestCase
def setup
establish_real_connection
end
def teardown
disconnect!
end
def test_logging
Bucket.create(TEST_BUCKET) # Clear out any custom grants
# Confirm that logging is not enabled on the test bucket
assert !Bucket.logging_enabled_for?(TEST_BUCKET)
assert !Bucket.find(TEST_BUCKET).logging_enabled?
assert_equal [], Bucket.logs_for(TEST_BUCKET)
# Confirm the current bucket doesn't have logging grants
policy = Bucket.acl(TEST_BUCKET)
assert !policy.grants.include?(:logging_read_acp)
assert !policy.grants.include?(:logging_write)
# Confirm that we can enable logging
assert_nothing_raised do
Bucket.enable_logging_for TEST_BUCKET
end
# Confirm enabling logging worked
assert Service.response.success?
assert Bucket.logging_enabled_for?(TEST_BUCKET)
assert Bucket.find(TEST_BUCKET).logging_enabled?
# Confirm the appropriate grants were added
policy = Bucket.acl(TEST_BUCKET)
assert policy.grants.include?(:logging_read_acp)
assert policy.grants.include?(:logging_write)
# Confirm logging status used defaults
logging_status = Bucket.logging_status_for TEST_BUCKET
assert_equal TEST_BUCKET, logging_status.target_bucket
assert_equal 'log-', logging_status.target_prefix
# Confirm we can update the logging status
logging_status.target_prefix = 'access-log-'
assert_nothing_raised do
Bucket.logging_status_for TEST_BUCKET, logging_status
end
assert Service.response.success?
logging_status = Bucket.logging_status_for TEST_BUCKET
assert_equal 'access-log-', logging_status.target_prefix
# Confirm we can make a request for the bucket's logs
assert_nothing_raised do
Bucket.logs_for TEST_BUCKET
end
# Confirm we can disable logging
assert_nothing_raised do
Bucket.disable_logging_for(TEST_BUCKET)
end
assert Service.response.success?
assert !Bucket.logging_enabled_for?(TEST_BUCKET)
end
end | jwarchol/aws-s3 | test/remote/logging_test.rb | Ruby | mit | 2,220 |
body {
padding: 5px 20px;
font-family: Verdana, Helvetica, Arial, Sans-serif;
color: #333;
font-size: 10pt;
}
body, li, a, label, div, table, th, td {
font-size: 10pt;
font-family: Verdana, Helvetica, Arial, Sans-serif;
}
li {
margin-bottom: 4px;
}
.information {
border: 1px solid #729ECD;
padding: 4px;
padding-left: 30px;
background: #E6EEF7 url(../images/information.png) no-repeat 6px 12px;
margin: 12px 0;
}
h1 {
font-size: 18pt;
}
h2 {
padding-top: 8px;
font-size: 14pt;
clear: both;
}
table.test {
width: 800px;
}
table.test th {
width: 700px;
font-weight: normal;
text-align: left;
padding: 4px;
padding-left: 30px;
}
table.test td {
padding: 4px;
}
tr.pass th {
border: 1px solid #72C868;
background: #E9FFDD url(../images/accept.png) no-repeat 6px 4px ;
}
tr.pass td {
border: 1px solid #72C868;
background-color: #E9FFDD;
}
tr.fail th {
border: 1px solid #F58263;
background: #FEEBE7 url(../images/exclamation.png) no-repeat 6px 4px ;
}
tr.fail td {
border: 1px solid #F58263;
background-color: #FEEBE7;
} | cloudland-sa/Datejs | test/styles/specifications.css | CSS | mit | 1,131 |
.peppermint.active {
position: relative;
overflow: hidden;
padding-left: 0;
padding-right: 0;
}
.peppermint.active .captions {
font-size: 0.9rem;
margin-bottom: 0.5rem;
text-align: center;
display: none;
}
.peppermint.active .slides {
z-index: 0;
position: relative;
overflow: hidden;
-ms-touch-action: pan-y;
touch-action: pan-y;
}
.peppermint.active .slides > * {
float: left;
margin: 0;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
-webkit-tap-highlight-color: transparent;
}
.peppermint.active .slides a:active,
.peppermint.active .slides a:active img {
outline: none;
}
.peppermint.active,
.peppermint.active .dots,
.peppermint.active .slides,
.peppermint.active .slides > * {
-webkit-transform: translate3d(0,0,0);
-ms-transform: translate3d(0,0,0);
-moz-transform: translate3d(0,0,0);
transform: translate3d(0,0,0);
-webkit-backface-visibility: hidden;
-moz-backface-visibility: hidden;
-ms-backface-visibility: hidden;
backface-visibility: hidden;
} | ahocevar/cdnjs | ajax/libs/peppermint/1.0.0/peppermint.required.css | CSS | mit | 1,030 |
package org.robolectric.shadows;
import android.content.ContentProviderOperation;
import android.content.ContentValues;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
import org.robolectric.annotation.RealObject;
import org.robolectric.annotation.HiddenApi;
import org.robolectric.util.ReflectionHelpers;
import java.util.Map;
/**
* Shadow for {@link android.content.ContentProviderOperation}.
*/
@Implements(ContentProviderOperation.class)
public class ShadowContentProviderOperation {
public final static int TYPE_INSERT = 1;
public final static int TYPE_UPDATE = 2;
public final static int TYPE_DELETE = 3;
public final static int TYPE_ASSERT = 4;
@RealObject
private ContentProviderOperation realOperation;
@HiddenApi @Implementation
public int getType() {
return getFieldReflectively("mType");
}
public String getSelection() {
return getFieldReflectively("mSelection");
}
public String[] getSelectionArgs() {
return getFieldReflectively("mSelectionArgs");
}
public ContentValues getContentValues() {
return getFieldReflectively("mValues");
}
public Integer getExpectedCount() {
return getFieldReflectively("mExpectedCount");
}
public ContentValues getValuesBackReferences() {
return getFieldReflectively("mValuesBackReferences");
}
@SuppressWarnings("unchecked")
public Map<Integer, Integer> getSelectionArgsBackReferences() {
return getFieldReflectively("mSelectionArgsBackReferences");
}
private <T> T getFieldReflectively(String fieldName) {
return ReflectionHelpers.getField(realOperation, fieldName);
}
}
| davidsun/robolectric | robolectric-shadows/shadows-core/src/main/java/org/robolectric/shadows/ShadowContentProviderOperation.java | Java | mit | 1,657 |
/*
Copyright (c) 2011, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.com/yui/license.html
version: 2.9.0
*/
body{font:13px/1.231 arial,helvetica,clean,sans-serif;*font-size:small;*font:x-small}select,input,textarea,button{font:99% arial,helvetica,clean,sans-serif}table{font-size:inherit;font:100%}pre,code,kbd,samp,tt{font-family:monospace;*font-size:108%;line-height:100%}/*
Copyright (c) 2011, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.com/yui/license.html
version: 2.9.0
*/
html{color:#000;background:#FFF}body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,code,form,fieldset,legend,input,button,textarea,select,p,blockquote,th,td{margin:0;padding:0}table{border-collapse:collapse;border-spacing:0}fieldset,img{border:0}address,button,caption,cite,code,dfn,em,input,optgroup,option,select,strong,textarea,th,var{font:inherit}del,ins{text-decoration:none}li{list-style:none}caption,th{text-align:left}h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal}q:before,q:after{content:''}abbr,acronym{border:0;font-variant:normal}sup{vertical-align:baseline}sub{vertical-align:baseline}legend{color:#000} | cythilya/Code_Snippets | functional_snippet/trim_201308062236/skin/reset-font-min.css | CSS | mit | 1,196 |
<!DOCTYPE html>
<html lang="en">
<head>
<title>WebRTC Text Chat / Data Sharing ® Muaz Khan</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<link rel="author" type="text/html" href="https://plus.google.com/100325991024054712503">
<meta name="author" content="Muaz Khan">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<script>
var hash = window.location.hash.replace('#', '');
if (!hash.length) location.href = location.href + '#text-chat-' + ((Math.random() * new Date().getTime()).toString(36).toLowerCase().replace( /\./g , '-'));
</script>
<link type="text/css" href="https://fonts.googleapis.com/css?family=Inconsolata" />
<style>
html { background: #eee; }
body {
font-family: "Inconsolata", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", monospace;
font-size: 1.2em;
line-height: 1.2em;
margin: 0;
}
body {
background: #fff;
border: 1px solid;
border-color: #ddd #aaa #aaa #ddd;
border-radius: 5px;
margin: .5em auto 0 auto;
padding: .8em;
padding-top: 0;
}
h1, h2 {
border-bottom: 1px solid black;
display: inline;
font-weight: normal;
line-height: 36px;
padding: 0 0 3px 0;
}
h1 {
background: rgb(238, 238, 238);
border-bottom-width: 2px;
display: block;
margin-top: 0;
padding: .3em;
text-align: center;
}
:-moz-any-link:focus {
border: 0;
color: #000;
}
::selection { background: #ccc; }
::-moz-selection { background: #ccc; }
button {
-moz-border-radius: 3px;
-moz-transition: none;
-webkit-transition: none;
background: #0370ea;
background: -moz-linear-gradient(top, #008dfd 0, #0370ea 100%);
background: -webkit-linear-gradient(top, #008dfd 0, #0370ea 100%);
border: 1px solid #076bd2;
border-radius: 3px;
color: #fff;
display: inline-block;
font-family: inherit;
font-size: .8em;
line-height: 1.3;
padding: 5px 12px;
text-align: center;
text-shadow: 1px 1px 1px #076bd2;
}
button:hover { background: rgb(9, 147, 240); }
button:active { background: rgb(10, 118, 190); }
button[disabled] {
background: none;
border: 1px solid rgb(187, 181, 181);
color: gray;
text-shadow: none;
}
footer { text-align: center; }
code {
color: rgb(204, 14, 14);
font-family: inherit;
}
pre {
border-left: 2px solid red;
margin-left: 2em;
padding-left: 1em;
}
input { font-size: 2em; }
#chat-table blockquote {
border: 1px dotted gray;
margin: 1em 5em;
padding: 1em 2em;
}
#chat-table blockquote hr {
border: 0;
border-top: 1px dotted #BBA9A9;
margin: 1em -2em;
}
.user-id {
border-right: 1px solid gray;
float: left;
height: 1em;
margin: 0 2em;
overflow: hidden;
padding: 0 1em;
text-align: right;
width: 3%;
}
.message {
border-bottom: 1px solid gray;
margin-left: 6em;
}
</style>
<script src="https://cdn.webrtc-experiment.com/firebase.js"> </script>
<script src="https://cdn.webrtc-experiment.com/data-connection.js"> </script>
</head>
<body>
<h1>
WebRTC Text Chat / Data Sharing / <a href="https://github.com/muaz-khan/WebRTC-Experiment/tree/master/text-chat"
target="_blank">Source Code</a>
</h1>
<p>
<span>Copyright © 2013</span> <a href="https://github.com/muaz-khan" target="_blank">
Muaz Khan</a><span><</span><a href="http://twitter.com/muazkh" target="_blank">@muazkh</a><span>>.</span>
</p>
<section class="plusone-gplus">
<div class="g-plusone" data-href="https://www.webrtc-experiment.com/"></div>
</section>
<section>
<h2>Setup a new connection:</h2>
<button id="setup-new-connection">Setup New Data Connection</button>
</section>
<table style="border-left: 1px solid black; border-right: 1px solid black; width: 100%;">
<tr>
<td>
<h2 style="display: block; font-size: 1em; text-align: center;">
Group Text Chat</h2>
<div id="chat-output">
</div>
<input type="text" id="user-id" style="font-size: 1.2em; margin-right: 0; width: 5em;"
placeholder="all" disabled title="Enter user-id to send direct messages.">
<input type="text" id="chat-input" style="font-size: 1.2em; margin-left: -.5em; width: 80%;"
placeholder="chat message" disabled>
</td>
</tr>
</table>
<script>
var roomid = window.location.hash.substr(1);
var connection = new DataConnection();
// connection.userid = prompt('Enter your username') || 'Anonymous';
// on data connection opens
connection.onopen = function(e) {
document.getElementById('chat-input').disabled = false;
useridBox.disabled = false;
appendDIV('Data connection opened between you and ' + e.userid, e.userid);
};
// on text message or data object received
connection.onmessage = function(message, userid) {
console.debug(userid, 'says', message);
appendDIV(message, userid);
};
// on data connection error
connection.onerror = function(e) {
console.debug('Error in data connection. Target user id', e.userid, 'Error', e);
};
// on data connection close
connection.onclose = function(e) {
console.debug('Data connection closed. Target user id', e.userid, 'Error', e);
};
/* custom signaling gateway
connection.openSignalingChannel = function(callback) {
return io.connect().on('message', callback);
};
*/
// using firebase for signaling
connection.firebase = 'signaling';
// if someone leaves; just remove his video
connection.onuserleft = function(userid) {
appendDIV(userid + ' Left.', userid);
};
// check pre-created data connections
connection.check(roomid);
document.getElementById('setup-new-connection').onclick = function() {
// setup new data connection
connection.setup(roomid);
this.disabled = true;
this.parentNode.innerHTML = '<h2><a href="' + location.href + '" target="_blank">Share this link</a></h2>';
};
var chatOutput = document.getElementById('chat-output');
function appendDIV(data, userid) {
var div = document.createElement('div');
div.innerHTML = '<section class="user-id" contenteditable title="Use his user-id to send him direct messages or throw out of the room!">' + userid + '</section>'
+ '<section class="message" contenteditable>' + data + '</section>';
chatOutput.insertBefore(div, chatOutput.firstChild);
div.tabIndex = 0;
div.focus();
chatInput.focus();
}
var chatInput = document.getElementById('chat-input');
var useridBox = document.getElementById('user-id');
chatInput.onkeypress = function(e) {
if (e.keyCode !== 13 || !this.value) return;
if (useridBox.value.length) {
var user = connection.channels[useridBox.value];
if (user) user.send(this.value);
else return alert('No such user exists.');
} else connection.send(this.value);
appendDIV(this.value, 'Me');
this.value = '';
this.focus();
};
</script>
<br />
<br />
<pre>
<script src="https://www.webrtc-experiment.com/data-connection.js"></script>
</pre>
<pre>
var connection = new DataConnection();
connection.onopen = function(e) { /* e.userid */ };
connection.onmessage = function(message, userid) {};
// share data with all connected users
connection.send(file || data || 'text message');
// share data between two unique users (i.e. direct messages)
connection.channels['user-id'].send(file || data || 'text-message');
// custom signaling gateway
connection.openSignalingChannel = function(callback) {
return io.connect().on('message', callback);
};
// check existing connections
connection.check('room-name');
document.getElementById('setup-new-connection').onclick = function() {
connection.setup('room-name');
};
</pre>
<br />
<br />
<section style="border: 1px solid rgb(189, 189, 189); border-radius: .2em; margin: 1em 3em;">
<h2 id="feedback" style="border-bottom: 1px solid rgb(189, 189, 189); padding: .2em .4em;">Feedback</h2>
<div>
<textarea id="message" style="border: 1px solid rgb(189, 189, 189); height: 8em; margin: .2em; outline: none; resize: vertical; width: 98%;" placeholder="Have any message? Suggestions or something went wrong?"></textarea>
</div>
<button id="send-message" style="font-size: 1em;">Send Message</button>
</section>
<footer>
<p> <a href="https://www.webrtc-experiment.com/" target="_blank">WebRTC Experiments!</a> © <a href="https://plus.google.com/100325991024054712503" rel="author" target="_blank">Muaz Khan</a>, <span>2013 </span> » <a href="mailto:muazkh@gmail.com" target="_blank">Email</a> » <a href="http://twitter.com/muazkh" target="_blank">@muazkh</a> » <a href="https://github.com/muaz-khan" target="_blank">Github</a></p>
</footer>
<script src="https://cdn.webrtc-experiment.com/commits.js"> </script>
</body>
</html>
| luckymark/WebRTC-Experiment | text-chat/index.html | HTML | mit | 11,430 |
ace.define("ace/mode/ocaml_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"],function(e,t,n){"use strict";var r=e("../lib/oop"),i=e("./text_highlight_rules").TextHighlightRules,s=function(){var e="and|as|assert|begin|class|constraint|do|done|downto|else|end|exception|external|for|fun|function|functor|if|in|include|inherit|initializer|lazy|let|match|method|module|mutable|new|object|of|open|or|private|rec|sig|struct|then|to|try|type|val|virtual|when|while|with",t="true|false",n="abs|abs_big_int|abs_float|abs_num|abstract_tag|accept|access|acos|add|add_available_units|add_big_int|add_buffer|add_channel|add_char|add_initializer|add_int_big_int|add_interfaces|add_num|add_string|add_substitute|add_substring|alarm|allocated_bytes|allow_only|allow_unsafe_modules|always|append|appname_get|appname_set|approx_num_exp|approx_num_fix|arg|argv|arith_status|array|array1_of_genarray|array2_of_genarray|array3_of_genarray|asin|asr|assoc|assq|at_exit|atan|atan2|auto_synchronize|background|basename|beginning_of_input|big_int_of_int|big_int_of_num|big_int_of_string|bind|bind_class|bind_tag|bits|bits_of_float|black|blit|blit_image|blue|bool|bool_of_string|bounded_full_split|bounded_split|bounded_split_delim|bprintf|break|broadcast|bscanf|button_down|c_layout|capitalize|cardinal|cardinal|catch|catch_break|ceil|ceiling_num|channel|char|char_of_int|chdir|check|check_suffix|chmod|choose|chop_extension|chop_suffix|chown|chown|chr|chroot|classify_float|clear|clear_available_units|clear_close_on_exec|clear_graph|clear_nonblock|clear_parser|close|close|closeTk|close_box|close_graph|close_in|close_in_noerr|close_out|close_out_noerr|close_process|close_process|close_process_full|close_process_in|close_process_out|close_subwindow|close_tag|close_tbox|closedir|closedir|closure_tag|code|combine|combine|combine|command|compact|compare|compare_big_int|compare_num|complex32|complex64|concat|conj|connect|contains|contains_from|contents|copy|cos|cosh|count|count|counters|create|create_alarm|create_image|create_matrix|create_matrix|create_matrix|create_object|create_object_and_run_initializers|create_object_opt|create_process|create_process|create_process_env|create_process_env|create_table|current|current_dir_name|current_point|current_x|current_y|curveto|custom_tag|cyan|data_size|decr|decr_num|default_available_units|delay|delete_alarm|descr_of_in_channel|descr_of_out_channel|destroy|diff|dim|dim1|dim2|dim3|dims|dirname|display_mode|div|div_big_int|div_num|double_array_tag|double_tag|draw_arc|draw_char|draw_circle|draw_ellipse|draw_image|draw_poly|draw_poly_line|draw_rect|draw_segments|draw_string|dummy_pos|dummy_table|dump_image|dup|dup2|elements|empty|end_of_input|environment|eprintf|epsilon_float|eq_big_int|eq_num|equal|err_formatter|error_message|escaped|establish_server|executable_name|execv|execve|execvp|execvpe|exists|exists2|exit|exp|failwith|fast_sort|fchmod|fchown|field|file|file_exists|fill|fill_arc|fill_circle|fill_ellipse|fill_poly|fill_rect|filter|final_tag|finalise|find|find_all|first_chars|firstkey|flatten|float|float32|float64|float_of_big_int|float_of_bits|float_of_int|float_of_num|float_of_string|floor|floor_num|flush|flush_all|flush_input|flush_str_formatter|fold|fold_left|fold_left2|fold_right|fold_right2|for_all|for_all2|force|force_newline|force_val|foreground|fork|format_of_string|formatter_of_buffer|formatter_of_out_channel|fortran_layout|forward_tag|fprintf|frexp|from|from_channel|from_file|from_file_bin|from_function|from_string|fscanf|fst|fstat|ftruncate|full_init|full_major|full_split|gcd_big_int|ge_big_int|ge_num|genarray_of_array1|genarray_of_array2|genarray_of_array3|get|get_all_formatter_output_functions|get_approx_printing|get_copy|get_ellipsis_text|get_error_when_null_denominator|get_floating_precision|get_formatter_output_functions|get_formatter_tag_functions|get_image|get_margin|get_mark_tags|get_max_boxes|get_max_indent|get_method|get_method_label|get_normalize_ratio|get_normalize_ratio_when_printing|get_print_tags|get_state|get_variable|getcwd|getegid|getegid|getenv|getenv|getenv|geteuid|geteuid|getgid|getgid|getgrgid|getgrgid|getgrnam|getgrnam|getgroups|gethostbyaddr|gethostbyname|gethostname|getitimer|getlogin|getpeername|getpid|getppid|getprotobyname|getprotobynumber|getpwnam|getpwuid|getservbyname|getservbyport|getsockname|getsockopt|getsockopt_float|getsockopt_int|getsockopt_optint|gettimeofday|getuid|global_replace|global_substitute|gmtime|green|grid|group_beginning|group_end|gt_big_int|gt_num|guard|handle_unix_error|hash|hash_param|hd|header_size|i|id|ignore|in_channel_length|in_channel_of_descr|incr|incr_num|index|index_from|inet_addr_any|inet_addr_of_string|infinity|infix_tag|init|init_class|input|input_binary_int|input_byte|input_char|input_line|input_value|int|int16_signed|int16_unsigned|int32|int64|int8_signed|int8_unsigned|int_of_big_int|int_of_char|int_of_float|int_of_num|int_of_string|integer_num|inter|interactive|inv|invalid_arg|is_block|is_empty|is_implicit|is_int|is_int_big_int|is_integer_num|is_relative|iter|iter2|iteri|join|junk|key_pressed|kill|kind|kprintf|kscanf|land|last_chars|layout|lazy_from_fun|lazy_from_val|lazy_is_val|lazy_tag|ldexp|le_big_int|le_num|length|lexeme|lexeme_char|lexeme_end|lexeme_end_p|lexeme_start|lexeme_start_p|lineto|link|list|listen|lnot|loadfile|loadfile_private|localtime|lock|lockf|log|log10|logand|lognot|logor|logxor|lor|lower_window|lowercase|lseek|lsl|lsr|lstat|lt_big_int|lt_num|lxor|magenta|magic|mainLoop|major|major_slice|make|make_formatter|make_image|make_lexer|make_matrix|make_self_init|map|map2|map_file|mapi|marshal|match_beginning|match_end|matched_group|matched_string|max|max_array_length|max_big_int|max_elt|max_float|max_int|max_num|max_string_length|mem|mem_assoc|mem_assq|memq|merge|min|min_big_int|min_elt|min_float|min_int|min_num|minor|minus_big_int|minus_num|minus_one|mkdir|mkfifo|mktime|mod|mod_big_int|mod_float|mod_num|modf|mouse_pos|moveto|mul|mult_big_int|mult_int_big_int|mult_num|nan|narrow|nat_of_num|nativeint|neg|neg_infinity|new_block|new_channel|new_method|new_variable|next|nextkey|nice|nice|no_scan_tag|norm|norm2|not|npeek|nth|nth_dim|num_digits_big_int|num_dims|num_of_big_int|num_of_int|num_of_nat|num_of_ratio|num_of_string|O|obj|object_tag|ocaml_version|of_array|of_channel|of_float|of_int|of_int32|of_list|of_nativeint|of_string|one|openTk|open_box|open_connection|open_graph|open_hbox|open_hovbox|open_hvbox|open_in|open_in_bin|open_in_gen|open_out|open_out_bin|open_out_gen|open_process|open_process_full|open_process_in|open_process_out|open_subwindow|open_tag|open_tbox|open_temp_file|open_vbox|opendbm|opendir|openfile|or|os_type|out_channel_length|out_channel_of_descr|output|output_binary_int|output_buffer|output_byte|output_char|output_string|output_value|over_max_boxes|pack|params|parent_dir_name|parse|parse_argv|partition|pause|peek|pipe|pixels|place|plot|plots|point_color|polar|poll|pop|pos_in|pos_out|pow|power_big_int_positive_big_int|power_big_int_positive_int|power_int_positive_big_int|power_int_positive_int|power_num|pp_close_box|pp_close_tag|pp_close_tbox|pp_force_newline|pp_get_all_formatter_output_functions|pp_get_ellipsis_text|pp_get_formatter_output_functions|pp_get_formatter_tag_functions|pp_get_margin|pp_get_mark_tags|pp_get_max_boxes|pp_get_max_indent|pp_get_print_tags|pp_open_box|pp_open_hbox|pp_open_hovbox|pp_open_hvbox|pp_open_tag|pp_open_tbox|pp_open_vbox|pp_over_max_boxes|pp_print_as|pp_print_bool|pp_print_break|pp_print_char|pp_print_cut|pp_print_float|pp_print_flush|pp_print_if_newline|pp_print_int|pp_print_newline|pp_print_space|pp_print_string|pp_print_tab|pp_print_tbreak|pp_set_all_formatter_output_functions|pp_set_ellipsis_text|pp_set_formatter_out_channel|pp_set_formatter_output_functions|pp_set_formatter_tag_functions|pp_set_margin|pp_set_mark_tags|pp_set_max_boxes|pp_set_max_indent|pp_set_print_tags|pp_set_tab|pp_set_tags|pred|pred_big_int|pred_num|prerr_char|prerr_endline|prerr_float|prerr_int|prerr_newline|prerr_string|print|print_as|print_bool|print_break|print_char|print_cut|print_endline|print_float|print_flush|print_if_newline|print_int|print_newline|print_space|print_stat|print_string|print_tab|print_tbreak|printf|prohibit|public_method_label|push|putenv|quo_num|quomod_big_int|quote|raise|raise_window|ratio_of_num|rcontains_from|read|read_float|read_int|read_key|read_line|readdir|readdir|readlink|really_input|receive|recv|recvfrom|red|ref|regexp|regexp_case_fold|regexp_string|regexp_string_case_fold|register|register_exception|rem|remember_mode|remove|remove_assoc|remove_assq|rename|replace|replace_first|replace_matched|repr|reset|reshape|reshape_1|reshape_2|reshape_3|rev|rev_append|rev_map|rev_map2|rewinddir|rgb|rhs_end|rhs_end_pos|rhs_start|rhs_start_pos|rindex|rindex_from|rlineto|rmdir|rmoveto|round_num|run_initializers|run_initializers_opt|scanf|search_backward|search_forward|seek_in|seek_out|select|self|self_init|send|sendto|set|set_all_formatter_output_functions|set_approx_printing|set_binary_mode_in|set_binary_mode_out|set_close_on_exec|set_close_on_exec|set_color|set_ellipsis_text|set_error_when_null_denominator|set_field|set_floating_precision|set_font|set_formatter_out_channel|set_formatter_output_functions|set_formatter_tag_functions|set_line_width|set_margin|set_mark_tags|set_max_boxes|set_max_indent|set_method|set_nonblock|set_nonblock|set_normalize_ratio|set_normalize_ratio_when_printing|set_print_tags|set_signal|set_state|set_tab|set_tag|set_tags|set_text_size|set_window_title|setgid|setgid|setitimer|setitimer|setsid|setsid|setsockopt|setsockopt|setsockopt_float|setsockopt_float|setsockopt_int|setsockopt_int|setsockopt_optint|setsockopt_optint|setuid|setuid|shift_left|shift_left|shift_left|shift_right|shift_right|shift_right|shift_right_logical|shift_right_logical|shift_right_logical|show_buckets|shutdown|shutdown|shutdown_connection|shutdown_connection|sigabrt|sigalrm|sigchld|sigcont|sigfpe|sighup|sigill|sigint|sigkill|sign_big_int|sign_num|signal|signal|sigpending|sigpending|sigpipe|sigprocmask|sigprocmask|sigprof|sigquit|sigsegv|sigstop|sigsuspend|sigsuspend|sigterm|sigtstp|sigttin|sigttou|sigusr1|sigusr2|sigvtalrm|sin|singleton|sinh|size|size|size_x|size_y|sleep|sleep|sleep|slice_left|slice_left|slice_left_1|slice_left_2|slice_right|slice_right|slice_right_1|slice_right_2|snd|socket|socket|socket|socketpair|socketpair|sort|sound|split|split_delim|sprintf|sprintf|sqrt|sqrt|sqrt_big_int|square_big_int|square_num|sscanf|stable_sort|stable_sort|stable_sort|stable_sort|stable_sort|stable_sort|stat|stat|stat|stat|stat|stats|stats|std_formatter|stdbuf|stderr|stderr|stderr|stdib|stdin|stdin|stdin|stdout|stdout|stdout|str_formatter|string|string_after|string_before|string_match|string_of_big_int|string_of_bool|string_of_float|string_of_format|string_of_inet_addr|string_of_inet_addr|string_of_int|string_of_num|string_partial_match|string_tag|sub|sub|sub_big_int|sub_left|sub_num|sub_right|subset|subset|substitute_first|substring|succ|succ|succ|succ|succ_big_int|succ_num|symbol_end|symbol_end_pos|symbol_start|symbol_start_pos|symlink|symlink|sync|synchronize|system|system|system|tag|take|tan|tanh|tcdrain|tcdrain|tcflow|tcflow|tcflush|tcflush|tcgetattr|tcgetattr|tcsendbreak|tcsendbreak|tcsetattr|tcsetattr|temp_file|text_size|time|time|time|timed_read|timed_write|times|times|tl|tl|tl|to_buffer|to_channel|to_float|to_hex|to_int|to_int32|to_list|to_list|to_list|to_nativeint|to_string|to_string|to_string|to_string|to_string|top|top|total_size|transfer|transp|truncate|truncate|truncate|truncate|truncate|truncate|try_lock|umask|umask|uncapitalize|uncapitalize|uncapitalize|union|union|unit_big_int|unlink|unlink|unlock|unmarshal|unsafe_blit|unsafe_fill|unsafe_get|unsafe_get|unsafe_set|unsafe_set|update|uppercase|uppercase|uppercase|uppercase|usage|utimes|utimes|wait|wait|wait|wait|wait_next_event|wait_pid|wait_read|wait_signal|wait_timed_read|wait_timed_write|wait_write|waitpid|white|widen|window_id|word_size|wrap|wrap_abort|write|yellow|yield|zero|zero_big_int|Arg|Arith_status|Array|Array1|Array2|Array3|ArrayLabels|Big_int|Bigarray|Buffer|Callback|CamlinternalOO|Char|Complex|Condition|Dbm|Digest|Dynlink|Event|Filename|Format|Gc|Genarray|Genlex|Graphics|GraphicsX11|Hashtbl|Int32|Int64|LargeFile|Lazy|Lexing|List|ListLabels|Make|Map|Marshal|MoreLabels|Mutex|Nativeint|Num|Obj|Oo|Parsing|Pervasives|Printexc|Printf|Queue|Random|Scanf|Scanning|Set|Sort|Stack|State|StdLabels|Str|Stream|String|StringLabels|Sys|Thread|ThreadUnix|Tk|Unix|UnixLabels|Weak",r=this.createKeywordMapper({"variable.language":"this",keyword:e,"constant.language":t,"support.function":n},"identifier"),i="(?:(?:[1-9]\\d*)|(?:0))",s="(?:0[oO]?[0-7]+)",o="(?:0[xX][\\dA-Fa-f]+)",u="(?:0[bB][01]+)",a="(?:"+i+"|"+s+"|"+o+"|"+u+")",f="(?:[eE][+-]?\\d+)",l="(?:\\.\\d+)",c="(?:\\d+)",h="(?:(?:"+c+"?"+l+")|(?:"+c+"\\.))",p="(?:(?:"+h+"|"+c+")"+f+")",d="(?:"+p+"|"+h+")";this.$rules={start:[{token:"comment",regex:"\\(\\*.*?\\*\\)\\s*?$"},{token:"comment",regex:"\\(\\*.*",next:"comment"},{token:"string",regex:'["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'},{token:"string",regex:"'.'"},{token:"string",regex:'"',next:"qstring"},{token:"constant.numeric",regex:"(?:"+d+"|\\d+)[jJ]\\b"},{token:"constant.numeric",regex:d},{token:"constant.numeric",regex:a+"\\b"},{token:r,regex:"[a-zA-Z_$][a-zA-Z0-9_$]*\\b"},{token:"keyword.operator",regex:"\\+\\.|\\-\\.|\\*\\.|\\/\\.|#|;;|\\+|\\-|\\*|\\*\\*\\/|\\/\\/|%|<<|>>|&|\\||\\^|~|<|>|<=|=>|==|!=|<>|<-|="},{token:"paren.lparen",regex:"[[({]"},{token:"paren.rparen",regex:"[\\])}]"},{token:"text",regex:"\\s+"}],comment:[{token:"comment",regex:"\\*\\)",next:"start"},{defaultToken:"comment"}],qstring:[{token:"string",regex:'"',next:"start"},{token:"string",regex:".+"}]}};r.inherits(s,i),t.OcamlHighlightRules=s}),ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(e,t,n){"use strict";var r=e("../range").Range,i=function(){};(function(){this.checkOutdent=function(e,t){return/^\s+$/.test(e)?/^\s*\}/.test(t):!1},this.autoOutdent=function(e,t){var n=e.getLine(t),i=n.match(/^(\s*\})/);if(!i)return 0;var s=i[1].length,o=e.findMatchingBracket({row:t,column:s});if(!o||o.row==t)return 0;var u=this.$getIndent(e.getLine(o.row));e.replace(new r(t,0,t,s-1),u)},this.$getIndent=function(e){return e.match(/^\s*/)[0]}}).call(i.prototype),t.MatchingBraceOutdent=i}),ace.define("ace/mode/ocaml",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/ocaml_highlight_rules","ace/mode/matching_brace_outdent","ace/range"],function(e,t,n){"use strict";var r=e("../lib/oop"),i=e("./text").Mode,s=e("./ocaml_highlight_rules").OcamlHighlightRules,o=e("./matching_brace_outdent").MatchingBraceOutdent,u=e("../range").Range,a=function(){this.HighlightRules=s,this.$behaviour=this.$defaultBehaviour,this.$outdent=new o};r.inherits(a,i);var f=/(?:[({[=:]|[-=]>|\b(?:else|try|with))\s*$/;(function(){this.toggleCommentLines=function(e,t,n,r){var i,s,o=!0,a=/^\s*\(\*(.*)\*\)/;for(i=n;i<=r;i++)if(!a.test(t.getLine(i))){o=!1;break}var f=new u(0,0,0,0);for(i=n;i<=r;i++)s=t.getLine(i),f.start.row=i,f.end.row=i,f.end.column=s.length,t.replace(f,o?s.match(a)[1]:"(*"+s+"*)")},this.getNextLineIndent=function(e,t,n){var r=this.$getIndent(t),i=this.getTokenizer().getLineTokens(t,e).tokens;return(!i.length||i[i.length-1].type!=="comment")&&e==="start"&&f.test(t)&&(r+=n),r},this.checkOutdent=function(e,t,n){return this.$outdent.checkOutdent(t,n)},this.autoOutdent=function(e,t,n){this.$outdent.autoOutdent(t,n)},this.$id="ace/mode/ocaml"}).call(a.prototype),t.Mode=a}); (function() {
ace.require(["ace/mode/ocaml"], function(m) {
if (typeof module == "object" && typeof exports == "object" && module) {
module.exports = m;
}
});
})();
| Heigvd/Wegas | wegas-resources/src/main/webapp/lib/ace/src-min-noconflict/mode-ocaml.js | JavaScript | mit | 15,919 |
package cofh.api.energy;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
/**
* Reference implementation of {@link IEnergyContainerItem}. Use/extend this or implement your own.
*
* @author King Lemming
*
*/
public class ItemEnergyContainer extends Item implements IEnergyContainerItem {
protected int capacity;
protected int maxReceive;
protected int maxExtract;
public ItemEnergyContainer() {
}
public ItemEnergyContainer(int capacity) {
this(capacity, capacity, capacity);
}
public ItemEnergyContainer(int capacity, int maxTransfer) {
this(capacity, maxTransfer, maxTransfer);
}
public ItemEnergyContainer(int capacity, int maxReceive, int maxExtract) {
this.capacity = capacity;
this.maxReceive = maxReceive;
this.maxExtract = maxExtract;
}
public ItemEnergyContainer setCapacity(int capacity) {
this.capacity = capacity;
return this;
}
public ItemEnergyContainer setMaxTransfer(int maxTransfer) {
setMaxReceive(maxTransfer);
setMaxExtract(maxTransfer);
return this;
}
public ItemEnergyContainer setMaxReceive(int maxReceive) {
this.maxReceive = maxReceive;
return this;
}
public ItemEnergyContainer setMaxExtract(int maxExtract) {
this.maxExtract = maxExtract;
return this;
}
/* IEnergyContainerItem */
@Override
public int receiveEnergy(ItemStack container, int maxReceive, boolean simulate) {
if (!container.hasTagCompound()) {
container.setTagCompound(new NBTTagCompound());
}
int energy = container.getTagCompound().getInteger("Energy");
int energyReceived = Math.min(capacity - energy, Math.min(this.maxReceive, maxReceive));
if (!simulate) {
energy += energyReceived;
container.getTagCompound().setInteger("Energy", energy);
}
return energyReceived;
}
@Override
public int extractEnergy(ItemStack container, int maxExtract, boolean simulate) {
if (container.getTagCompound() == null || !container.getTagCompound().hasKey("Energy")) {
return 0;
}
int energy = container.getTagCompound().getInteger("Energy");
int energyExtracted = Math.min(energy, Math.min(this.maxExtract, maxExtract));
if (!simulate) {
energy -= energyExtracted;
container.getTagCompound().setInteger("Energy", energy);
}
return energyExtracted;
}
@Override
public int getEnergyStored(ItemStack container) {
if (container.getTagCompound() == null || !container.getTagCompound().hasKey("Energy")) {
return 0;
}
return container.getTagCompound().getInteger("Energy");
}
@Override
public int getMaxEnergyStored(ItemStack container) {
return capacity;
}
}
| CyberdyneCC/BigReactors | src/main/java/cofh/api/energy/ItemEnergyContainer.java | Java | mit | 2,646 |
<?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\Console\Helper;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Formatter\OutputFormatterStyle;
/**
* The Dialog class provides helpers to interact with the user.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated since version 2.5, to be removed in 3.0.
* Use {@link \Symfony\Component\Console\Helper\QuestionHelper} instead.
*/
class DialogHelper extends InputAwareHelper
{
private $inputStream;
private static $shell;
private static $stty;
public function __construct($triggerDeprecationError = true)
{
if ($triggerDeprecationError) {
@trigger_error('"Symfony\Component\Console\Helper\DialogHelper" is deprecated since version 2.5 and will be removed in 3.0. Use "Symfony\Component\Console\Helper\QuestionHelper" instead.', E_USER_DEPRECATED);
}
}
/**
* Asks the user to select a value.
*
* @param OutputInterface $output An Output instance
* @param string|array $question The question to ask
* @param array $choices List of choices to pick from
* @param bool|string $default The default answer if the user enters nothing
* @param bool|int $attempts Max number of times to ask before giving up (false by default, which means infinite)
* @param string $errorMessage Message which will be shown if invalid value from choice list would be picked
* @param bool $multiselect Select more than one value separated by comma
*
* @return int|string|array The selected value or values (the key of the choices array)
*
* @throws \InvalidArgumentException
*/
public function select(OutputInterface $output, $question, $choices, $default = null, $attempts = false, $errorMessage = 'Value "%s" is invalid', $multiselect = false)
{
$width = max(array_map('strlen', array_keys($choices)));
$messages = (array) $question;
foreach ($choices as $key => $value) {
$messages[] = sprintf(" [<info>%-${width}s</info>] %s", $key, $value);
}
$output->writeln($messages);
$result = $this->askAndValidate($output, '> ', function ($picked) use ($choices, $errorMessage, $multiselect) {
// Collapse all spaces.
$selectedChoices = str_replace(' ', '', $picked);
if ($multiselect) {
// Check for a separated comma values
if (!preg_match('/^[a-zA-Z0-9_-]+(?:,[a-zA-Z0-9_-]+)*$/', $selectedChoices, $matches)) {
throw new \InvalidArgumentException(sprintf($errorMessage, $picked));
}
$selectedChoices = explode(',', $selectedChoices);
} else {
$selectedChoices = array($picked);
}
$multiselectChoices = array();
foreach ($selectedChoices as $value) {
if (empty($choices[$value])) {
throw new \InvalidArgumentException(sprintf($errorMessage, $value));
}
$multiselectChoices[] = $value;
}
if ($multiselect) {
return $multiselectChoices;
}
return $picked;
}, $attempts, $default);
return $result;
}
/**
* Asks a question to the user.
*
* @param OutputInterface $output An Output instance
* @param string|array $question The question to ask
* @param string $default The default answer if none is given by the user
* @param array $autocomplete List of values to autocomplete
*
* @return string The user answer
*
* @throws \RuntimeException If there is no data to read in the input stream
*/
public function ask(OutputInterface $output, $question, $default = null, array $autocomplete = null)
{
if ($this->input && !$this->input->isInteractive()) {
return $default;
}
$output->write($question);
$inputStream = $this->inputStream ?: STDIN;
if (null === $autocomplete || !$this->hasSttyAvailable()) {
$ret = fgets($inputStream, 4096);
if (false === $ret) {
throw new \RuntimeException('Aborted');
}
$ret = trim($ret);
} else {
$ret = '';
$i = 0;
$ofs = -1;
$matches = $autocomplete;
$numMatches = count($matches);
$sttyMode = shell_exec('stty -g');
// Disable icanon (so we can fread each keypress) and echo (we'll do echoing here instead)
shell_exec('stty -icanon -echo');
// Add highlighted text style
$output->getFormatter()->setStyle('hl', new OutputFormatterStyle('black', 'white'));
// Read a keypress
while (!feof($inputStream)) {
$c = fread($inputStream, 1);
// Backspace Character
if ("\177" === $c) {
if (0 === $numMatches && 0 !== $i) {
--$i;
// Move cursor backwards
$output->write("\033[1D");
}
if ($i === 0) {
$ofs = -1;
$matches = $autocomplete;
$numMatches = count($matches);
} else {
$numMatches = 0;
}
// Pop the last character off the end of our string
$ret = substr($ret, 0, $i);
} elseif ("\033" === $c) {
// Did we read an escape sequence?
$c .= fread($inputStream, 2);
// A = Up Arrow. B = Down Arrow
if (isset($c[2]) && ('A' === $c[2] || 'B' === $c[2])) {
if ('A' === $c[2] && -1 === $ofs) {
$ofs = 0;
}
if (0 === $numMatches) {
continue;
}
$ofs += ('A' === $c[2]) ? -1 : 1;
$ofs = ($numMatches + $ofs) % $numMatches;
}
} elseif (ord($c) < 32) {
if ("\t" === $c || "\n" === $c) {
if ($numMatches > 0 && -1 !== $ofs) {
$ret = $matches[$ofs];
// Echo out remaining chars for current match
$output->write(substr($ret, $i));
$i = strlen($ret);
}
if ("\n" === $c) {
$output->write($c);
break;
}
$numMatches = 0;
}
continue;
} else {
$output->write($c);
$ret .= $c;
++$i;
$numMatches = 0;
$ofs = 0;
foreach ($autocomplete as $value) {
// If typed characters match the beginning chunk of value (e.g. [AcmeDe]moBundle)
if (0 === strpos($value, $ret) && $i !== strlen($value)) {
$matches[$numMatches++] = $value;
}
}
}
// Erase characters from cursor to end of line
$output->write("\033[K");
if ($numMatches > 0 && -1 !== $ofs) {
// Save cursor position
$output->write("\0337");
// Write highlighted text
$output->write('<hl>'.substr($matches[$ofs], $i).'</hl>');
// Restore cursor position
$output->write("\0338");
}
}
// Reset stty so it behaves normally again
shell_exec(sprintf('stty %s', $sttyMode));
}
return strlen($ret) > 0 ? $ret : $default;
}
/**
* Asks a confirmation to the user.
*
* The question will be asked until the user answers by nothing, yes, or no.
*
* @param OutputInterface $output An Output instance
* @param string|array $question The question to ask
* @param bool $default The default answer if the user enters nothing
*
* @return bool true if the user has confirmed, false otherwise
*/
public function askConfirmation(OutputInterface $output, $question, $default = true)
{
$answer = 'z';
while ($answer && !in_array(strtolower($answer[0]), array('y', 'n'))) {
$answer = $this->ask($output, $question);
}
if (false === $default) {
return $answer && 'y' == strtolower($answer[0]);
}
return !$answer || 'y' == strtolower($answer[0]);
}
/**
* Asks a question to the user, the response is hidden.
*
* @param OutputInterface $output An Output instance
* @param string|array $question The question
* @param bool $fallback In case the response can not be hidden, whether to fallback on non-hidden question or not
*
* @return string The answer
*
* @throws \RuntimeException In case the fallback is deactivated and the response can not be hidden
*/
public function askHiddenResponse(OutputInterface $output, $question, $fallback = true)
{
if ('\\' === DIRECTORY_SEPARATOR) {
$exe = __DIR__.'/../Resources/bin/hiddeninput.exe';
// handle code running from a phar
if ('phar:' === substr(__FILE__, 0, 5)) {
$tmpExe = sys_get_temp_dir().'/hiddeninput.exe';
copy($exe, $tmpExe);
$exe = $tmpExe;
}
$output->write($question);
$value = rtrim(shell_exec($exe));
$output->writeln('');
if (isset($tmpExe)) {
unlink($tmpExe);
}
return $value;
}
if ($this->hasSttyAvailable()) {
$output->write($question);
$sttyMode = shell_exec('stty -g');
shell_exec('stty -echo');
$value = fgets($this->inputStream ?: STDIN, 4096);
shell_exec(sprintf('stty %s', $sttyMode));
if (false === $value) {
throw new \RuntimeException('Aborted');
}
$value = trim($value);
$output->writeln('');
return $value;
}
if (false !== $shell = $this->getShell()) {
$output->write($question);
$readCmd = $shell === 'csh' ? 'set mypassword = $<' : 'read -r mypassword';
$command = sprintf("/usr/bin/env %s -c 'stty -echo; %s; stty echo; echo \$mypassword'", $shell, $readCmd);
$value = rtrim(shell_exec($command));
$output->writeln('');
return $value;
}
if ($fallback) {
return $this->ask($output, $question);
}
throw new \RuntimeException('Unable to hide the response');
}
/**
* Asks for a value and validates the response.
*
* The validator receives the data to validate. It must return the
* validated data when the data is valid and throw an exception
* otherwise.
*
* @param OutputInterface $output An Output instance
* @param string|array $question The question to ask
* @param callable $validator A PHP callback
* @param int|false $attempts Max number of times to ask before giving up (false by default, which means infinite)
* @param string $default The default answer if none is given by the user
* @param array $autocomplete List of values to autocomplete
*
* @return mixed
*
* @throws \Exception When any of the validators return an error
*/
public function askAndValidate(OutputInterface $output, $question, $validator, $attempts = false, $default = null, array $autocomplete = null)
{
$that = $this;
$interviewer = function () use ($output, $question, $default, $autocomplete, $that) {
return $that->ask($output, $question, $default, $autocomplete);
};
return $this->validateAttempts($interviewer, $output, $validator, $attempts);
}
/**
* Asks for a value, hide and validates the response.
*
* The validator receives the data to validate. It must return the
* validated data when the data is valid and throw an exception
* otherwise.
*
* @param OutputInterface $output An Output instance
* @param string|array $question The question to ask
* @param callable $validator A PHP callback
* @param int|false $attempts Max number of times to ask before giving up (false by default, which means infinite)
* @param bool $fallback In case the response can not be hidden, whether to fallback on non-hidden question or not
*
* @return string The response
*
* @throws \Exception When any of the validators return an error
* @throws \RuntimeException In case the fallback is deactivated and the response can not be hidden
*/
public function askHiddenResponseAndValidate(OutputInterface $output, $question, $validator, $attempts = false, $fallback = true)
{
$that = $this;
$interviewer = function () use ($output, $question, $fallback, $that) {
return $that->askHiddenResponse($output, $question, $fallback);
};
return $this->validateAttempts($interviewer, $output, $validator, $attempts);
}
/**
* Sets the input stream to read from when interacting with the user.
*
* This is mainly useful for testing purpose.
*
* @param resource $stream The input stream
*/
public function setInputStream($stream)
{
$this->inputStream = $stream;
}
/**
* Returns the helper's input stream.
*
* @return string
*/
public function getInputStream()
{
return $this->inputStream;
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'dialog';
}
/**
* Return a valid Unix shell.
*
* @return string|bool The valid shell name, false in case no valid shell is found
*/
private function getShell()
{
if (null !== self::$shell) {
return self::$shell;
}
self::$shell = false;
if (file_exists('/usr/bin/env')) {
// handle other OSs with bash/zsh/ksh/csh if available to hide the answer
$test = "/usr/bin/env %s -c 'echo OK' 2> /dev/null";
foreach (array('bash', 'zsh', 'ksh', 'csh') as $sh) {
if ('OK' === rtrim(shell_exec(sprintf($test, $sh)))) {
self::$shell = $sh;
break;
}
}
}
return self::$shell;
}
private function hasSttyAvailable()
{
if (null !== self::$stty) {
return self::$stty;
}
exec('stty 2>&1', $output, $exitcode);
return self::$stty = $exitcode === 0;
}
/**
* Validate an attempt.
*
* @param callable $interviewer A callable that will ask for a question and return the result
* @param OutputInterface $output An Output instance
* @param callable $validator A PHP callback
* @param int|false $attempts Max number of times to ask before giving up ; false will ask infinitely
*
* @return string The validated response
*
* @throws \Exception In case the max number of attempts has been reached and no valid response has been given
*/
private function validateAttempts($interviewer, OutputInterface $output, $validator, $attempts)
{
$e = null;
while (false === $attempts || $attempts--) {
if (null !== $e) {
$output->writeln($this->getHelperSet()->get('formatter')->formatBlock($e->getMessage(), 'error'));
}
try {
return call_user_func($validator, $interviewer());
} catch (\Exception $e) {
}
}
throw $e;
}
}
| ImaginationSydney/symfony | src/Symfony/Component/Console/Helper/DialogHelper.php | PHP | mit | 16,904 |
/*
TimelineJS - ver. 2.35.3 - 2015-02-17
Copyright (c) 2012-2013 Northwestern University
a project of the Northwestern University Knight Lab, originally created by Zach Wise
https://github.com/NUKnightLab/TimelineJS
This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
if(typeof VMM!="undefined"){VMM.Language={lang:"hi",api:{wikipedia:"hi"},date:{month:["जनवरी","फ़रवरी","मार्च","अप्रैल","मई","जून","जुलाई","अगस्त","सितम्बर","अक्टूबर","नवंबर","दिसंबर"],month_abbr:["जनवरी","फ़रवरी","मार्च","अप्रैल","मई","जून","जुलाई","अगस्त","सितम्बर","अक्टूबर","नवंबर","दिसंबर"],day:["रविवार","सोमवार","मंगलवार","बुधवार","गुरुवार","शुक्रवार","शनिवार"],day_abbr:["रवि","सोम","मंगल","बुध","गुरु","शुक्र","शनि"]},dateformats:{year:"yyyy",month_short:"mmm",month:"mmmm yyyy",full_short:"mmm d",full:"mmmm d',' yyyy",time_no_seconds_short:"h:MM TT",time_no_seconds_small_date:"h:MM TT'<br/><small>'mmmm d',' yyyy'</small>'",full_long:"mmm d',' yyyy 'at' h:MM TT",full_long_small_date:"h:MM TT'<br/><small>mmm d',' yyyy'</small>'"},messages:{loading_timeline:"टाइमलाइन लोड हो रहा है",return_to_title:"शीर्षक पर लौटें",expand_timeline:"टाइमलाइन का विस्तार करें",contract_timeline:"टाइमलाइन का अनुबंध करें",wikipedia:"विकिपीडिया, मुक्त विश्वकोश से",loading_content:"लोड हो रहा है सामग्री",loading:"लोड हो रहा है",swipe_nav:"Swipe to Navigate",read_more:"और पढ़ें"}}} | mzdani/cdnjs | ajax/libs/timelinejs/2.35.3/js/locale/hi.js | JavaScript | mit | 2,163 |
.oo-ui-icon-alignCentre{background-image:url(themes/mediawiki/images/icons/align-center.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/align-center.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/align-center.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/align-center.png)}.oo-ui-image-invert.oo-ui-icon-alignCentre{background-image:url(themes/mediawiki/images/icons/align-center-invert.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/align-center-invert.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/align-center-invert.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/align-center-invert.png)}.oo-ui-icon-alignLeft{background-image:url(themes/mediawiki/images/icons/align-float-left.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/align-float-left.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/align-float-left.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/align-float-left.png)}.oo-ui-image-invert.oo-ui-icon-alignLeft{background-image:url(themes/mediawiki/images/icons/align-float-left-invert.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/align-float-left-invert.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/align-float-left-invert.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/align-float-left-invert.png)}.oo-ui-icon-alignRight{background-image:url(themes/mediawiki/images/icons/align-float-right.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/align-float-right.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/align-float-right.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/align-float-right.png)}.oo-ui-image-invert.oo-ui-icon-alignRight{background-image:url(themes/mediawiki/images/icons/align-float-right-invert.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/align-float-right-invert.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/align-float-right-invert.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/align-float-right-invert.png)}.oo-ui-icon-attachment{background-image:url(themes/mediawiki/images/icons/attachment-rtl.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/attachment-rtl.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/attachment-rtl.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/attachment-rtl.png)}.oo-ui-image-invert.oo-ui-icon-attachment{background-image:url(themes/mediawiki/images/icons/attachment-rtl-invert.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/attachment-rtl-invert.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/attachment-rtl-invert.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/attachment-rtl-invert.png)}.oo-ui-icon-calendar{background-image:url(themes/mediawiki/images/icons/calendar-rtl.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/calendar-rtl.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/calendar-rtl.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/calendar-rtl.png)}.oo-ui-image-invert.oo-ui-icon-calendar{background-image:url(themes/mediawiki/images/icons/calendar-rtl-invert.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/calendar-rtl-invert.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/calendar-rtl-invert.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/calendar-rtl-invert.png)}.oo-ui-icon-code{background-image:url(themes/mediawiki/images/icons/code.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/code.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/code.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/code.png)}.oo-ui-image-invert.oo-ui-icon-code{background-image:url(themes/mediawiki/images/icons/code-invert.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/code-invert.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/code-invert.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/code-invert.png)}.oo-ui-icon-find{background-image:url(themes/mediawiki/images/icons/find-rtl.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/find-rtl.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/find-rtl.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/find-rtl.png)}.oo-ui-image-invert.oo-ui-icon-find{background-image:url(themes/mediawiki/images/icons/find-rtl-invert.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/find-rtl-invert.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/find-rtl-invert.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/find-rtl-invert.png)}.oo-ui-icon-language{background-image:url(themes/mediawiki/images/icons/language-rtl.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/language-rtl.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/language-rtl.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/language-rtl.png)}.oo-ui-image-invert.oo-ui-icon-language{background-image:url(themes/mediawiki/images/icons/language-rtl-invert.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/language-rtl-invert.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/language-rtl-invert.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/language-rtl-invert.png)}.oo-ui-icon-layout{background-image:url(themes/mediawiki/images/icons/layout-rtl.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/layout-rtl.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/layout-rtl.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/layout-rtl.png)}.oo-ui-image-invert.oo-ui-icon-layout{background-image:url(themes/mediawiki/images/icons/layout-rtl-invert.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/layout-rtl-invert.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/layout-rtl-invert.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/layout-rtl-invert.png)}.oo-ui-icon-markup{background-image:url(themes/mediawiki/images/icons/markup.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/markup.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/markup.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/markup.png)}.oo-ui-image-invert.oo-ui-icon-markup{background-image:url(themes/mediawiki/images/icons/markup-invert.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/markup-invert.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/markup-invert.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/markup-invert.png)}.oo-ui-icon-newline{background-image:url(themes/mediawiki/images/icons/newline-rtl.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/newline-rtl.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/newline-rtl.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/newline-rtl.png)}.oo-ui-image-invert.oo-ui-icon-newline{background-image:url(themes/mediawiki/images/icons/newline-rtl-invert.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/newline-rtl-invert.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/newline-rtl-invert.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/newline-rtl-invert.png)}.oo-ui-icon-noWikiText{background-image:url(themes/mediawiki/images/icons/noWikiText-rtl.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/noWikiText-rtl.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/noWikiText-rtl.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/noWikiText-rtl.png)}.oo-ui-image-invert.oo-ui-icon-noWikiText{background-image:url(themes/mediawiki/images/icons/noWikiText-rtl-invert.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/noWikiText-rtl-invert.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/noWikiText-rtl-invert.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/noWikiText-rtl-invert.png)}.oo-ui-icon-outline{background-image:url(themes/mediawiki/images/icons/outline-rtl.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/outline-rtl.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/outline-rtl.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/outline-rtl.png)}.oo-ui-image-invert.oo-ui-icon-outline{background-image:url(themes/mediawiki/images/icons/outline-rtl-invert.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/outline-rtl-invert.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/outline-rtl-invert.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/outline-rtl-invert.png)}.oo-ui-icon-puzzle{background-image:url(themes/mediawiki/images/icons/puzzle-rtl.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/puzzle-rtl.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/puzzle-rtl.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/puzzle-rtl.png)}.oo-ui-image-invert.oo-ui-icon-puzzle{background-image:url(themes/mediawiki/images/icons/puzzle-rtl-invert.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/puzzle-rtl-invert.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/puzzle-rtl-invert.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/puzzle-rtl-invert.png)}.oo-ui-icon-quotes{background-image:url(themes/mediawiki/images/icons/quotes-rtl.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/quotes-rtl.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/quotes-rtl.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/quotes-rtl.png)}.oo-ui-image-invert.oo-ui-icon-quotes{background-image:url(themes/mediawiki/images/icons/quotes-rtl-invert.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/quotes-rtl-invert.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/quotes-rtl-invert.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/quotes-rtl-invert.png)}.oo-ui-icon-quotesAdd{background-image:url(themes/mediawiki/images/icons/quotesAdd-rtl.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/quotesAdd-rtl.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/quotesAdd-rtl.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/quotesAdd-rtl.png)}.oo-ui-image-invert.oo-ui-icon-quotesAdd{background-image:url(themes/mediawiki/images/icons/quotesAdd-rtl-invert.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/quotesAdd-rtl-invert.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/quotesAdd-rtl-invert.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/quotesAdd-rtl-invert.png)}.oo-ui-icon-redirect{background-image:url(themes/mediawiki/images/icons/articleRedirect-rtl.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/articleRedirect-rtl.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/articleRedirect-rtl.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/articleRedirect-rtl.png)}.oo-ui-image-invert.oo-ui-icon-redirect{background-image:url(themes/mediawiki/images/icons/articleRedirect-rtl-invert.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/articleRedirect-rtl-invert.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/articleRedirect-rtl-invert.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/articleRedirect-rtl-invert.png)}.oo-ui-icon-searchCaseSensitive{background-image:url(themes/mediawiki/images/icons/case-sensitive.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/case-sensitive.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/case-sensitive.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/case-sensitive.png)}.oo-ui-image-invert.oo-ui-icon-searchCaseSensitive{background-image:url(themes/mediawiki/images/icons/case-sensitive-invert.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/case-sensitive-invert.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/case-sensitive-invert.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/case-sensitive-invert.png)}.oo-ui-icon-searchRegularExpression{background-image:url(themes/mediawiki/images/icons/regular-expression.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/regular-expression.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/regular-expression.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/regular-expression.png)}.oo-ui-image-invert.oo-ui-icon-searchRegularExpression{background-image:url(themes/mediawiki/images/icons/regular-expression-invert.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/regular-expression-invert.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/regular-expression-invert.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/regular-expression-invert.png)}.oo-ui-icon-specialCharacter{background-image:url(themes/mediawiki/images/icons/specialCharacter.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/specialCharacter.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/specialCharacter.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/specialCharacter.png)}.oo-ui-image-invert.oo-ui-icon-specialCharacter{background-image:url(themes/mediawiki/images/icons/specialCharacter-invert.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/specialCharacter-invert.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/specialCharacter-invert.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/specialCharacter-invert.png)}.oo-ui-icon-table{background-image:url(themes/mediawiki/images/icons/table.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/table.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/table.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/table.png)}.oo-ui-image-invert.oo-ui-icon-table{background-image:url(themes/mediawiki/images/icons/table-invert.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/table-invert.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/table-invert.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/table-invert.png)}.oo-ui-icon-tableAddColumnAfter{background-image:url(themes/mediawiki/images/icons/table-insert-column-ltr.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/table-insert-column-ltr.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/table-insert-column-ltr.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/table-insert-column-ltr.png)}.oo-ui-image-invert.oo-ui-icon-tableAddColumnAfter{background-image:url(themes/mediawiki/images/icons/table-insert-column-ltr-invert.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/table-insert-column-ltr-invert.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/table-insert-column-ltr-invert.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/table-insert-column-ltr-invert.png)}.oo-ui-icon-tableAddColumnBefore{background-image:url(themes/mediawiki/images/icons/table-insert-column-rtl.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/table-insert-column-rtl.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/table-insert-column-rtl.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/table-insert-column-rtl.png)}.oo-ui-image-invert.oo-ui-icon-tableAddColumnBefore{background-image:url(themes/mediawiki/images/icons/table-insert-column-rtl-invert.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/table-insert-column-rtl-invert.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/table-insert-column-rtl-invert.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/table-insert-column-rtl-invert.png)}.oo-ui-icon-tableAddRowAfter{background-image:url(themes/mediawiki/images/icons/table-insert-row-after.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/table-insert-row-after.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/table-insert-row-after.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/table-insert-row-after.png)}.oo-ui-image-invert.oo-ui-icon-tableAddRowAfter{background-image:url(themes/mediawiki/images/icons/table-insert-row-after-invert.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/table-insert-row-after-invert.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/table-insert-row-after-invert.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/table-insert-row-after-invert.png)}.oo-ui-icon-tableAddRowBefore{background-image:url(themes/mediawiki/images/icons/table-insert-row-before.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/table-insert-row-before.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/table-insert-row-before.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/table-insert-row-before.png)}.oo-ui-image-invert.oo-ui-icon-tableAddRowBefore{background-image:url(themes/mediawiki/images/icons/table-insert-row-before-invert.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/table-insert-row-before-invert.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/table-insert-row-before-invert.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/table-insert-row-before-invert.png)}.oo-ui-icon-tableCaption{background-image:url(themes/mediawiki/images/icons/table-caption.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/table-caption.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/table-caption.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/table-caption.png)}.oo-ui-image-invert.oo-ui-icon-tableCaption{background-image:url(themes/mediawiki/images/icons/table-caption-invert.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/table-caption-invert.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/table-caption-invert.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/table-caption-invert.png)}.oo-ui-icon-tableMergeCells{background-image:url(themes/mediawiki/images/icons/table-merge-cells.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/table-merge-cells.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/table-merge-cells.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/table-merge-cells.png)}.oo-ui-image-invert.oo-ui-icon-tableMergeCells{background-image:url(themes/mediawiki/images/icons/table-merge-cells-invert.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/table-merge-cells-invert.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/table-merge-cells-invert.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/table-merge-cells-invert.png)}.oo-ui-icon-templateAdd{background-image:url(themes/mediawiki/images/icons/templateAdd-rtl.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/templateAdd-rtl.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/templateAdd-rtl.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/templateAdd-rtl.png)}.oo-ui-image-invert.oo-ui-icon-templateAdd{background-image:url(themes/mediawiki/images/icons/templateAdd-rtl-invert.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/templateAdd-rtl-invert.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/templateAdd-rtl-invert.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/templateAdd-rtl-invert.png)}.oo-ui-icon-translation{background-image:url(themes/mediawiki/images/icons/language-rtl.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/language-rtl.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/language-rtl.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/language-rtl.png)}.oo-ui-image-invert.oo-ui-icon-translation{background-image:url(themes/mediawiki/images/icons/language-rtl-invert.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/language-rtl-invert.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/language-rtl-invert.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/language-rtl-invert.png)}.oo-ui-icon-wikiText{background-image:url(themes/mediawiki/images/icons/wikiText.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/wikiText.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/wikiText.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/wikiText.png)}.oo-ui-image-invert.oo-ui-icon-wikiText{background-image:url(themes/mediawiki/images/icons/wikiText-invert.png);background-image:-webkit-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/wikiText-invert.svg);background-image:linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/wikiText-invert.svg);background-image:-o-linear-gradient(transparent,transparent),url(themes/mediawiki/images/icons/wikiText-invert.png)} | x112358/cdnjs | ajax/libs/oojs-ui/0.16.5/oojs-ui-mediawiki-icons-editing-advanced.rtl.min.css | CSS | mit | 27,816 |
YUI.add("node-core",function(c){var j=".",e="nodeName",n="nodeType",b="ownerDocument",m="tagName",d="_yuid",i={},p=Array.prototype.slice,f=c.DOM,k=function(r){if(!this.getDOMNode){return new k(r);}if(typeof r=="string"){r=k._fromString(r);if(!r){return null;}}var q=(r.nodeType!==9)?r.uniqueID:r[d];if(q&&k._instances[q]&&k._instances[q]._node!==r){r[d]=null;}q=q||c.stamp(r);if(!q){q=c.guid();}this[d]=q;this._node=r;this._stateProxy=r;if(this._initPlugins){this._initPlugins();}},o=function(r){var q=null;if(r){q=(typeof r=="string")?function(s){return c.Selector.test(s,r);}:function(s){return r(c.one(s));};}return q;};k.ATTRS={};k.DOM_EVENTS={};k._fromString=function(q){if(q){if(q.indexOf("doc")===0){q=c.config.doc;}else{if(q.indexOf("win")===0){q=c.config.win;}else{q=c.Selector.query(q,null,true);}}}return q||null;};k.NAME="node";k.re_aria=/^(?:role$|aria-)/;k.SHOW_TRANSITION="fadeIn";k.HIDE_TRANSITION="fadeOut";k._instances={};k.getDOMNode=function(q){if(q){return(q.nodeType)?q:q._node||null;}return null;};k.scrubVal=function(r,q){if(r){if(typeof r=="object"||typeof r=="function"){if(n in r||f.isWindow(r)){r=c.one(r);}else{if((r.item&&!r._nodes)||(r[0]&&r[0][n])){r=c.all(r);}}}}else{if(typeof r==="undefined"){r=q;}else{if(r===null){r=null;}}}return r;};k.addMethod=function(q,s,r){if(q&&s&&typeof s=="function"){k.prototype[q]=function(){var u=p.call(arguments),v=this,t;if(u[0]&&u[0]._node){u[0]=u[0]._node;}if(u[1]&&u[1]._node){u[1]=u[1]._node;}u.unshift(v._node);t=s.apply(v,u);if(t){t=k.scrubVal(t,v);}(typeof t!="undefined")||(t=v);return t;};}else{}};k.importMethod=function(s,q,r){if(typeof q=="string"){r=r||q;k.addMethod(r,s[q],s);}else{c.Array.each(q,function(t){k.importMethod(s,t);});}};k.one=function(t){var q=null,s,r;if(t){if(typeof t=="string"){t=k._fromString(t);if(!t){return null;}}else{if(t.getDOMNode){return t;}}if(t.nodeType||c.DOM.isWindow(t)){r=(t.uniqueID&&t.nodeType!==9)?t.uniqueID:t._yuid;q=k._instances[r];s=q?q._node:null;if(!q||(s&&t!==s)){q=new k(t);if(t.nodeType!=11){k._instances[q[d]]=q;}}}}return q;};k.DEFAULT_SETTER=function(q,s){var r=this._stateProxy,t;if(q.indexOf(j)>-1){t=q;q=q.split(j);c.Object.setValue(r,q,s);}else{if(typeof r[q]!="undefined"){r[q]=s;}}return s;};k.DEFAULT_GETTER=function(q){var r=this._stateProxy,s;if(q.indexOf&&q.indexOf(j)>-1){s=c.Object.getValue(r,q.split(j));}else{if(typeof r[q]!="undefined"){s=r[q];}}return s;};c.mix(k.prototype,{DATA_PREFIX:"data-",toString:function(){var t=this[d]+": not bound to a node",s=this._node,q,u,r;if(s){q=s.attributes;u=(q&&q.id)?s.getAttribute("id"):null;r=(q&&q.className)?s.getAttribute("className"):null;t=s[e];if(u){t+="#"+u;}if(r){t+="."+r.replace(" ",".");}t+=" "+this[d];}return t;},get:function(q){var r;if(this._getAttr){r=this._getAttr(q);}else{r=this._get(q);}if(r){r=k.scrubVal(r,this);}else{if(r===null){r=null;}}return r;},_get:function(q){var r=k.ATTRS[q],s;if(r&&r.getter){s=r.getter.call(this);}else{if(k.re_aria.test(q)){s=this._node.getAttribute(q,2);}else{s=k.DEFAULT_GETTER.apply(this,arguments);}}return s;},set:function(q,s){var r=k.ATTRS[q];if(this._setAttr){this._setAttr.apply(this,arguments);}else{if(r&&r.setter){r.setter.call(this,s,q);}else{if(k.re_aria.test(q)){this._node.setAttribute(q,s);}else{k.DEFAULT_SETTER.apply(this,arguments);}}}return this;},setAttrs:function(q){if(this._setAttrs){this._setAttrs(q);}else{c.Object.each(q,function(r,s){this.set(s,r);},this);}return this;},getAttrs:function(r){var q={};if(this._getAttrs){this._getAttrs(r);}else{c.Array.each(r,function(s,t){q[s]=this.get(s);},this);}return q;},compareTo:function(q){var r=this._node;if(q&&q._node){q=q._node;}return r===q;},inDoc:function(r){var q=this._node;r=(r)?r._node||r:q[b];if(r.documentElement){return f.contains(r.documentElement,q);}},getById:function(s){var r=this._node,q=f.byId(s,r[b]);if(q&&f.contains(r,q)){q=c.one(q);}else{q=null;}return q;},ancestor:function(q,s,r){if(arguments.length===2&&(typeof s=="string"||typeof s=="function")){r=s;}return c.one(f.ancestor(this._node,o(q),s,o(r)));},ancestors:function(q,s,r){if(arguments.length===2&&(typeof s=="string"||typeof s=="function")){r=s;}return c.all(f.ancestors(this._node,o(q),s,o(r)));},previous:function(r,q){return c.one(f.elementByAxis(this._node,"previousSibling",o(r),q));},next:function(r,q){return c.one(f.elementByAxis(this._node,"nextSibling",o(r),q));},siblings:function(q){return c.all(f.siblings(this._node,o(q)));},one:function(q){return c.one(c.Selector.query(q,this._node,true));},all:function(q){var r=c.all(c.Selector.query(q,this._node));r._query=q;r._queryRoot=this._node;return r;},test:function(q){return c.Selector.test(this._node,q);},remove:function(q){var r=this._node;if(r&&r.parentNode){r.parentNode.removeChild(r);}if(q){this.destroy();}return this;},replace:function(q){var r=this._node;if(typeof q=="string"){q=k.create(q);}r.parentNode.replaceChild(k.getDOMNode(q),r);return this;},replaceChild:function(r,q){if(typeof r=="string"){r=f.create(r);}return c.one(this._node.replaceChild(k.getDOMNode(r),k.getDOMNode(q)));},destroy:function(s){var r=c.config.doc.uniqueID?"uniqueID":"_yuid",q;this.purge();if(this.unplug){this.unplug();}this.clearData();if(s){c.NodeList.each(this.all("*"),function(t){q=k._instances[t[r]];if(q){q.destroy();}});}this._node=null;this._stateProxy=null;delete k._instances[this._yuid];},invoke:function(x,r,q,w,v,u){var t=this._node,s;if(r&&r._node){r=r._node;}if(q&&q._node){q=q._node;}s=t[x](r,q,w,v,u);return k.scrubVal(s,this);},swap:c.config.doc.documentElement.swapNode?function(q){this._node.swapNode(k.getDOMNode(q));}:function(q){q=k.getDOMNode(q);var s=this._node,r=q.parentNode,t=q.nextSibling;if(t===s){r.insertBefore(s,q);}else{if(q===s.nextSibling){r.insertBefore(q,s);}else{s.parentNode.replaceChild(q,s);f.addHTML(r,s,t);}}return this;},hasMethod:function(r){var q=this._node;return !!(q&&r in q&&typeof q[r]!="unknown"&&(typeof q[r]=="function"||String(q[r]).indexOf("function")===1));},isFragment:function(){return(this.get("nodeType")===11);
},empty:function(){this.get("childNodes").remove().destroy(true);return this;},getDOMNode:function(){return this._node;}},true);c.Node=k;c.one=k.one;var a=function(q){var r=[];if(q){if(typeof q==="string"){this._query=q;q=c.Selector.query(q);}else{if(q.nodeType||f.isWindow(q)){q=[q];}else{if(q._node){q=[q._node];}else{if(q[0]&&q[0]._node){c.Array.each(q,function(s){if(s._node){r.push(s._node);}});q=r;}else{q=c.Array(q,0,true);}}}}}this._nodes=q||[];};a.NAME="NodeList";a.getDOMNodes=function(q){return(q&&q._nodes)?q._nodes:q;};a.each=function(q,t,s){var r=q._nodes;if(r&&r.length){c.Array.each(r,t,s||q);}else{}};a.addMethod=function(q,s,r){if(q&&s){a.prototype[q]=function(){var u=[],t=arguments;c.Array.each(this._nodes,function(z){var y=(z.uniqueID&&z.nodeType!==9)?"uniqueID":"_yuid",w=c.Node._instances[z[y]],x,v;if(!w){w=a._getTempNode(z);}x=r||w;v=s.apply(x,t);if(v!==undefined&&v!==w){u[u.length]=v;}});return u.length?u:this;};}else{}};a.importMethod=function(s,q,r){if(typeof q==="string"){r=r||q;a.addMethod(q,s[q]);}else{c.Array.each(q,function(t){a.importMethod(s,t);});}};a._getTempNode=function(r){var q=a._tempNode;if(!q){q=c.Node.create("<div></div>");a._tempNode=q;}q._node=r;q._stateProxy=r;return q;};c.mix(a.prototype,{_invoke:function(t,s,q){var r=(q)?[]:this;this.each(function(u){var v=u[t].apply(u,s);if(q){r.push(v);}});return r;},item:function(q){return c.one((this._nodes||[])[q]);},each:function(s,r){var q=this;c.Array.each(this._nodes,function(u,t){u=c.one(u);return s.call(r||u,u,t,q);});return q;},batch:function(r,q){var s=this;c.Array.each(this._nodes,function(v,u){var t=c.Node._instances[v[d]];if(!t){t=a._getTempNode(v);}return r.call(q||t,t,u,s);});return s;},some:function(s,r){var q=this;return c.Array.some(this._nodes,function(u,t){u=c.one(u);r=r||u;return s.call(r,u,t,q);});},toFrag:function(){return c.one(c.DOM._nl2frag(this._nodes));},indexOf:function(q){return c.Array.indexOf(this._nodes,c.Node.getDOMNode(q));},filter:function(q){return c.all(c.Selector.filter(this._nodes,q));},modulus:function(t,s){s=s||0;var q=[];a.each(this,function(u,r){if(r%t===s){q.push(u);}});return c.all(q);},odd:function(){return this.modulus(2,1);},even:function(){return this.modulus(2);},destructor:function(){},refresh:function(){var t,r=this._nodes,s=this._query,q=this._queryRoot;if(s){if(!q){if(r&&r[0]&&r[0].ownerDocument){q=r[0].ownerDocument;}}this._nodes=c.Selector.query(s,q);}return this;},size:function(){return this._nodes.length;},isEmpty:function(){return this._nodes.length<1;},toString:function(){var t="",s=this[d]+": not bound to any nodes",q=this._nodes,r;if(q&&q[0]){r=q[0];t+=r[e];if(r.id){t+="#"+r.id;}if(r.className){t+="."+r.className.replace(" ",".");}if(q.length>1){t+="...["+q.length+" items]";}}return t||s;},getDOMNodes:function(){return this._nodes;}},true);a.importMethod(c.Node.prototype,["destroy","empty","remove","set"]);a.prototype.get=function(r){var u=[],t=this._nodes,s=false,v=a._getTempNode,q,w;if(t[0]){q=c.Node._instances[t[0]._yuid]||v(t[0]);w=q._get(r);if(w&&w.nodeType){s=true;}}c.Array.each(t,function(x){q=c.Node._instances[x._yuid];if(!q){q=v(x);}w=q._get(r);if(!s){w=c.Node.scrubVal(w,q);}u.push(w);});return(s)?c.all(u):u;};c.NodeList=a;c.all=function(q){return new a(q);};c.Node.all=c.all;var l=c.NodeList,h=Array.prototype,g={"concat":1,"pop":0,"push":0,"shift":0,"slice":1,"splice":1,"unshift":0};c.Object.each(g,function(r,q){l.prototype[q]=function(){var u=[],v=0,s,t;while(typeof(s=arguments[v++])!="undefined"){u.push(s._node||s._nodes||s);}t=h[q].apply(this._nodes,u);if(r){t=c.all(t);}else{t=c.Node.scrubVal(t);}return t;};});c.Array.each(["removeChild","hasChildNodes","cloneNode","hasAttribute","scrollIntoView","getElementsByTagName","focus","blur","submit","reset","select","createCaption"],function(q){c.Node.prototype[q]=function(u,s,r){var t=this.invoke(q,u,s,r);return t;};});c.Node.prototype.removeAttribute=function(q){var r=this._node;if(r){r.removeAttribute(q);}return this;};c.Node.importMethod(c.DOM,["contains","setAttribute","getAttribute","wrap","unwrap","generateID"]);c.NodeList.importMethod(c.Node.prototype,["getAttribute","setAttribute","removeAttribute","unwrap","wrap","generateID"]);},"@VERSION@",{requires:["dom-core","selector"]}); | CyrusSUEN/cdnjs | ajax/libs/yui/3.5.0/node-core/node-core-min.js | JavaScript | mit | 10,282 |
YUI.add('event-delegate', function(Y) {
/**
* Adds event delegation support to the library.
*
* @module event
* @submodule event-delegate
*/
var toArray = Y.Array,
YLang = Y.Lang,
isString = YLang.isString,
isObject = YLang.isObject,
isArray = YLang.isArray,
selectorTest = Y.Selector.test,
detachCategories = Y.Env.evt.handles;
/**
* <p>Sets up event delegation on a container element. The delegated event
* will use a supplied selector or filtering function to test if the event
* references at least one node that should trigger the subscription
* callback.</p>
*
* <p>Selector string filters will trigger the callback if the event originated
* from a node that matches it or is contained in a node that matches it.
* Function filters are called for each Node up the parent axis to the
* subscribing container node, and receive at each level the Node and the event
* object. The function should return true (or a truthy value) if that Node
* should trigger the subscription callback. Note, it is possible for filters
* to match multiple Nodes for a single event. In this case, the delegate
* callback will be executed for each matching Node.</p>
*
* <p>For each matching Node, the callback will be executed with its 'this'
* object set to the Node matched by the filter (unless a specific context was
* provided during subscription), and the provided event's
* <code>currentTarget</code> will also be set to the matching Node. The
* containing Node from which the subscription was originally made can be
* referenced as <code>e.container</code>.
*
* @method delegate
* @param type {String} the event type to delegate
* @param fn {Function} the callback function to execute. This function
* will be provided the event object for the delegated event.
* @param el {String|node} the element that is the delegation container
* @param spec {string|Function} a selector that must match the target of the
* event or a function to test target and its parents for a match
* @param context optional argument that specifies what 'this' refers to.
* @param args* 0..n additional arguments to pass on to the callback function.
* These arguments will be added after the event object.
* @return {EventHandle} the detach handle
* @for YUI
*/
function delegate(type, fn, el, filter) {
var args = toArray(arguments, 0, true),
query = isString(el) ? el : null,
typeBits, synth, container, categories, cat, i, len, handles, handle;
// Support Y.delegate({ click: fnA, key: fnB }, context, filter, ...);
// and Y.delegate(['click', 'key'], fn, context, filter, ...);
if (isObject(type)) {
handles = [];
if (isArray(type)) {
for (i = 0, len = type.length; i < len; ++i) {
args[0] = type[i];
handles.push(Y.delegate.apply(Y, args));
}
} else {
// Y.delegate({'click', fn}, context, filter) =>
// Y.delegate('click', fn, context, filter)
args.unshift(null); // one arg becomes two; need to make space
for (i in type) {
if (type.hasOwnProperty(i)) {
args[0] = i;
args[1] = type[i];
handles.push(Y.delegate.apply(Y, args));
}
}
}
return new Y.EventHandle(handles);
}
typeBits = type.split(/\|/);
if (typeBits.length > 1) {
cat = typeBits.shift();
args[0] = type = typeBits.shift();
}
synth = Y.Node.DOM_EVENTS[type];
if (isObject(synth) && synth.delegate) {
handle = synth.delegate.apply(synth, arguments);
}
if (!handle) {
if (!type || !fn || !el || !filter) {
Y.log("delegate requires type, callback, parent, & filter", "warn");
return;
}
container = (query) ? Y.Selector.query(query, null, true) : el;
if (!container && isString(el)) {
handle = Y.on('available', function () {
Y.mix(handle, Y.delegate.apply(Y, args), true);
}, el);
}
if (!handle && container) {
args.splice(2, 2, container); // remove the filter
handle = Y.Event._attach(args, { facade: false });
handle.sub.filter = filter;
handle.sub._notify = delegate.notifySub;
}
}
if (handle && cat) {
categories = detachCategories[cat] || (detachCategories[cat] = {});
categories = categories[type] || (categories[type] = []);
categories.push(handle);
}
return handle;
}
/**
* Overrides the <code>_notify</code> method on the normal DOM subscription to
* inject the filtering logic and only proceed in the case of a match.
*
* @method delegate.notifySub
* @param thisObj {Object} default 'this' object for the callback
* @param args {Array} arguments passed to the event's <code>fire()</code>
* @param ce {CustomEvent} the custom event managing the DOM subscriptions for
* the subscribed event on the subscribing node.
* @return {Boolean} false if the event was stopped
* @private
* @static
* @since 3.2.0
*/
delegate.notifySub = function (thisObj, args, ce) {
// Preserve args for other subscribers
args = args.slice();
if (this.args) {
args.push.apply(args, this.args);
}
// Only notify subs if the event occurred on a targeted element
var currentTarget = delegate._applyFilter(this.filter, args, ce),
//container = e.currentTarget,
e, i, len, ret;
if (currentTarget) {
// Support multiple matches up the the container subtree
currentTarget = toArray(currentTarget);
// The second arg is the currentTarget, but we'll be reusing this
// facade, replacing the currentTarget for each use, so it doesn't
// matter what element we seed it with.
e = args[0] = new Y.DOMEventFacade(args[0], ce.el, ce);
e.container = Y.one(ce.el);
for (i = 0, len = currentTarget.length; i < len && !e.stopped; ++i) {
e.currentTarget = Y.one(currentTarget[i]);
ret = this.fn.apply(this.context || e.currentTarget, args);
if (ret === false) { // stop further notifications
break;
}
}
return ret;
}
};
/**
* <p>Compiles a selector string into a filter function to identify whether
* Nodes along the parent axis of an event's target should trigger event
* notification.</p>
*
* <p>This function is memoized, so previously compiled filter functions are
* returned if the same selector string is provided.</p>
*
* <p>This function may be useful when defining synthetic events for delegate
* handling.</p>
*
* @method delegate.compileFilter
* @param selector {String} the selector string to base the filtration on
* @return {Function}
* @since 3.2.0
* @static
*/
delegate.compileFilter = Y.cached(function (selector) {
return function (target, e) {
return selectorTest(target._node, selector, e.currentTarget._node);
};
});
/**
* Walks up the parent axis of an event's target, and tests each element
* against a supplied filter function. If any Nodes, including the container,
* satisfy the filter, the delegated callback will be triggered for each.
*
* @method delegate._applyFilter
* @param filter {Function} boolean function to test for inclusion in event
* notification
* @param args {Array} the arguments that would be passed to subscribers
* @param ce {CustomEvent} the DOM event wrapper
* @return {Node|Node[]|undefined} The Node or Nodes that satisfy the filter
* @protected
*/
delegate._applyFilter = function (filter, args, ce) {
var e = args[0],
container = ce.el, // facadeless events in IE, have no e.currentTarget
target = e.target || e.srcElement,
match = [],
isContainer = false;
// Resolve text nodes to their containing element
if (target.nodeType === 3) {
target = target.parentNode;
}
// passing target as the first arg rather than leaving well enough alone
// making 'this' in the filter function refer to the target. This is to
// support bound filter functions.
args.unshift(target);
if (isString(filter)) {
while (target) {
isContainer = (target === container);
if (selectorTest(target, filter, (isContainer ?null: container))) {
match.push(target);
}
if (isContainer) {
break;
}
target = target.parentNode;
}
} else {
// filter functions are implementer code and should receive wrappers
args[0] = Y.one(target);
args[1] = new Y.DOMEventFacade(e, container, ce);
while (target) {
// filter(target, e, extra args...) - this === target
if (filter.apply(args[0], args)) {
match.push(target);
}
if (target === container) {
break;
}
target = target.parentNode;
args[0] = Y.one(target);
}
args[1] = e; // restore the raw DOM event
}
if (match.length <= 1) {
match = match[0]; // single match or undefined
}
// remove the target
args.shift();
return match;
};
/**
* Sets up event delegation on a container element. The delegated event
* will use a supplied filter to test if the callback should be executed.
* This filter can be either a selector string or a function that returns
* a Node to use as the currentTarget for the event.
*
* The event object for the delegated event is supplied to the callback
* function. It is modified slightly in order to support all properties
* that may be needed for event delegation. 'currentTarget' is set to
* the element that matched the selector string filter or the Node returned
* from the filter function. 'container' is set to the element that the
* listener is delegated from (this normally would be the 'currentTarget').
*
* Filter functions will be called with the arguments that would be passed to
* the callback function, including the event object as the first parameter.
* The function should return false (or a falsey value) if the success criteria
* aren't met, and the Node to use as the event's currentTarget and 'this'
* object if they are.
*
* @method delegate
* @param type {string} the event type to delegate
* @param fn {function} the callback function to execute. This function
* will be provided the event object for the delegated event.
* @param el {string|node} the element that is the delegation container
* @param filter {string|function} a selector that must match the target of the
* event or a function that returns a Node or false.
* @param context optional argument that specifies what 'this' refers to.
* @param args* 0..n additional arguments to pass on to the callback function.
* These arguments will be added after the event object.
* @return {EventHandle} the detach handle
* @for YUI
*/
Y.delegate = Y.Event.delegate = delegate;
}, '@VERSION@' ,{requires:['node-base']});
| jrbasso/cdnjs | ajax/libs/yui/3.4.0/event-delegate/event-delegate-debug.js | JavaScript | mit | 11,378 |
<?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\Config\Definition\Builder;
use Symfony\Component\Config\Definition\EnumNode;
/**
* Enum Node Definition.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
class EnumNodeDefinition extends ScalarNodeDefinition
{
private $values;
public function values(array $values)
{
$values = array_unique($values);
if (count($values) <= 1) {
throw new \InvalidArgumentException('->values() must be called with at least two distinct values.');
}
$this->values = $values;
return $this;
}
/**
* Instantiate a Node
*
* @return EnumNode The node
*
* @throws \RuntimeException
*/
protected function instantiateNode()
{
if (null === $this->values) {
throw new \RuntimeException('You must call ->values() on enum nodes.');
}
return new EnumNode($this->name, $this->parent, $this->values);
}
}
| LeQuangAnh/USVTracking | vendor/symfony/symfony/src/Symfony/Component/Config/Definition/Builder/EnumNodeDefinition.php | PHP | mit | 1,207 |
<?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\Config\Definition\Builder;
use Symfony\Component\Config\Definition\EnumNode;
/**
* Enum Node Definition.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
class EnumNodeDefinition extends ScalarNodeDefinition
{
private $values;
public function values(array $values)
{
$values = array_unique($values);
if (count($values) <= 1) {
throw new \InvalidArgumentException('->values() must be called with at least two distinct values.');
}
$this->values = $values;
return $this;
}
/**
* Instantiate a Node
*
* @return EnumNode The node
*
* @throws \RuntimeException
*/
protected function instantiateNode()
{
if (null === $this->values) {
throw new \RuntimeException('You must call ->values() on enum nodes.');
}
return new EnumNode($this->name, $this->parent, $this->values);
}
}
| Leagueify/Symfony | vendor/symfony/symfony/src/Symfony/Component/Config/Definition/Builder/EnumNodeDefinition.php | PHP | mit | 1,207 |
YUI.add('datasource-cache', function(Y) {
/**
* Plugs DataSource with caching functionality.
*
* @module datasource
* @submodule datasource-cache
*/
/**
* DataSourceCache extension binds Cache to DataSource.
* @class DataSourceCacheExtension
*/
var DataSourceCacheExtension = function() {
};
Y.mix(DataSourceCacheExtension, {
/**
* The namespace for the plugin. This will be the property on the host which
* references the plugin instance.
*
* @property NS
* @type String
* @static
* @final
* @value "cache"
*/
NS: "cache",
/**
* Class name.
*
* @property NAME
* @type String
* @static
* @final
* @value "dataSourceCacheExtension"
*/
NAME: "dataSourceCacheExtension"
});
DataSourceCacheExtension.prototype = {
/**
* Internal init() handler.
*
* @method initializer
* @param config {Object} Config object.
* @private
*/
initializer: function(config) {
this.doBefore("_defRequestFn", this._beforeDefRequestFn);
this.doBefore("_defResponseFn", this._beforeDefResponseFn);
},
/**
* First look for cached response, then send request to live data.
*
* @method _beforeDefRequestFn
* @param e {Event.Facade} Event Facade with the following properties:
* <dl>
* <dt>tId (Number)</dt> <dd>Unique transaction ID.</dd>
* <dt>request (Object)</dt> <dd>The request.</dd>
* <dt>callback (Object)</dt> <dd>The callback object.</dd>
* <dt>cfg (Object)</dt> <dd>Configuration object.</dd>
* </dl>
* @protected
*/
_beforeDefRequestFn: function(e) {
// Is response already in the Cache?
var entry = (this.retrieve(e.request)) || null;
if(entry && entry.response) {
this.get("host").fire("response", Y.mix(entry, e));
return new Y.Do.Halt("DataSourceCache extension halted _defRequestFn");
}
},
/**
* Adds data to cache before returning data.
*
* @method _beforeDefResponseFn
* @param e {Event.Facade} Event Facade with the following properties:
* <dl>
* <dt>tId (Number)</dt> <dd>Unique transaction ID.</dd>
* <dt>request (Object)</dt> <dd>The request.</dd>
* <dt>callback (Object)</dt> <dd>The callback object with the following properties:
* <dl>
* <dt>success (Function)</dt> <dd>Success handler.</dd>
* <dt>failure (Function)</dt> <dd>Failure handler.</dd>
* </dl>
* </dd>
* <dt>data (Object)</dt> <dd>Raw data.</dd>
* <dt>response (Object)</dt> <dd>Normalized response object with the following properties:
* <dl>
* <dt>cached (Object)</dt> <dd>True when response is cached.</dd>
* <dt>results (Object)</dt> <dd>Parsed results.</dd>
* <dt>meta (Object)</dt> <dd>Parsed meta data.</dd>
* <dt>error (Object)</dt> <dd>Error object.</dd>
* </dl>
* </dd>
* <dt>cfg (Object)</dt> <dd>Configuration object.</dd>
* </dl>
* @protected
*/
_beforeDefResponseFn: function(e) {
// Add to Cache before returning
if(e.response && !e.cached) {
this.add(e.request, e.response);
}
}
};
Y.namespace("Plugin").DataSourceCacheExtension = DataSourceCacheExtension;
/**
* DataSource plugin adds cache functionality.
* @class DataSourceCache
* @extends Cache
* @uses Plugin.Base, DataSourceCachePlugin
*/
function DataSourceCache(config) {
var cache = config && config.cache ? config.cache : Y.Cache,
tmpclass = Y.Base.create("dataSourceCache", cache, [Y.Plugin.Base, Y.Plugin.DataSourceCacheExtension]),
tmpinstance = new tmpclass(config);
tmpclass.NS = "tmpClass";
return tmpinstance;
}
Y.mix(DataSourceCache, {
/**
* The namespace for the plugin. This will be the property on the host which
* references the plugin instance.
*
* @property NS
* @type String
* @static
* @final
* @value "cache"
*/
NS: "cache",
/**
* Class name.
*
* @property NAME
* @type String
* @static
* @final
* @value "dataSourceCache"
*/
NAME: "dataSourceCache"
});
Y.namespace("Plugin").DataSourceCache = DataSourceCache;
}, '@VERSION@' ,{requires:['datasource-local', 'cache-base']});
| pombredanne/cdnjs | ajax/libs/yui/3.3.0/datasource/datasource-cache-debug.js | JavaScript | mit | 4,408 |
/*
* jQuery UI CSS Framework 1.8.16
*
* Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* http://docs.jquery.com/UI/Theming/API
*/
/* Layout helpers
----------------------------------*/
.ui-helper-hidden { display: none; }
.ui-helper-hidden-accessible { position: absolute !important; clip: rect(1px 1px 1px 1px); clip: rect(1px,1px,1px,1px); }
.ui-helper-reset { margin: 0; padding: 0; border: 0; outline: 0; line-height: 1.3; text-decoration: none; font-size: 100%; list-style: none; }
.ui-helper-clearfix:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; }
.ui-helper-clearfix { display: inline-block; }
/* required comment for clearfix to work in Opera \*/
* html .ui-helper-clearfix { height:1%; }
.ui-helper-clearfix { display:block; }
/* end clearfix */
.ui-helper-zfix { width: 100%; height: 100%; top: 0; left: 0; position: absolute; opacity: 0; filter:Alpha(Opacity=0); }
/* Interaction Cues
----------------------------------*/
.ui-state-disabled { cursor: default !important; }
/* Icons
----------------------------------*/
/* states and images */
.ui-icon { display: block; text-indent: -99999px; overflow: hidden; background-repeat: no-repeat; }
/* Misc visuals
----------------------------------*/
/* Overlays */
.ui-widget-overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
| aruis/baiducdnstatic | libs/jqueryui/1.8.16/themes/le-frog/jquery.ui.core.css | CSS | mit | 1,459 |
webshims.register('jme', function($, webshims, window, doc, undefined){
"use strict";
var props = {};
var fns = {};
var slice = Array.prototype.slice;
var options = $.extend({selector: '.mediaplayer'}, webshims.cfg.mediaelement.jme);
webshims.cfg.mediaelement.jme = options;
$.jme = {
plugins: {},
data: function(elem, name, value){
var data = $(elem).data('jme') || $.data(elem, 'jme', {});
if(value === undefined){
return (name) ? data[name] : data;
} else {
data[name] = value;
}
},
registerPlugin: function(name, plugin){
this.plugins[name] = plugin;
if(!plugin.nodeName){
plugin.nodeName = '';
}
if(!plugin.className){
plugin.className = name;
}
options[name] = $.extend(plugin.options || {}, options[name]);
if(options[name] && options[name].text){
plugin.text = options[name].text;
} else if(options.i18n && options.i18n[name]){
plugin.text = options.i18n[name];
}
},
defineMethod: function(name, fn){
fns[name] = fn;
},
defineProp: function(name, desc){
if(!desc){
desc = {};
}
if(!desc.set){
if(desc.readonly){
desc.set = function(){
throw(name +' is readonly');
};
} else {
desc.set = $.noop;
}
}
if(!desc.get){
desc.get = function(elem){
return $.jme.data(elem, name);
};
}
props[name] = desc;
},
prop: function(elem, name, value){
if(!props[name]){
return $.prop(elem, name, value);
}
if(value === undefined){
return props[name].get( elem );
} else {
var setValue = props[name].set(elem, value);
if(setValue === undefined){
setValue = value;
}
if(setValue != 'noDataSet'){
$.jme.data(elem, name, setValue);
}
}
}
};
$.fn.jmeProp = function(name, value){
return $.access( this, $.jme.prop, name, value, arguments.length > 1 );
};
$.fn.jmeFn = function(fn){
var args = slice.call( arguments, 1 );
var ret;
this.each(function(){
ret = (fns[fn] || $.prop(this, fn)).apply(this, args);
if(ret !== undefined){
return false;
}
});
return (ret !== undefined) ? ret : this;
};
var idlStates = {
emptied: 1,
pause: 1
};
var unwaitingEvents = {
canplay: 1, canplaythrough: 1
};
var baseSelector = options.selector;
$.jme.initJME = function(context, insertedElement){
$(baseSelector, context).add(insertedElement.filter(baseSelector)).jmePlayer();
};
$.jme.getDOMList = function(attr){
var list = [];
if(!attr){
attr = [];
}
if(typeof attr == 'string'){
attr = attr.split(' ');
}
$.each(attr, function(i, id){
if(id){
id = document.getElementById(id);
if(id){
list.push(id);
}
}
});
return list;
};
$.jme.getButtonText = function(button, classes){
var isCheckbox;
var lastState;
var txtChangeFn = function(state){
if(lastState === state){return;}
lastState = state;
button
.removeClass(classes[(state) ? 0 : 1])
.addClass(classes[state])
;
if(isCheckbox){
button.prop('checked', !!state);
(button.data('checkboxradio') || {refresh: $.noop}).refresh();
}
};
if (button.is('[type="checkbox"], [type="radio"]')){
button.prop('checked', function(){
return this.defaultChecked;
});
isCheckbox = true;
} else if(button.is('a')){
button.on('click', function(e){
e.preventDefault();
});
}
return txtChangeFn;
};
$.fn.jmePlayer = function(opts){
return this.each(function(){
if(opts){
$.jme.data(this, $.extend(true, {}, opts));
}
var mediaUpdateFn, canPlay, removeCanPlay, canplayTimer, lastState, stopEmptiedEvent;
var media = $('audio, video', this).eq(0);
var base = $(this);
var jmeData = $.jme.data(this);
var mediaData = $.jme.data(media[0]);
base.addClass(media.prop('nodeName').toLowerCase()+'player');
mediaData.player = base;
mediaData.media = media;
if(!jmeData.media){
removeCanPlay = function(){
media.off('canplay', canPlay);
clearTimeout(canplayTimer);
};
canPlay = function(){
var state = (media.prop('paused')) ? 'idle' : 'playing';
base.attr('data-state', state);
};
mediaUpdateFn = function(e){
var state = e.type;
var readyState;
var paused;
removeCanPlay();
if(unwaitingEvents[state] && lastState != 'waiting'){
return;
}
if(stopEmptiedEvent && state == 'emptied'){
return;
}
if(state == 'ended' || $.prop(this, 'ended')){
state = 'ended';
} else if(state == 'waiting'){
if($.prop(this, 'readyState') > 2){
state = '';
} else {
canplayTimer = setTimeout(function(){
if(media.prop('readyState') > 2){
canPlay();
}
}, 9);
media.on('canPlay', canPlay);
}
} else if(idlStates[state]){
state = 'idle';
} else {
readyState = $.prop(this, 'readyState');
paused = $.prop(this, 'paused');
if(!paused && readyState < 3){
state = 'waiting';
} else if(!paused && readyState > 2){
state = 'playing';
} else {
state = 'idle';
}
}
if(state == 'idle' && base._seekpause){
state = false;
}
if(state){
lastState = state;
base.attr('data-state', state);
}
};
jmeData.media = media;
jmeData.player = base;
media
.on('ended emptied play', (function(){
var timer;
var releaseEmptied = function(){
stopEmptiedEvent = false;
};
var ended = function(){
removeCanPlay();
media.jmeFn('pause');
if(!options.noReload && media.prop('ended') && media.prop('paused') && !media.prop('autoplay') && !media.prop('loop') && !media.hasClass('no-reload')){
stopEmptiedEvent = true;
media.jmeFn('load');
base.attr('data-state', 'ended');
setTimeout(releaseEmptied);
}
};
return function(e){
clearTimeout(timer);
if(e.type == 'ended' && !options.noReload && !media.prop('autoplay') && !media.prop('loop') && !media.hasClass('no-reload')){
timer = setTimeout(ended);
}
};
})())
.on('emptied waiting canplay canplaythrough playing ended pause mediaerror', mediaUpdateFn)
.on('volumechange updateJMEState', function(){
var volume = $.prop(this, 'volume');
base[!volume || $.prop(this, 'muted') ? 'addClass' : 'removeClass']('state-muted');
if(volume < 0.01){
volume = 'no';
} else if(volume < 0.36){
volume = 'low';
} else if(volume < 0.7){
volume = 'medium';
} else {
volume = 'high';
}
base.attr('data-volume', volume);
})
;
if(mediaUpdateFn){
media.on('updateJMEState', mediaUpdateFn).triggerHandler('updateJMEState');
}
}
});
};
$.jme.defineProp('isPlaying', {
get: function(elem){
return (!$.prop(elem, 'ended') && !$.prop(elem, 'paused') && $.prop(elem, 'readyState') > 1 && !$.data(elem, 'mediaerror'));
},
readonly: true
});
$.jme.defineProp('player', {
readonly: true
});
$.jme.defineProp('media', {
readonly: true
});
$.jme.defineProp('srces', {
get: function(elem){
var srces;
var data = $.jme.data(elem);
var src = data.media.prop('src');
if(src){
return [{src: src}];
}
srces = $.map($('source', data.media).get(), function(source){
var src = {
src: $.prop(source, 'src')
};
var tmp = $.attr(source, 'media');
if(tmp){
src.media = tmp;
}
tmp = $.attr(source, 'type');
if(tmp){
src.type = tmp;
}
return src;
});
return srces;
},
set: function(elem, srces){
var data = $.jme.data(elem);
var setSrc = function(i, src){
if(typeof src == 'string'){
src = {src: src};
}
$(document.createElement('source')).attr(src).appendTo(data.media);
};
data.media.removeAttr('src').find('source').remove();
if($.isArray(srces)){
$.each(srces, setSrc);
} else {
setSrc(0, srces);
}
data.media.jmeFn('load');
return 'noDataSet';
}
});
$.jme.defineMethod('togglePlay', function(){
$(this).jmeFn( ( props.isPlaying.get(this) ) ? 'pause' : 'play' );
});
$.jme.defineMethod('addControls', function(controls){
var data = $.jme.data(this) || {};
if(!data.media){return;}
var oldControls = $.jme.data(data.player[0], 'controlElements') || $([]);
controls = $(controls);
$.each($.jme.plugins, function(name, plugin){
controls
.filter('.'+plugin.className)
.add(controls.find('.'+plugin.className))
.each(function(){
var control = $(this);
var options = $.jme.data(this);
options.player = data.player;
options.media = data.media;
if(options._rendered){return;}
options._rendered = true;
if(plugin.options){
$.each(plugin.options, function(option, value){
if(!(option in options)){
options[option] = value;
}
});
}
plugin._create(control, data.media, data.player, options);
control = null;
})
;
});
$.jme.data(data.player[0], 'controlElements', oldControls.add(controls));
data.player.triggerHandler('controlsadded');
});
webshims.addReady($.jme.initJME);
webshims._polyfill(['mediaelement']);
});
;webshims.register('mediacontrols', function($, webshims, window){
"use strict";
var pseudoClasses = 'pseudoClasses';
var options = webshims.cfg.mediaelement.jme;
var baseSelector = options.selector;
var btnStructure = '<button class="{%class%}" type="button" aria-label="{%text%}"></button>';
var slideStructure = '<div class="{%class%} media-range"></div>';
var timeStructure = '<div class="{%class%}">00:00</div>';
var noVolumeClass = (function(){
var audio;
var ret = '';
if(typeof window.Audio == 'function'){
audio = new Audio();
audio.volume = 0.55;
ret = audio.volume = 0.55 ? '' : ' no-volume-api';
}
return ret;
})();
var getBarHtml = (function(){
var cache = {};
var regTemplate = /\{\{(.+?)\}\}/igm;
return function(template, invalidCache){
if(!template){
template = options.barTemplate;
}
if(!cache[template] || invalidCache){
cache[template] = template.replace(regTemplate, function(match, matchName){
var plugin = $.jme.plugins[matchName];
if(plugin && plugin.structure){
return plugin.structure.replace('{%class%}', matchName).replace('{%text%}', plugin.text || '');
}
return match;
});
}
return cache[template] || '';
};
})();
var loadLazy = function(){
if(!loadLazy.loaded){
loadLazy.loaded = true;
webshims.loader.loadList(['mediacontrols-lazy', 'range-ui']);
}
};
var lazyLoadPlugin = function(fn){
if(!fn){
fn = '_create';
}
var rfn = function(c, media){
var obj = this;
var args = arguments;
loadLazy();
webshims.ready('mediacontrols-lazy', function(){
if(rfn != obj[fn] && $.data(media[0])){
return obj[fn].apply(obj, args);
} else {
webshims.error('stop too much recursion');
}
});
};
return rfn;
};
if(!options.barTemplate){
options.barTemplate = '<div class="play-pause-container">{{play-pause}}</div><div class="playlist-container"><div class="playlist-box">{{playlist-prev}}{{playlist-next}}</div></div><div class="currenttime-container">{{currenttime-display}}</div><div class="progress-container">{{time-slider}}</div><div class="duration-container">{{duration-display}}</div><div class="mute-container">{{mute-unmute}}</div><div class="volume-container">{{volume-slider}}</div><div class="subtitle-container"><div class="subtitle-controls">{{captions}}</div></div><div class="fullscreen-container">{{fullscreen}}</div>';
}
if(!options.barStructure){
options.barStructure = '<div class="jme-media-overlay"></div><div class="jme-controlbar'+ noVolumeClass +'" tabindex="-1"><div class="jme-cb-box"></div></div>';
}
webshims.loader.addModule('mediacontrols-lazy', {
src: 'jme/mediacontrols-lazy'
});
var userActivity = {
_create: lazyLoadPlugin()
};
$.jme.plugins.useractivity = userActivity;
$.jme.defineProp('controlbar', {
set: function(elem, value){
value = !!value;
var controls, playerSize;
var data = $.jme.data(elem);
var controlBar = $('div.jme-mediaoverlay, div.jme-controlbar', data.player);
var structure = '';
if(value && !controlBar[0]){
if(data._controlbar){
data._controlbar.appendTo(data.player);
} else {
data.media.prop('controls', false);
structure = getBarHtml();
data._controlbar = $( options.barStructure );
controlBar = data._controlbar.find('div.jme-cb-box').addClass('media-controls');
controls = data._controlbar.filter('.jme-media-overlay').addClass('play-pause');
controls = controls.add( controlBar );
$(structure).appendTo(controlBar);
data._controlbar.appendTo(data.player);
data.player.jmeFn('addControls', controls);
playerSize = (function(){
var lastSize;
var sizes = [
{size: 290, name: 'xx-small'},
{size: 380, name: 'x-small'},
{size: 490, name: 'small'},
{size: 756, name: 'medium'},
{size: 1024, name: 'large'}
];
var len = sizes.length;
return function(){
var size = 'x-large';
var i = 0;
var width = data.player.outerWidth();
var fSize = Math.max(parseInt(data.player.css('fontSize'), 10) || 16, 13);
width = width * (16 / fSize);
for(; i < len; i++){
if(sizes[i].size >= width){
size = sizes[i].name;
break;
}
}
if(lastSize != size){
lastSize = size;
data.player.attr('data-playersize', size);
}
};
})();
userActivity._create(data.player, data.media, data.player);
playerSize();
webshims.ready('dom-support', function(){
data.player.onWSOff('updateshadowdom', playerSize);
controls.add(data._controlbar).addClass(webshims.shadowClass);
webshims.addShadowDom();
});
}
} else if(!value) {
controlBar.detach();
}
return value;
}
});
$.jme.registerPlugin('play-pause', {
structure: btnStructure,
text: 'play / pause',
_create: lazyLoadPlugin()
});
$.jme.registerPlugin('mute-unmute', {
structure: btnStructure,
text: 'mute / unmute',
_create: lazyLoadPlugin()
});
$.jme.registerPlugin('volume-slider', {
structure: slideStructure,
_create: lazyLoadPlugin()
});
$.jme.registerPlugin('time-slider', {
structure: slideStructure,
options: {
format: ['mm', 'ss']
},
_create: lazyLoadPlugin()
});
$.jme.defineProp('format', {
set: function(elem, format){
if(!$.isArray(format)){
format = format.split(':');
}
var data = $.jme.data(elem);
data.format = format;
$(elem).triggerHandler('updatetimeformat');
data.player.triggerHandler('updatetimeformat');
return 'noDataSet';
}
});
$.jme.registerPlugin('duration-display', {
structure: timeStructure,
options: {
format: "mm:ss"
},
_create: lazyLoadPlugin()
});
$.jme.defineProp('countdown', {
set: function(elem, value){
var data = $.jme.data(elem);
data.countdown = !!value;
$(elem).triggerHandler('updatetimeformat');
data.player.triggerHandler('updatetimeformat');
return 'noDataSet';
}
});
$.jme.registerPlugin('currenttime-display', {
structure: timeStructure,
options: {
format: "mm:ss",
countdown: false
},
_create: lazyLoadPlugin()
});
/**
* Added Poster Plugin
* @author mderting
*/
/*
* the old technique wasn't fully bullet proof
* beside this, jme2 adovactes to use the new improved state-classes to handle visual effect on specific state (see CSS change)
*/
$.jme.registerPlugin('poster-display', {
structure: '<div />',
options: {
},
_create: lazyLoadPlugin()
});
$.jme.registerPlugin('fullscreen', {
options: {
fullscreen: true,
autoplayfs: false
},
structure: btnStructure,
text: 'enter fullscreen / exit fullscreen',
_create: lazyLoadPlugin()
});
$.jme.registerPlugin('captions', {
structure: btnStructure,
text: 'subtitles',
_create: function(control, media, base){
var trackElems = media.find('track');
control.wsclonedcheckbox = $(control).clone().attr({role: 'checkbox'}).insertBefore(control);
base.attr('data-tracks', trackElems.length > 1 ? 'many' : trackElems.length);
control.attr('aria-haspopup', 'true');
lazyLoadPlugin().apply(this, arguments);
}
});
webshims.ready(webshims.cfg.mediaelement.plugins.concat(['mediaelement']), function(){
webshims.addReady(function(context, insertedElement){
$(baseSelector, context).add(insertedElement.filter(baseSelector)).jmeProp('controlbar', true);
});
});
webshims.ready('WINDOWLOAD', loadLazy);
});
;webshims.ready('jme DOM', function(){
"use strict";
var webshims = window.webshims;
var $ = webshims.$;
var jme = $.jme;
var listId = 0;
var btnStructure = '<button class="{%class%}" type="button" aria-label="{%text%}"></button>';
function PlaylistList(data){
this._data = data;
this.lists = {};
this.on('showcontrolschange', this._updateControlsClass);
}
$.extend(PlaylistList.prototype, {
on: function(){
$.fn.on.apply($(this), arguments);
},
off: function(){
$.fn.off.apply($(this), arguments);
},
_getListId: function(list){
var id;
if(typeof list == 'string'){
id = list;
} else {
id = list.id;
}
return id;
},
_updateControlsClass: function(){
this._data.player[this.getShowcontrolsList() ? 'addClass' : 'removeClass']('has-playlist');
},
add: function(list, opts){
list = new Playlist(list, this, opts);
if(!list.id){
listId++;
list.id = 'list-'+listId;
}
this.lists[list.id] = list;
if(list.options.showcontrols){
this._data.player.addClass('has-playlist');
}
return list;
},
remove: function(list){
var id = this._getListId(list);
if(this.lists[id]){
this.lists[id]._remove();
delete this.lists[id];
}
if(!this.getShowcontrolsList()){
this._data.player.removeClass('has-playlist');
}
},
getAutoplayList: function(){
var clist = null;
$.each(this.lists, function(id, list){
if(list.options.autoplay){
clist = list;
return false;
}
});
return clist;
},
getShowcontrolsList: function(){
var clist = null;
$.each(this.lists, function(id, list){
if(list.options.showcontrols){
clist = list;
return false;
}
});
return clist;
}
});
function Playlist(list, parent, opts){
this.list = list || [];
this.playlists = parent;
this.media = parent._data.media;
this.player = parent._data.player;
this.options = $.extend(true, {}, Playlist.defaults, opts);
this.options.itemTmpl = this.options.itemTmpl.trim();
this.deferred = $.Deferred();
this._selectedIndex = -1;
this._selectedItem = null;
this.$rendered = null;
this._detectListType();
this.autoplay(this.options.autoplay);
this.deferred.done(function(){
this._addEvents(this);
if(this.options.defaultSelected == 'auto' && !this.media.jmeProp('srces').length){
this.options.defaultSelected = 0;
}
if(this.list[this.options.defaultSelected]){
this.selectedIndex(this.options.defaultSelected);
}
this._fire('addlist');
});
}
Playlist.getText = function($elem){
return $elem.attr('content') || ($elem.text() || '').trim();
};
Playlist.getUrl = function($elem){
return $elem.attr('content') || $elem.attr('url') || $elem.attr('href') || $elem.attr('src') || ($elem.text() || '').trim();
};
Playlist.defaults = {
loop: false,
autoplay: false,
defaultSelected: 'auto',
addItemEvents: true,
showcontrols: true,
ajax: {},
itemTmpl: '<li class="list-item">' +
'<% if(typeof poster == "string" && poster) {%><img src="<%=poster%>" /><% }%>' +
'<h3><%=title%></h3>' +
'<% if(typeof description == "string" && description) {%><div class="item-description"><%=description%></div><% }%>' +
'</li>',
renderer: function(item, template){
return $.jme.tmpl(template, item);
},
mapDom: function(element){
return {
title: Playlist.getText($('[itemprop="name"], h1, h2, h3, h4, h5, h6, a', element)),
srces: $('[itemprop="contentUrl"], a[type^="video"], a[type^="audio"]', element).map(function(){
var tmp;
var src = {src: Playlist.getUrl($(this))};
if(this.nodeName.toLowerCase() == 'a'){
tmp = $.prop(this, 'type');
} else {
tmp = Playlist.getText($('[itemprop="encodingFormat"]', element));
}
if(tmp){
src.type = tmp;
}
tmp = $.attr(this, 'data-media');
if(tmp){
src.media = tmp;
}
return src;
}).get(),
tracks: $('a[type="text/vtt"]').map(mapTrackUrl).get(),
poster: Playlist.getUrl($('[itemprop="thumbnailUrl"], a[type^="image"], img', element)) || null,
description: Playlist.getText($('[itemprop="description"], .item-description, p', element)) || null
};
},
mapUrl: function(opts, callback){
$.ajax($.extend(opts, {
success: function(data){
var list;
if($.isArray(data)){
list = data;
} else if(data.responseData && data.responseData.feed){
data = data.responseData.feed;
list = (data.entries || []).map(mapJsonFeed);
} else {
list = [];
$('item', data).each(function(){
var srces = $('enclosure, media\\:content', this)
.filter('[type^="video"], [type^="audio"]')
.map(mapUrl)
.get()
;
if(srces.length){
list.push({
title: $('title', this).html(),
srces: srces,
publishedDate: $('pubDate', this).html() || null,
description: $('description', this).text() || null,
poster: Playlist.getUrl($('itunes\\:image, media\\:thumbnail, enclosure[type^="image"], media\\:content[type^="image"]', this)) || null,
author: $('itunes\\:author', this).html() || null,
duration: $('itunes\\:duration', this).html() || null,
tracks: $('media\\:subTitle', this).map(mapTrackUrl).get() || null
});
}
});
}
if(list != data){
list.fullData = data;
}
callback(list);
}
}));
}
};
function mapJsonFeed(item){
item.description = item.description || item.content;
item.srces = [];
(item.mediaGroups || []).forEach(function(mediagroup){
(mediagroup.contents || []).forEach(function(itemSrc){
itemSrc.src = itemSrc.src || itemSrc.url;
item.srces.push(itemSrc);
});
});
return item;
}
function mapTrackUrl(){
return {
src: $.attr(this, 'href'),
srclang: $.attr(this, 'lang'),
label: $.attr(this, 'data-label')
};
}
function mapUrl(){
return {
src: $.attr(this, 'url') || $.attr(this, 'href'),
type: $.attr(this, 'type')
};
}
function filterNode(){
return this.nodeType == 1;
}
$.extend(Playlist.prototype, {
on: function(){
$.fn.on.apply($(this), arguments);
},
off: function(){
$.fn.off.apply($(this), arguments);
},
_detectListType: function(){
var fullData;
if(typeof this.list == 'string'){
this._createListFromUrl();
return;
}
if(this.list.nodeName || (this.list.length > 0 && this.list[0].nodeName)){
this._createListFromDom();
} else if(this.list.responseData && this.list.responseData.feed){
fullData = this.list.responseData.feed;
this.list = (fullData.entries || []).map(mapJsonFeed);
this.list.fullData = fullData;
}
this.deferred.resolveWith(this);
},
_createListFromUrl: function(){
var that = this;
this.options.ajax.url = this.list;
this.options.mapUrl(this.options.ajax, function(list){
that.list = list;
that.deferred.resolveWith(that);
});
},
_createListFromDom: function(){
var that = this;
this.$rendered = $(this.list).eq(0);
this.list = [];
if(this.$rendered){
this._addDomList();
this.list = this.$rendered.children().map(function(){
return that._createItemFromDom(this);
}).get();
}
},
_createItemFromDom: function(dom){
var item = this.options.mapDom(dom);
this._addItemData(item, dom);
return item;
},
_fire: function(evt, extra){
var evt = $.Event(evt);
$(this).triggerHandler(evt, extra);
$(this.playlists).triggerHandler(evt, $.merge([{list: this}], extra || []));
if(this.$rendered){
this.$rendered.triggerHandler(evt, extra);
}
},
_addDomList: function(){
this.$rendered
.attr({
'data-autoplay': this.options.autoplay,
'data-loop': this.options.loop
})
.addClass('media-playlist')
.data('playlist', this)
;
},
_addItemData: function(item, dom){
var that = this;
item.$item = $(dom).data('itemData', item);
if(item == this._selectedItem){
item.$item.addClass('selected-item');
}
if(this.options.addItemEvents){
item.$item.on('click.playlist', function(e){
if(that.options.addItemEvents){
that.playItem(item, e);
return false;
}
});
}
},
_addEvents: function(that){
var o = that.options;
var onEnded = function(e){
if(o.autoplay){
that.playNext(e);
}
};
this.media.on('ended', onEnded);
this._remove = function(){
that.media.off('ended', onEnded);
that.autoplay(false);
if(that.$rendered){
that.$rendered.remove();
}
that._fire('removelist');
};
},
_remove: function(){
this._fire('removelist');
},
render: function(callback){
if(this.$rendered){
callback(this.$rendered, this.player, this);
} else {
this.deferred.done(function(){
var nodeName;
var that = this;
var items = [];
if(!this.$rendered){
$.each(this.list, function(i, item){
var domItem = $($.parseHTML(that.options.renderer(item, that.options.itemTmpl))).filter(filterNode)[0];
that._addItemData(item, domItem);
items.push(domItem);
});
nodeName = (items[0] && items[0].nodeName || '').toLowerCase();
switch (nodeName){
case 'li':
this.$rendered = $.parseHTML('<ul />');
break;
case 'option':
this.$rendered = $.parseHTML('<select />');
break;
default:
this.$rendered = $.parseHTML('<div />');
break;
}
this.$rendered = $(this.$rendered).html(items);
this._addDomList();
}
callback(this.$rendered, this.player, this);
});
}
},
/*
addItem: function(item, pos){
},
removeItem: function(item){
},
*/
_loadItem: function(item){
var media = this.media;
media.attr('poster', item.poster || '');
$('track', media).remove();
$.each(item.tracks || [], function(i, track){
$('<track />').attr(track).appendTo(media);
});
media.jmeProp('srces', item.srces);
},
_getItem: function(item){
if(item && (item.nodeName || item.jquery || typeof item == 'string')){
item = $(item).data('itemData');
}
return item;
},
playItem: function(item, e){
var media;
this.selectedItem(item, e);
if(item){
media = this.media.play();
setTimeout(function(){
media.play();
}, 9);
}
},
selectedIndex: function(index, e){
if(arguments.length){
this.selectedItem(this.list[index], e);
} else {
return this._selectedIndex;
}
},
selectedItem: function(item, e){
var oldItem, found;
if(arguments.length){
found = -1;
item = this._getItem(item);
if(item){
$.each(this.list, function(i){
if(item == this){
found = i;
return false;
}
});
}
if(found >= 0){
this._loadItem(this.list[found]);
}
if(found != this._selectedIndex){
oldItem = this._selectedItem || null;
if(oldItem && oldItem.$item){
oldItem.$item.removeClass('selected-item');
}
this._selectedItem = this.list[found] || null;
this._selectedIndex = found;
if(this._selectedItem && this._selectedItem.$item){
this._selectedItem.$item.addClass('selected-item');
}
if(oldItem !== this._selectedItem){
this._fire('itemchange', [{oldItem: oldItem, from: e || null}]);
}
}
} else {
return this._selectedItem;
}
},
playNext: function(){
var item = this.getNext();
if(item){
this.playItem(item);
}
},
playPrev: function(){
var item = this.getPrev();
if(item){
this.playItem(item);
}
},
getNext: function(){
var index = this._selectedIndex + 1;
return this.list[index] || (this.options.loop ? this.list[0] : null);
},
getPrev: function(){
var index = this._selectedIndex - 1;
return this.list[index] || (this.options.loop ? this.list[this.list.length - 1] : null);
}
});
[{name: 'autoplay', fn: 'getAutoplayList'}, {name: 'showcontrols', fn: 'getShowcontrolsList'}, {name: 'loop'}].forEach(function(desc){
Playlist.prototype[desc.name] = function(value){
var curList;
if(arguments.length){
value = !!value;
if(value && desc.fn){
curList = this.playlists[desc.fn]();
if(curList && curList != this){
curList[desc.name](false);
}
}
if(this.options[desc.name] != value){
this.options[desc.name] = value;
if(this.$rendered){
this.$rendered.attr('data-'+desc.name, value);
}
this._fire(desc.name+'change');
}
} else {
return this.options[desc.name];
}
}
});
jme.defineProp('playlists', {
writable: false,
get: function(elem){
var data = $.jme.data(elem);
if(elem != data.player[0]){return null;}
if(!data.playlists){
data.playlists = new PlaylistList(data);
}
return data.playlists;
}
});
jme.defineMethod('addPlaylist', function(list, options){
var playlists = $.jme.prop(this, 'playlists');
if(playlists && playlists.add){
return playlists.add(list, options);
}
return null;
});
[
{name: 'playlist-prev', text: 'previous', get: 'getPrev', play: 'playPrev'},
{name: 'playlist-next', text: 'next', get: 'getNext', play: 'playNext'}
]
.forEach(function(desc){
$.jme.registerPlugin(desc.name, {
structure: btnStructure,
text: desc.text,
_create: function(control, media, base){
var cList;
var playlists = base.jmeProp('playlists');
function itemChange(){
var item = cList[desc.get]();
if(item){
control.prop({'disabled': false, title: item.title});
} else {
control.prop({'disabled': true, title: ''});
}
}
function listchange(){
var newClist = playlists.getShowcontrolsList();
if(newClist != cList){
if(cList){
cList.off('itemchange', itemChange);
}
cList = newClist;
if(cList){
cList.on('itemchange', itemChange);
itemChange();
}
}
}
control.on('click', function(){
if(cList){
cList[desc.play]();
}
});
playlists.on({
'addlist removelist showcontrolschange':listchange
});
listchange();
}
});
})
;
// Simple JavaScript Templating
(function() {
var cache = {};
$.jme.tmpl = function tmpl(str, data) {
// Figure out if we're getting a template, or if we need to
// load the template - and be sure to cache the result.
if(!cache[str]){
cache[str] = new Function("obj",
"var p=[],print=function(){p.push.apply(p,arguments);};" +
// Introduce the data as local variables using with(){}
"with(obj){p.push('" +
// Convert the template into pure JavaScript
str.replace(/[\r\t\n]/g, " ")
.replace(/'(?=[^%]*%>)/g,"\t")
.split("'").join("\\'")
.split("\t").join("'")
.replace(/<%=(.+?)%>/g, "',$1,'")
.split("<%").join("');")
.split("%>").join("p.push('")
+ "');}return p.join('');");
}
// Provide some basic currying to the user
return data ? cache[str](data) : cache[str];
};
})();
$.jme.Playlist = Playlist;
webshims.isReady('playlist', true);
});
| nareshs435/cdnjs | ajax/libs/webshim/1.13.2-RC2/dev/shims/combos/98.js | JavaScript | mit | 32,028 |
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang("a11yhelp","de",{title:"Barrierefreiheitinformationen",contents:"Hilfeinhalt. Um den Dialog zu schliessen die Taste 'ESC' drücken.",legend:[{name:"Allgemein",items:[{name:"Editor Symbolleiste",legend:"Drücken Sie ${toolbarFocus} auf der Symbolleiste. Gehen Sie zur nächsten oder vorherigen Symbolleistengruppe mit TAB und SHIFT-TAB. Gehen Sie zur nächsten oder vorherigen Symbolleiste auf die Schaltfläche mit dem RECHTS- oder LINKS-Pfeil. Drücken Sie die Leertaste oder Eingabetaste, um die Schaltfläche in der Symbolleiste aktivieren."},
{name:"Editor Dialog",legend:"Innerhalb des Dialogs drücken Sie TAB um zum nächsten Dialogfeld zu gelangen, drücken Sie SHIFT-TAG um zum vorherigen Feld zu wechseln, drücken Sie ENTER um den Dialog abzusenden und ESC um den Dialog zu abzubrechen. Um zwischen den Reitern innerhalb eines Dialogs zu wechseln drücken sie ALT-F10. Um zum nächsten Reiter zu gelangen können Sie TAB oder die rechte Pfeiltaste. Zurück gelangt man mit SHIFT-TAB oder der linken Pfeiltaste. Mit der Leertaste oder Enter kann man den Reiter auswählen."},
{name:"Editor Kontextmenü",legend:"Dürcken Sie ${contextMenu} oder die Anwendungstaste um das Kontextmenü zu öffnen. Man kann die Pfeiltasten zum Wechsel benutzen. Mit der Leertaste oder der Enter-Taste kann man den Menüpunkt aufrufen. Schliessen Sie das Kontextmenü mit der ESC-Taste."},{name:"Editor Listen",legend:"Innerhalb einer Listenbox kann man mit der TAB-Taste oder den Pfeilrunter-Taste den nächsten Menüeintrag wählen. Mit der Shift-TAB Tastenkombination oder der Pfeilhoch-Taste gelangt man zum vorherigen Menüpunkt. Mit der Leertaste oder Enter kann man den Menüpunkt auswählen. Drücken Sie ESC zum Verlassen des Menüs."},
{name:"Editor Elementpfadleiste",legend:"Drücken Sie ${elementsPathFocus} um sich durch die Pfadleiste zu bewegen. Um zum nächsten Element zu gelangen drücken Sie TAB oder die Pfeilrechts-Taste. Zum vorherigen Element gelangen Sie mit der SHIFT-TAB oder der Pfeillinks-Taste. Drücken Sie die Leertaste oder Enter um das Element auszuwählen."}]},{name:"Befehle",items:[{name:"Wiederholen Befehl",legend:"Drücken Sie ${undo}"},{name:"Rückgängig Befehl",legend:"Drücken Sie ${redo}"},{name:"Fettschrift Befehl",
legend:"Drücken Sie ${bold}"},{name:"Italic Befehl",legend:"Drücken Sie ${italic}"},{name:"Unterstreichung Befehl",legend:"Drücken Sie ${underline}"},{name:"Link Befehl",legend:"Drücken Sie ${link}"},{name:"Symbolleiste zuammenklappen Befehl",legend:"Drücken Sie ${toolbarCollapse}"},{name:"Zugang bisheriger Fokussierung Raumbefehl ",legend:"Drücken Sie ${accessPreviousSpace} auf den am nächsten nicht erreichbar Fokus-Abstand vor die Einfügemarke zugreifen: zwei benachbarte HR-Elemente. Wiederholen Sie die Tastenkombination um entfernte Fokusräume zu erreichen. "},
{name:"Zugang nächster Schwerpunkt Raumbefehl ",legend:"Drücken Sie $ { accessNextSpace }, um den nächsten unerreichbar Fokus Leerzeichen nach dem Cursor zum Beispiel auf: zwei benachbarten HR Elemente. Wiederholen Sie die Tastenkombination zum fernen Fokus Bereiche zu erreichen. "},{name:"Eingabehilfen",legend:"Drücken Sie ${a11yHelp}"}]}]}); | PeterDaveHello/jsdelivr | files/ckeditor/4.2/plugins/a11yhelp/dialogs/lang/de.js | JavaScript | mit | 3,358 |
YUI.add('event-key', function (Y, NAME) {
/**
* Functionality to listen for one or more specific key combinations.
* @module event
* @submodule event-key
*/
var ALT = "+alt",
CTRL = "+ctrl",
META = "+meta",
SHIFT = "+shift",
trim = Y.Lang.trim,
eventDef = {
KEY_MAP: {
enter : 13,
esc : 27,
backspace: 8,
tab : 9,
pageup : 33,
pagedown : 34
},
_typeRE: /^(up|down|press):/,
_keysRE: /^(?:up|down|press):|\+(alt|ctrl|meta|shift)/g,
processArgs: function (args) {
var spec = args.splice(3,1)[0],
mods = Y.Array.hash(spec.match(/\+(?:alt|ctrl|meta|shift)\b/g) || []),
config = {
type: this._typeRE.test(spec) ? RegExp.$1 : null,
mods: mods,
keys: null
},
// strip type and modifiers from spec, leaving only keyCodes
bits = spec.replace(this._keysRE, ''),
chr, uc, lc, i;
if (bits) {
bits = bits.split(',');
config.keys = {};
// FIXME: need to support '65,esc' => keypress, keydown
for (i = bits.length - 1; i >= 0; --i) {
chr = trim(bits[i]);
// catch sloppy filters, trailing commas, etc 'a,,'
if (!chr) {
continue;
}
// non-numerics are single characters or key names
if (+chr == chr) {
config.keys[chr] = mods;
} else {
lc = chr.toLowerCase();
if (this.KEY_MAP[lc]) {
config.keys[this.KEY_MAP[lc]] = mods;
// FIXME: '65,enter' defaults keydown for both
if (!config.type) {
config.type = "down"; // safest
}
} else {
// FIXME: Character mapping only works for keypress
// events. Otherwise, it uses String.fromCharCode()
// from the keyCode, which is wrong.
chr = chr.charAt(0);
uc = chr.toUpperCase();
if (mods["+shift"]) {
chr = uc;
}
// FIXME: stupid assumption that
// the keycode of the lower case == the
// charCode of the upper case
// a (key:65,char:97), A (key:65,char:65)
config.keys[chr.charCodeAt(0)] =
(chr === uc) ?
// upper case chars get +shift free
Y.merge(mods, { "+shift": true }) :
mods;
}
}
}
}
if (!config.type) {
config.type = "press";
}
return config;
},
on: function (node, sub, notifier, filter) {
var spec = sub._extra,
type = "key" + spec.type,
keys = spec.keys,
method = (filter) ? "delegate" : "on";
// Note: without specifying any keyCodes, this becomes a
// horribly inefficient alias for 'keydown' (et al), but I
// can't abort this subscription for a simple
// Y.on('keypress', ...);
// Please use keyCodes or just subscribe directly to keydown,
// keyup, or keypress
sub._detach = node[method](type, function (e) {
var key = keys ? keys[e.which] : spec.mods;
if (key &&
(!key[ALT] || (key[ALT] && e.altKey)) &&
(!key[CTRL] || (key[CTRL] && e.ctrlKey)) &&
(!key[META] || (key[META] && e.metaKey)) &&
(!key[SHIFT] || (key[SHIFT] && e.shiftKey)))
{
notifier.fire(e);
}
}, filter);
},
detach: function (node, sub, notifier) {
sub._detach.detach();
}
};
eventDef.delegate = eventDef.on;
eventDef.detachDelegate = eventDef.detach;
/**
* <p>Add a key listener. The listener will only be notified if the
* keystroke detected meets the supplied specification. The
* specification is a string that is defined as:</p>
*
* <dl>
* <dt>spec</dt>
* <dd><code>[{type}:]{code}[,{code}]*</code></dd>
* <dt>type</dt>
* <dd><code>"down", "up", or "press"</code></dd>
* <dt>code</dt>
* <dd><code>{keyCode|character|keyName}[+{modifier}]*</code></dd>
* <dt>modifier</dt>
* <dd><code>"shift", "ctrl", "alt", or "meta"</code></dd>
* <dt>keyName</dt>
* <dd><code>"enter", "backspace", "esc", "tab", "pageup", or "pagedown"</code></dd>
* </dl>
*
* <p>Examples:</p>
* <ul>
* <li><code>Y.on("key", callback, "press:12,65+shift+ctrl", "#my-input");</code></li>
* <li><code>Y.delegate("key", preventSubmit, "#forms", "enter", "input[type=text]");</code></li>
* <li><code>Y.one("doc").on("key", viNav, "j,k,l,;");</code></li>
* </ul>
*
* @event key
* @for YUI
* @param type {string} 'key'
* @param fn {function} the function to execute
* @param id {string|HTMLElement|collection} the element(s) to bind
* @param spec {string} the keyCode and modifier specification
* @param o optional context object
* @param args 0..n additional arguments to provide to the listener.
* @return {Event.Handle} the detach handle
*/
Y.Event.define('key', eventDef, true);
}, '@VERSION@', {"requires": ["event-synthetic"]});
| ZDroid/cdnjs | ajax/libs/yui/3.12.0/event-key/event-key.js | JavaScript | mit | 6,036 |
%% Sequential Bayesian Updating of a Beta-Bernoulli model.
% In this example we draw samples from a Bernoulli distribution and then
% sequentially fit a Beta-Bernoulli model, plotting the posterior of the
% parameters at each iteration.
%% Sample
% This file is from pmtk3.googlecode.com
setSeed(0);
mu = 0.7; % 70% probability of success
n = 100; % number of samples
X = rand(n, 1) < mu;
%% Update & Plot
figure; hold on; box on;
[styles, colors, symbols] = plotColors();
ns = [5 50 100];
betaPrior = [0.5, 0.5]; % uninformative prior
xs = linspace(0.001, 0.999, 40);
model = struct();
for i=1:numel(ns)
n = ns(i);
Xsubset = X(1:n);
nsucc = sum( Xsubset);
nfail = sum(~Xsubset);
model.a = betaPrior(1) + nsucc;
model.b = betaPrior(2) + nfail;
p = exp(betaLogprob(model, xs));
name = sprintf('n=%d', n);
plot(xs, p, [styles{i}, colors(i)], 'LineWidth', 3, 'DisplayName', name);
end
axis([0, 1, -0.2, 10.5])
h = verticalLine(mean(X), 'LineStyle' , '--' , ...
'LineWidth' , 2.5 , ...
'Color' , 'c' , ...
'DisplayName', 'truth' );
if ~isOctave
uistack(h, 'bottom');
end
legend('Location', 'NorthWest');
printPmtkFigure betaSeqUpdate
| h1arshad/pmtk3 | demos/bernoulliBetaSequentialUpdate.m | Matlab | mit | 1,290 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.