text stringlengths 2 1.04M | meta dict |
|---|---|
#include "config.h"
#include "core/fileapi/File.h"
#include "bindings/core/v8/ExceptionState.h"
#include "core/dom/ExceptionCode.h"
#include "core/fileapi/FilePropertyBag.h"
#include "platform/FileMetadata.h"
#include "platform/MIMETypeRegistry.h"
#include "platform/blob/BlobData.h"
#include "public/platform/Platform.h"
#include "public/platform/WebFileUtilities.h"
#include "wtf/CurrentTime.h"
#include "wtf/DateMath.h"
namespace blink {
static String getContentTypeFromFileName(const String& name, File::ContentTypeLookupPolicy policy)
{
String type;
int index = name.reverseFind('.');
if (index != -1) {
if (policy == File::WellKnownContentTypes) {
type = MIMETypeRegistry::getWellKnownMIMETypeForExtension(name.substring(index + 1));
} else {
ASSERT(policy == File::AllContentTypes);
type = MIMETypeRegistry::getMIMETypeForExtension(name.substring(index + 1));
}
}
return type;
}
static PassOwnPtr<BlobData> createBlobDataForFileWithType(const String& path, const String& contentType)
{
OwnPtr<BlobData> blobData = BlobData::create();
blobData->setContentType(contentType);
blobData->appendFile(path);
return blobData.release();
}
static PassOwnPtr<BlobData> createBlobDataForFile(const String& path, File::ContentTypeLookupPolicy policy)
{
return createBlobDataForFileWithType(path, getContentTypeFromFileName(path, policy));
}
static PassOwnPtr<BlobData> createBlobDataForFileWithName(const String& path, const String& fileSystemName, File::ContentTypeLookupPolicy policy)
{
return createBlobDataForFileWithType(path, getContentTypeFromFileName(fileSystemName, policy));
}
static PassOwnPtr<BlobData> createBlobDataForFileWithMetadata(const String& fileSystemName, const FileMetadata& metadata)
{
OwnPtr<BlobData> blobData = BlobData::create();
blobData->setContentType(getContentTypeFromFileName(fileSystemName, File::WellKnownContentTypes));
blobData->appendFile(metadata.platformPath, 0, metadata.length, metadata.modificationTime / msPerSecond);
return blobData.release();
}
static PassOwnPtr<BlobData> createBlobDataForFileSystemURL(const KURL& fileSystemURL, const FileMetadata& metadata)
{
OwnPtr<BlobData> blobData = BlobData::create();
blobData->setContentType(getContentTypeFromFileName(fileSystemURL.path(), File::WellKnownContentTypes));
blobData->appendFileSystemURL(fileSystemURL, 0, metadata.length, metadata.modificationTime / msPerSecond);
return blobData.release();
}
// static
File* File::create(const HeapVector<BlobOrStringOrArrayBufferViewOrArrayBuffer>& fileBits, const String& fileName, const FilePropertyBag& options, ExceptionState& exceptionState)
{
ASSERT(options.hasType());
if (!options.type().containsOnlyASCII()) {
exceptionState.throwDOMException(SyntaxError, "The 'type' property must consist of ASCII characters.");
return nullptr;
}
double lastModified;
if (options.hasLastModified())
lastModified = static_cast<double>(options.lastModified());
else
lastModified = currentTimeMS();
ASSERT(options.hasEndings());
bool normalizeLineEndingsToNative = options.endings() == "native";
OwnPtr<BlobData> blobData = BlobData::create();
blobData->setContentType(options.type().lower());
populateBlobData(blobData.get(), fileBits, normalizeLineEndingsToNative);
long long fileSize = blobData->length();
return File::create(fileName, lastModified, BlobDataHandle::create(blobData.release(), fileSize));
}
File* File::create(const unsigned char* data, size_t bytes, const String& mimeType)
{
ASSERT(data);
OwnPtr<BlobData> blobData = BlobData::create();
blobData->setContentType(mimeType);
blobData->appendBytes(data, bytes);
long long blobSize = blobData->length();
// create blob as the type of file with two additional attributes -- name and lastModificationTime
return File::create("", currentTimeMS(), BlobDataHandle::create(blobData.release(), blobSize));
}
File* File::createWithRelativePath(const String& path, const String& relativePath)
{
File* file = new File(path, File::AllContentTypes, File::IsUserVisible);
file->m_relativePath = relativePath;
return file;
}
File::File(const String& path, ContentTypeLookupPolicy policy, UserVisibility userVisibility)
: Blob(BlobDataHandle::create(createBlobDataForFile(path, policy), -1))
, m_hasBackingFile(true)
, m_userVisibility(userVisibility)
, m_path(path)
, m_name(Platform::current()->fileUtilities()->baseName(path))
, m_snapshotSize(-1)
, m_snapshotModificationTimeMS(invalidFileTime())
{
}
File::File(const String& path, const String& name, ContentTypeLookupPolicy policy, UserVisibility userVisibility)
: Blob(BlobDataHandle::create(createBlobDataForFileWithName(path, name, policy), -1))
, m_hasBackingFile(true)
, m_userVisibility(userVisibility)
, m_path(path)
, m_name(name)
, m_snapshotSize(-1)
, m_snapshotModificationTimeMS(invalidFileTime())
{
}
File::File(const String& path, const String& name, const String& relativePath, UserVisibility userVisibility, bool hasSnaphotData, uint64_t size, double lastModified, PassRefPtr<BlobDataHandle> blobDataHandle)
: Blob(blobDataHandle)
, m_hasBackingFile(!path.isEmpty() || !relativePath.isEmpty())
, m_userVisibility(userVisibility)
, m_path(path)
, m_name(name)
, m_snapshotSize(hasSnaphotData ? static_cast<long long>(size) : -1)
, m_snapshotModificationTimeMS(hasSnaphotData ? lastModified : invalidFileTime())
, m_relativePath(relativePath)
{
}
File::File(const String& name, double modificationTimeMS, PassRefPtr<BlobDataHandle> blobDataHandle)
: Blob(blobDataHandle)
, m_hasBackingFile(false)
, m_userVisibility(File::IsNotUserVisible)
, m_name(name)
, m_snapshotSize(Blob::size())
, m_snapshotModificationTimeMS(modificationTimeMS)
{
}
File::File(const String& name, const FileMetadata& metadata, UserVisibility userVisibility)
: Blob(BlobDataHandle::create(createBlobDataForFileWithMetadata(name, metadata), metadata.length))
, m_hasBackingFile(true)
, m_userVisibility(userVisibility)
, m_path(metadata.platformPath)
, m_name(name)
, m_snapshotSize(metadata.length)
, m_snapshotModificationTimeMS(metadata.modificationTime)
{
}
File::File(const KURL& fileSystemURL, const FileMetadata& metadata, UserVisibility userVisibility)
: Blob(BlobDataHandle::create(createBlobDataForFileSystemURL(fileSystemURL, metadata), metadata.length))
, m_hasBackingFile(false)
, m_userVisibility(userVisibility)
, m_name(decodeURLEscapeSequences(fileSystemURL.lastPathComponent()))
, m_fileSystemURL(fileSystemURL)
, m_snapshotSize(metadata.length)
, m_snapshotModificationTimeMS(metadata.modificationTime)
{
}
File::File(const File& other)
: Blob(other.blobDataHandle())
, m_hasBackingFile(other.m_hasBackingFile)
, m_userVisibility(other.m_userVisibility)
, m_path(other.m_path)
, m_name(other.m_name)
, m_fileSystemURL(other.m_fileSystemURL)
, m_snapshotSize(other.m_snapshotSize)
, m_snapshotModificationTimeMS(other.m_snapshotModificationTimeMS)
, m_relativePath(other.m_relativePath)
{
}
File* File::clone(const String& name) const
{
File* file = new File(*this);
if (!name.isNull())
file->m_name = name;
return file;
}
double File::lastModifiedMS() const
{
if (hasValidSnapshotMetadata() && isValidFileTime(m_snapshotModificationTimeMS))
return m_snapshotModificationTimeMS;
double modificationTimeMS;
if (hasBackingFile() && getFileModificationTime(m_path, modificationTimeMS) && isValidFileTime(modificationTimeMS))
return modificationTimeMS;
return currentTimeMS();
}
long long File::lastModified() const
{
double modifiedDate = lastModifiedMS();
// The getter should return the current time when the last modification time isn't known.
if (!isValidFileTime(modifiedDate))
modifiedDate = currentTimeMS();
// lastModified returns a number, not a Date instance,
// http://dev.w3.org/2006/webapi/FileAPI/#file-attrs
return floor(modifiedDate);
}
double File::lastModifiedDate() const
{
double modifiedDate = lastModifiedMS();
// The getter should return the current time when the last modification time isn't known.
if (!isValidFileTime(modifiedDate))
modifiedDate = currentTimeMS();
// lastModifiedDate returns a Date instance,
// http://www.w3.org/TR/FileAPI/#dfn-lastModifiedDate
return modifiedDate;
}
unsigned long long File::size() const
{
if (hasValidSnapshotMetadata())
return m_snapshotSize;
// FIXME: JavaScript cannot represent sizes as large as unsigned long long, we need to
// come up with an exception to throw if file size is not representable.
long long size;
if (!hasBackingFile() || !getFileSize(m_path, size))
return 0;
return static_cast<unsigned long long>(size);
}
Blob* File::slice(long long start, long long end, const String& contentType, ExceptionState& exceptionState) const
{
if (hasBeenClosed()) {
exceptionState.throwDOMException(InvalidStateError, "File has been closed.");
return nullptr;
}
if (!m_hasBackingFile)
return Blob::slice(start, end, contentType, exceptionState);
// FIXME: This involves synchronous file operation. We need to figure out how to make it asynchronous.
long long size;
double modificationTimeMS;
captureSnapshot(size, modificationTimeMS);
clampSliceOffsets(size, start, end);
long long length = end - start;
OwnPtr<BlobData> blobData = BlobData::create();
blobData->setContentType(contentType);
if (!m_fileSystemURL.isEmpty()) {
blobData->appendFileSystemURL(m_fileSystemURL, start, length, modificationTimeMS / msPerSecond);
} else {
ASSERT(!m_path.isEmpty());
blobData->appendFile(m_path, start, length, modificationTimeMS / msPerSecond);
}
return Blob::create(BlobDataHandle::create(blobData.release(), length));
}
void File::captureSnapshot(long long& snapshotSize, double& snapshotModificationTimeMS) const
{
if (hasValidSnapshotMetadata()) {
snapshotSize = m_snapshotSize;
snapshotModificationTimeMS = m_snapshotModificationTimeMS;
return;
}
// Obtains a snapshot of the file by capturing its current size and modification time. This is used when we slice a file for the first time.
// If we fail to retrieve the size or modification time, probably due to that the file has been deleted, 0 size is returned.
FileMetadata metadata;
if (!hasBackingFile() || !getFileMetadata(m_path, metadata)) {
snapshotSize = 0;
snapshotModificationTimeMS = invalidFileTime();
return;
}
snapshotSize = metadata.length;
snapshotModificationTimeMS = metadata.modificationTime;
}
void File::close(ExecutionContext* executionContext, ExceptionState& exceptionState)
{
if (hasBeenClosed()) {
exceptionState.throwDOMException(InvalidStateError, "Blob has been closed.");
return;
}
// Reset the File to its closed representation, an empty
// Blob. The name isn't cleared, as it should still be
// available.
m_hasBackingFile = false;
m_path = String();
m_fileSystemURL = KURL();
invalidateSnapshotMetadata();
m_relativePath = String();
Blob::close(executionContext, exceptionState);
}
void File::appendTo(BlobData& blobData) const
{
if (!m_hasBackingFile) {
Blob::appendTo(blobData);
return;
}
// FIXME: This involves synchronous file operation. We need to figure out how to make it asynchronous.
long long size;
double modificationTimeMS;
captureSnapshot(size, modificationTimeMS);
if (!m_fileSystemURL.isEmpty()) {
blobData.appendFileSystemURL(m_fileSystemURL, 0, size, modificationTimeMS / msPerSecond);
return;
}
ASSERT(!m_path.isEmpty());
blobData.appendFile(m_path, 0, size, modificationTimeMS / msPerSecond);
}
bool File::hasSameSource(const File& other) const
{
if (m_hasBackingFile != other.m_hasBackingFile)
return false;
if (m_hasBackingFile)
return m_path == other.m_path;
if (m_fileSystemURL.isEmpty() != other.m_fileSystemURL.isEmpty())
return false;
if (!m_fileSystemURL.isEmpty())
return m_fileSystemURL == other.m_fileSystemURL;
return uuid() == other.uuid();
}
} // namespace blink
| {
"content_hash": "6ee1a57dffc982eda2428cbbc3218ab9",
"timestamp": "",
"source": "github",
"line_count": 354,
"max_line_length": 209,
"avg_line_length": 35.68926553672316,
"alnum_prop": 0.7221782491689093,
"repo_name": "Workday/OpenFrame",
"id": "5c8802b1d49f3b5e2053b0c127ae232e57dcd074",
"size": "13964",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "third_party/WebKit/Source/core/fileapi/File.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
using Microsoft.AspNetCore.Http;
using OrchardCore.Environment.Extensions.Features;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
namespace OrchardCore.Environment.Cache.CacheContextProviders
{
public class FeaturesCacheContextProvider : ICacheContextProvider
{
private const string FeaturesPrefix = "features:";
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IFeatureHash _featureHash;
public FeaturesCacheContextProvider(
IHttpContextAccessor httpContextAccessor,
IFeatureHash featureHash
)
{
_httpContextAccessor = httpContextAccessor;
_featureHash = featureHash;
}
public async Task PopulateContextEntriesAsync(IEnumerable<string> contexts, List<CacheContextEntry> entries)
{
if (contexts.Any(ctx => string.Equals(ctx, "features", StringComparison.OrdinalIgnoreCase)))
{
// Add a hash of the enabled features
var hash = await _featureHash.GetFeatureHashAsync();
entries.Add(new CacheContextEntry("features", hash.ToString(CultureInfo.InvariantCulture)));
}
else
{
foreach (var context in contexts.Where(ctx => ctx.StartsWith(FeaturesPrefix, StringComparison.OrdinalIgnoreCase)))
{
var featureName = context.Substring(FeaturesPrefix.Length);
var hash = await _featureHash.GetFeatureHashAsync(featureName);
entries.Add(new CacheContextEntry("features", hash.ToString(CultureInfo.InvariantCulture)));
}
}
}
}
}
| {
"content_hash": "317de8751b70aec01ab37c84c4993c4c",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 130,
"avg_line_length": 38.4468085106383,
"alnum_prop": 0.6502490315439956,
"repo_name": "lukaskabrt/Orchard2",
"id": "25600b41aedd1eabf2b67c75675bf5dbb13d5fcd",
"size": "1809",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/OrchardCore/OrchardCore.Environment.Cache/CacheContextProviders/FeaturesCacheContextProvider.cs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C#",
"bytes": "2997702"
},
{
"name": "CSS",
"bytes": "1051211"
},
{
"name": "HTML",
"bytes": "37155"
},
{
"name": "JavaScript",
"bytes": "1875847"
},
{
"name": "Liquid",
"bytes": "8674"
},
{
"name": "PHP",
"bytes": "1241"
}
],
"symlink_target": ""
} |
declare namespace jdk {
namespace jfr {
class FlightRecorderPermission extends java.security.BasicPermission {
public constructor(arg0: java.lang.String | string)
}
}
}
| {
"content_hash": "011faaedc4ea98238d2cf702c164e18c",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 74,
"avg_line_length": 21,
"alnum_prop": 0.7142857142857143,
"repo_name": "wizawu/1c",
"id": "cc5a7fff0ff2499b41e1569620a17caffa96223c",
"size": "189",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "@types/jdk/jdk.jfr.FlightRecorderPermission.d.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "4841"
},
{
"name": "JavaScript",
"bytes": "419"
},
{
"name": "Makefile",
"bytes": "846"
},
{
"name": "Shell",
"bytes": "841"
},
{
"name": "TypeScript",
"bytes": "67719"
}
],
"symlink_target": ""
} |
#pragma once
#ifndef O3DGC_SC3DMC_DECODER_H
#define O3DGC_SC3DMC_DECODER_H
#include "o3dgcCommon.h"
#include "o3dgcBinaryStream.h"
#include "o3dgcIndexedFaceSet.h"
#include "o3dgcSC3DMCEncodeParams.h"
#include "o3dgcTriangleListDecoder.h"
namespace o3dgc
{
//!
template <class T>
class SC3DMCDecoder
{
public:
//! Constructor.
SC3DMCDecoder(void)
{
m_iterator = 0;
m_streamSize = 0;
m_quantFloatArray = 0;
m_quantFloatArraySize = 0;
m_normals = 0;
m_normalsSize = 0;
m_streamType = O3DGC_STREAM_TYPE_UNKOWN;
};
//! Destructor.
~SC3DMCDecoder(void)
{
delete [] m_normals;
delete [] m_quantFloatArray;
}
//!
O3DGCErrorCode DecodeHeader(IndexedFaceSet<T> & ifs,
const BinaryStream & bstream);
//!
O3DGCErrorCode DecodePayload(IndexedFaceSet<T> & ifs,
const BinaryStream & bstream);
const SC3DMCStats & GetStats() const { return m_stats;}
unsigned long GetIterator() const { return m_iterator;}
O3DGCErrorCode SetIterator(unsigned long iterator) { m_iterator = iterator; return O3DGC_OK; }
private:
O3DGCErrorCode DecodeFloatArray(Real * const floatArray,
unsigned long numfloatArraySize,
unsigned long dimfloatArraySize,
unsigned long stride,
const Real * const minfloatArray,
const Real * const maxfloatArray,
unsigned long nQBits,
const IndexedFaceSet<T> & ifs,
O3DGCSC3DMCPredictionMode & predMode,
const BinaryStream & bstream);
O3DGCErrorCode IQuantizeFloatArray(Real * const floatArray,
unsigned long numfloatArraySize,
unsigned long dimfloatArraySize,
unsigned long stride,
const Real * const minfloatArray,
const Real * const maxfloatArray,
unsigned long nQBits);
O3DGCErrorCode DecodeIntArray(long * const intArray,
unsigned long numIntArraySize,
unsigned long dimIntArraySize,
unsigned long stride,
const IndexedFaceSet<T> & ifs,
O3DGCSC3DMCPredictionMode & predMode,
const BinaryStream & bstream);
O3DGCErrorCode ProcessNormals(const IndexedFaceSet<T> & ifs);
unsigned long m_iterator;
unsigned long m_streamSize;
SC3DMCEncodeParams m_params;
TriangleListDecoder<T> m_triangleListDecoder;
long * m_quantFloatArray;
unsigned long m_quantFloatArraySize;
Vector<char> m_orientation;
Real * m_normals;
unsigned long m_normalsSize;
SC3DMCStats m_stats;
O3DGCStreamType m_streamType;
};
}
#include "o3dgcSC3DMCDecoder.inl" // template implementation
#endif // O3DGC_SC3DMC_DECODER_H
| {
"content_hash": "ee652b546c4f7409733ddfb51ac16eb4",
"timestamp": "",
"source": "github",
"line_count": 91,
"max_line_length": 109,
"avg_line_length": 51.472527472527474,
"alnum_prop": 0.3874893253629377,
"repo_name": "orefkov/Urho3D",
"id": "e6f803b94537e5d3c61211bd721e9129121cfb7e",
"size": "5777",
"binary": false,
"copies": "14",
"ref": "refs/heads/master",
"path": "Source/ThirdParty/Assimp/contrib/Open3DGC/o3dgcSC3DMCDecoder.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "26680"
},
{
"name": "AngelScript",
"bytes": "1462571"
},
{
"name": "Batchfile",
"bytes": "5992"
},
{
"name": "C++",
"bytes": "9785998"
},
{
"name": "CMake",
"bytes": "288445"
},
{
"name": "GLSL",
"bytes": "166626"
},
{
"name": "HLSL",
"bytes": "181386"
},
{
"name": "HTML",
"bytes": "10543"
},
{
"name": "Kotlin",
"bytes": "19296"
},
{
"name": "MAXScript",
"bytes": "94704"
},
{
"name": "Mustache",
"bytes": "309"
},
{
"name": "Objective-C",
"bytes": "5441"
},
{
"name": "SCSS",
"bytes": "661"
},
{
"name": "Shell",
"bytes": "15238"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.17.1: http://docutils.sourceforge.net/" />
<title>megnet.losses module — megnet 1.3.0 documentation</title>
<link rel="stylesheet" type="text/css" href="_static/pygments.css" />
<link rel="stylesheet" type="text/css" href="_static/flasky.css" />
<script data-url_root="./" id="documentation_options" src="_static/documentation_options.js"></script>
<script src="_static/jquery.js"></script>
<script src="_static/underscore.js"></script>
<script src="_static/doctools.js"></script>
<link rel="index" title="Index" href="genindex.html" />
<link rel="search" title="Search" href="search.html" />
<link rel="prev" title="megnet.config module" href="megnet.config.html" />
<link media="only screen and (max-device-width: 480px)" href="_static/small_flask.css" type= "text/css" rel="stylesheet" />
<meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9">
</head><body>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="right" >
<a href="megnet.config.html" title="megnet.config module"
accesskey="P">previous</a> |</li>
<li class="nav-item nav-item-0"><a href="index.html">megnet 1.3.0 documentation</a> »</li>
<li class="nav-item nav-item-1"><a href="megnet.html" accesskey="U">megnet package</a> »</li>
<li class="nav-item nav-item-this"><a href="">megnet.losses module</a></li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<section id="module-megnet.losses">
<span id="megnet-losses-module"></span><h1>megnet.losses module<a class="headerlink" href="#module-megnet.losses" title="Permalink to this headline">¶</a></h1>
<p>Loss functions</p>
<dl class="py function">
<dt class="sig sig-object py" id="megnet.losses.mean_squared_error_with_scale">
<span class="sig-name descname"><span class="pre">mean_squared_error_with_scale</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">y_true</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">y_pred</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">scale</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">10000</span></span></em><span class="sig-paren">)</span><a class="reference internal" href="_modules/megnet/losses.html#mean_squared_error_with_scale"><span class="viewcode-link"><span class="pre">[source]</span></span></a><a class="headerlink" href="#megnet.losses.mean_squared_error_with_scale" title="Permalink to this definition">¶</a></dt>
<dd><p>Keras default log for tracking progress shows two decimal points,
here we multiply the mse by a factor to fully show the loss in progress bar</p>
<dl class="field-list simple">
<dt class="field-odd">Parameters</dt>
<dd class="field-odd"><ul class="simple">
<li><p><strong>y_true</strong> – (tensor) training y</p></li>
<li><p><strong>y_pred</strong> – (tensor) predicted y</p></li>
<li><p><strong>scale</strong> – (int or float) factor to multiply with mse</p></li>
</ul>
</dd>
<dt class="field-even">Returns</dt>
<dd class="field-even"><p>scaled mse (float)</p>
</dd>
</dl>
</dd></dl>
<dl class="py function">
<dt class="sig sig-object py" id="megnet.losses.mse_scale">
<span class="sig-name descname"><span class="pre">mse_scale</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">y_true</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">y_pred</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">scale</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">10000</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#megnet.losses.mse_scale" title="Permalink to this definition">¶</a></dt>
<dd><p>Keras default log for tracking progress shows two decimal points,
here we multiply the mse by a factor to fully show the loss in progress bar</p>
<dl class="field-list simple">
<dt class="field-odd">Parameters</dt>
<dd class="field-odd"><ul class="simple">
<li><p><strong>y_true</strong> – (tensor) training y</p></li>
<li><p><strong>y_pred</strong> – (tensor) predicted y</p></li>
<li><p><strong>scale</strong> – (int or float) factor to multiply with mse</p></li>
</ul>
</dd>
<dt class="field-even">Returns</dt>
<dd class="field-even"><p>scaled mse (float)</p>
</dd>
</dl>
</dd></dl>
</section>
<div class="clearer"></div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper"><h3>Related Topics</h3>
<ul>
<li><a href="index.html">Documentation overview</a><ul>
<li><a href="megnet.html">megnet package</a><ul>
<li>Previous: <a href="megnet.config.html" title="previous chapter">megnet.config module</a></li>
</ul></li>
</ul></li>
</ul>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="_sources/megnet.losses.rst.txt"
rel="nofollow">Show Source</a></li>
</ul>
</div>
<div id="searchbox" style="display: none" role="search">
<h3 id="searchlabel">Quick search</h3>
<div class="searchformwrapper">
<form class="search" action="search.html" method="get">
<input type="text" name="q" aria-labelledby="searchlabel" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"/>
<input type="submit" value="Go" />
</form>
</div>
</div>
<script>$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="footer">
© Copyright 2019, Materials Virtual Lab.
</div>
</body>
</html> | {
"content_hash": "0b9dd8149d3cccff54b72edcf871091a",
"timestamp": "",
"source": "github",
"line_count": 134,
"max_line_length": 805,
"avg_line_length": 48.485074626865675,
"alnum_prop": 0.6412190241649992,
"repo_name": "materialsvirtuallab/megnet",
"id": "7084b6b42d6687950204dc1f8f378f5aab76389f",
"size": "6513",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/megnet.losses.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "5100"
},
{
"name": "CSS",
"bytes": "4156"
},
{
"name": "HTML",
"bytes": "11342"
},
{
"name": "JavaScript",
"bytes": "9573"
},
{
"name": "Jupyter Notebook",
"bytes": "1346431"
},
{
"name": "Makefile",
"bytes": "5573"
},
{
"name": "Procfile",
"bytes": "49"
},
{
"name": "Python",
"bytes": "268660"
},
{
"name": "R",
"bytes": "10398"
},
{
"name": "Shell",
"bytes": "380"
}
],
"symlink_target": ""
} |
package com.mes.msgboard.controller;
import javax.validation.Validator;
import javax.validation.groups.Default;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import com.mes.msgboard.api.IDiscussionAPI;
import com.mes.msgboard.common.DiscussionResponseMapper;
import com.mes.msgboard.common.MESException;
import com.mes.msgboard.enums.SearchType;
import com.mes.msgboard.json.DiscussionRequest;
import com.mes.msgboard.json.DiscussionResponse;
import com.mes.msgboard.json.ErrorResponse;
import com.mes.msgboard.service.DiscussionService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
@RestController
@RequestMapping(path = "/api/${mes.api.version}")
public class DiscussionController implements IDiscussionAPI {
@Autowired
Validator validator;
@Autowired
DiscussionService discussionService;
@Override
@RequestMapping(path = "/discussions", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
@ApiOperation(value = "Create Discussion", tags = "discussion", response = DiscussionResponse.class, code = 201)
@ApiResponses(value = { @ApiResponse(code = 201, message = "Created", response = DiscussionResponse.class),
@ApiResponse(code = 400, message = "Bad Request", response = ErrorResponse.class),
@ApiResponse(code = 500, message = "Internal Server Error", response = ErrorResponse.class),
@ApiResponse(code = 401, message = "UnAuthorized", response = ErrorResponse.class) })
@ApiImplicitParam(paramType="header",name="Authorization",required=true)
@ResponseStatus(code = HttpStatus.CREATED)
public ResponseEntity<DiscussionResponse> createDiscussion(@RequestBody DiscussionRequest discussionRequest)
throws MESException {
try {
if (validator.validate(discussionRequest, Default.class).size() > 0) {
throw new MESException("BAD_REQUEST", "Missing required param", HttpStatus.BAD_REQUEST, null);
}
if (validator.validate(discussionRequest.getDiscussion(), Default.class).size() > 0) {
throw new MESException("BAD_REQUEST", "Missing required param", HttpStatus.BAD_REQUEST, null);
}
return ResponseEntity.status(HttpStatus.CREATED).body(new DiscussionResponseMapper()
.apply(discussionService.createDiscusion(discussionRequest.getDiscussion())));
} catch (Exception e) {
if (e instanceof MESException) {
throw e;
}
throw new MESException("INTERNAL_SERVER_ERROR", "INTERNAL_SERVER_ERROR", HttpStatus.INTERNAL_SERVER_ERROR,
e);
}
}
@Override
@RequestMapping(path = "/discussions", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@ApiOperation(value = "Get All Discussions", tags = "discussion", response = DiscussionResponse.class, code = 200)
@ApiResponses(value = { @ApiResponse(code = 200, message = "OK", response = DiscussionResponse.class),
@ApiResponse(code = 400, message = "Bad Request", response = ErrorResponse.class),
@ApiResponse(code = 500, message = "Internal Server Error", response = ErrorResponse.class),
@ApiResponse(code = 401, message = "UnAuthorized", response = ErrorResponse.class) })
@ApiImplicitParam(paramType="header",name="Authorization",required=true)
@ResponseStatus(code = HttpStatus.OK)
public ResponseEntity<DiscussionResponse> getAllDiscussion() throws MESException {
try {
return ResponseEntity.status(HttpStatus.OK)
.body(new DiscussionResponseMapper().apply(discussionService.getAllDiscusion()));
} catch (Exception e) {
if (e instanceof MESException) {
throw e;
}
throw new MESException("INTERNAL_SERVER_ERROR", "INTERNAL_SERVER_ERROR", HttpStatus.INTERNAL_SERVER_ERROR,
e);
}
}
@Override
@RequestMapping(path = "/categories/{categoryId}/discussions", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@ApiOperation(value = "Get All Discussions for a category", tags = "discussion", response = DiscussionResponse.class, code = 200)
@ApiResponses(value = { @ApiResponse(code = 200, message = "OK", response = DiscussionResponse.class),
@ApiResponse(code = 400, message = "Bad Request", response = ErrorResponse.class),
@ApiResponse(code = 500, message = "Internal Server Error", response = ErrorResponse.class),
@ApiResponse(code = 401, message = "UnAuthorized", response = ErrorResponse.class) })
@ApiImplicitParam(paramType="header",name="Authorization",required=true)
@ResponseStatus(code = HttpStatus.OK)
public ResponseEntity<DiscussionResponse> getAllDiscussionByCategory(
@ApiParam(name = "categoryId", required = true) @PathVariable("categoryId") String categoryId)
throws MESException {
try {
return ResponseEntity.status(HttpStatus.OK).body(
new DiscussionResponseMapper().apply(discussionService.getAllDiscusionByCategory(categoryId)));
} catch (Exception e) {
if (e instanceof MESException) {
throw e;
}
throw new MESException("INTERNAL_SERVER_ERROR", "INTERNAL_SERVER_ERROR", HttpStatus.INTERNAL_SERVER_ERROR,
e);
}
}
@Override
@RequestMapping(path = "/discussions", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
@ApiOperation(value = "Update a discussion", tags = "discussion", response = DiscussionResponse.class, code = 202)
@ApiResponses(value = { @ApiResponse(code = 202, message = "Accepted", response = DiscussionResponse.class),
@ApiResponse(code = 400, message = "Bad Request", response = ErrorResponse.class),
@ApiResponse(code = 500, message = "Internal Server Error", response = ErrorResponse.class),
@ApiResponse(code = 401, message = "UnAuthorized", response = ErrorResponse.class) })
@ApiImplicitParam(paramType="header",name="Authorization",required=true)
@ResponseStatus(code = HttpStatus.ACCEPTED)
public ResponseEntity<DiscussionResponse> editDiscussion(@RequestBody DiscussionRequest discussionRequest)
throws MESException {
try {
if (discussionRequest.getDiscussion().getId() == null) {
throw new MESException("BAD_REQUEST", "ID must be present for update", HttpStatus.BAD_REQUEST, null);
}
return ResponseEntity.status(HttpStatus.ACCEPTED).body(new DiscussionResponseMapper()
.apply(discussionService.updateDiscussion(discussionRequest.getDiscussion())));
} catch (Exception e) {
if (e instanceof MESException) {
throw e;
}
throw new MESException("INTERNAL_SERVER_ERROR", "INTERNAL_SERVER_ERROR", HttpStatus.INTERNAL_SERVER_ERROR,
e);
}
}
@Override
@RequestMapping(path = "/discussions/search", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@ApiOperation(value = "Search discussions", tags = "discussion", response = DiscussionResponse.class, code = 200)
@ApiResponses(value = { @ApiResponse(code = 200, message = "OK", response = DiscussionResponse.class),
@ApiResponse(code = 400, message = "Bad Request", response = ErrorResponse.class),
@ApiResponse(code = 500, message = "Internal Server Error", response = ErrorResponse.class),
@ApiResponse(code = 401, message = "UnAuthorized", response = ErrorResponse.class) })
@ApiImplicitParam(paramType="header",name="Authorization",required=true)
@ResponseStatus(code = HttpStatus.OK)
public ResponseEntity<DiscussionResponse> searchDiscussion(
@ApiParam(example = "body", value = "filter") @RequestParam("filter") SearchType filter,
@ApiParam(example = "some text", value = "textQuery") @RequestParam("textQuery") String textQuery)
throws MESException {
try {
return ResponseEntity.status(HttpStatus.OK)
.body(new DiscussionResponseMapper().apply(discussionService.searchDiscussion(filter, textQuery)));
} catch (Exception e) {
if (e instanceof MESException) {
throw e;
}
throw new MESException("INTERNAL_SERVER_ERROR", "INTERNAL_SERVER_ERROR", HttpStatus.INTERNAL_SERVER_ERROR,
e);
}
}
}
| {
"content_hash": "29977e22d8bbb9d5ea9d07f70c3e3811",
"timestamp": "",
"source": "github",
"line_count": 172,
"max_line_length": 158,
"avg_line_length": 49.9593023255814,
"alnum_prop": 0.7616664727103456,
"repo_name": "dhruba619/mes",
"id": "85a59598ba59e92796fe440d33bfae0bb65ee905",
"size": "8593",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/mes/msgboard/controller/DiscussionController.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "117618"
}
],
"symlink_target": ""
} |
[](http://badge.fury.io/gh/nekojira%2Fwp-api-menus) [](https://gitter.im/nekojira/wp-api-menus?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[WordPress](http://www.wordpress.org/) plugin that extends the JSON REST [WP API](https://github.com/WP-API/WP-API) with new routes pointing to WordPress registered menus. Read the [WP API documentation](http://wp-api.org/).
[](https://wordpress.org/plugins/wp-api-menus/)
#### New routes available:
- `/menus` list of every registered menu.
- `/menus/<id>` data for a specific menu.
- `/menu-locations` list of all registered theme locations.
- `/menu-locations/<location>` data for menu in specified menu in theme location.
Currently, the `menu-locations/<location>` route for individual menus will return a tree with full menu hierarchy, with correct menu item order and listing children for each menu item. The `menus/<id>` route will output menu details and a flat array of menu items. Item order or if each item has a parent will be indicated in each item attributes, but this route won't output items as a tree.
You can alter the data arrangement of each individual menu items and children using the filter hook `json_menus_format_menu_item`.
#### Contributing
* Submit a pull request or open a ticket here on Github.
| {
"content_hash": "5237f1906803e70126f0f6fc326c7f8b",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 393,
"avg_line_length": 76.0952380952381,
"alnum_prop": 0.7571964956195244,
"repo_name": "pjlamb12/wp-angular",
"id": "f016b7dd71550239e8ba223ad393b9e50ea09383",
"size": "1642",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "wordpress/wp-content/plugins/wp-api-menus/README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "872"
},
{
"name": "CSS",
"bytes": "1728062"
},
{
"name": "HTML",
"bytes": "14669"
},
{
"name": "JavaScript",
"bytes": "1773219"
},
{
"name": "PHP",
"bytes": "9262115"
}
],
"symlink_target": ""
} |
angular.module('angularAppRoutes', ['ui.router'])
.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('/', {
url: '/findGames',
templateUrl: 'angular_views/findGames.html',
controller: 'findGamesController'
})
.state('findGames', {
url: '/findGames',
templateUrl: 'angular_views/findGames.html',
controller: 'findGamesController'
})
.state('listAGame', {
url: '/listAGame',
templateUrl: 'angular_views/listAGame.html',
controller: 'listAGameController'
})
.state('myGames', {
url: '/myGames',
templateUrl: 'angular_views/myGames.html',
controller: 'myGamesController'
})
.state('login', {
url: '/login',
templateUrl: 'angular_views/login.html',
controller: 'loginController'
})
.state('signup', {
url: '/signup',
templateUrl: 'angular_views/signup.html',
controller: 'signupController'
})
.state('logout', {
url: '/logout',
templateUrl: 'angular_views/logout.html',
controller: 'logoutController'
})
.state('seeGame', {
url: '/seeGame',
templateUrl: 'angular_views/seeGame.html',
controller: 'seeGameController'
})
.state('userProfile', {
url: '/userProfile',
templateUrl: 'angular_views/userProfile.html',
controller: 'userProfileController'
})
;
$urlRouterProvider.otherwise('/findGames');
}]);
| {
"content_hash": "70a82f436483c0c504a512886e97e363",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 97,
"avg_line_length": 27.82758620689655,
"alnum_prop": 0.570631970260223,
"repo_name": "21tag/AngularRecess",
"id": "8810b8a828b6146959c0cf3be215ea75cc0d4231",
"size": "1614",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/js/angular_routes.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "362528"
},
{
"name": "CoffeeScript",
"bytes": "3443"
},
{
"name": "JavaScript",
"bytes": "484383"
},
{
"name": "Ruby",
"bytes": "878"
}
],
"symlink_target": ""
} |
package uk.co.real_logic.sbe.examples;
import org.agrona.DirectBuffer;
import uk.co.real_logic.sbe.PrimitiveValue;
import uk.co.real_logic.sbe.ir.Encoding;
import uk.co.real_logic.sbe.ir.Token;
import uk.co.real_logic.sbe.otf.TokenListener;
import uk.co.real_logic.sbe.otf.Types;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Iterator;
import java.util.List;
public class ExampleTokenListener implements TokenListener
{
private int compositeLevel = 0;
private final PrintWriter out;
private final Deque<String> namedScope = new ArrayDeque<>();
private final byte[] tempBuffer = new byte[1024];
public ExampleTokenListener(final PrintWriter out)
{
this.out = out;
}
public void onBeginMessage(final Token token)
{
namedScope.push(token.name() + ".");
}
public void onEndMessage(final Token token)
{
namedScope.pop();
}
public void onEncoding(
final Token fieldToken,
final DirectBuffer buffer,
final int index,
final Token typeToken,
final int actingVersion)
{
final CharSequence value = readEncodingAsString(buffer, index, typeToken, actingVersion);
printScope();
out.append(compositeLevel > 0 ? typeToken.name() : fieldToken.name())
.append('=')
.append(value)
.println();
}
public void onEnum(
final Token fieldToken,
final DirectBuffer buffer,
final int bufferIndex,
final List<Token> tokens,
final int beginIndex,
final int endIndex,
final int actingVersion)
{
final Token typeToken = tokens.get(beginIndex + 1);
final long encodedValue = readEncodingAsLong(buffer, bufferIndex, typeToken, actingVersion);
String value = null;
if (fieldToken.isConstantEncoding())
{
final String refValue = fieldToken.encoding().constValue().toString();
final int indexOfDot = refValue.indexOf('.');
value = -1 == indexOfDot ? refValue : refValue.substring(indexOfDot + 1);
}
else
{
for (int i = beginIndex + 1; i < endIndex; i++)
{
if (encodedValue == tokens.get(i).encoding().constValue().longValue())
{
value = tokens.get(i).name();
break;
}
}
}
printScope();
out.append(determineName(0, fieldToken, tokens, beginIndex))
.append('=')
.append(value)
.println();
}
public void onBitSet(
final Token fieldToken,
final DirectBuffer buffer,
final int bufferIndex,
final List<Token> tokens,
final int beginIndex,
final int endIndex,
final int actingVersion)
{
final Token typeToken = tokens.get(beginIndex + 1);
final long encodedValue = readEncodingAsLong(buffer, bufferIndex, typeToken, actingVersion);
printScope();
out.append(determineName(0, fieldToken, tokens, beginIndex)).append(':');
for (int i = beginIndex + 1; i < endIndex; i++)
{
out.append(' ').append(tokens.get(i).name()).append('=');
final long bitPosition = tokens.get(i).encoding().constValue().longValue();
final boolean flag = (encodedValue & (1L << bitPosition)) != 0;
out.append(Boolean.toString(flag));
}
out.println();
}
public void onBeginComposite(
final Token fieldToken, final List<Token> tokens, final int fromIndex, final int toIndex)
{
++compositeLevel;
namedScope.push(determineName(1, fieldToken, tokens, fromIndex) + ".");
}
public void onEndComposite(final Token fieldToken, final List<Token> tokens, final int fromIndex, final int toIndex)
{
--compositeLevel;
namedScope.pop();
}
public void onGroupHeader(final Token token, final int numInGroup)
{
printScope();
out.append(token.name())
.append(" Group Header : numInGroup=")
.append(Integer.toString(numInGroup))
.println();
}
public void onBeginGroup(final Token token, final int groupIndex, final int numInGroup)
{
namedScope.push(token.name() + ".");
}
public void onEndGroup(final Token token, final int groupIndex, final int numInGroup)
{
namedScope.pop();
}
public void onVarData(
final Token fieldToken,
final DirectBuffer buffer,
final int bufferIndex,
final int length,
final Token typeToken)
{
final String value;
try
{
final String characterEncoding = typeToken.encoding().characterEncoding();
if (null == characterEncoding)
{
value = length + " bytes of raw data";
}
else
{
buffer.getBytes(bufferIndex, tempBuffer, 0, length);
value = new String(tempBuffer, 0, length, characterEncoding);
}
}
catch (final UnsupportedEncodingException ex)
{
ex.printStackTrace();
return;
}
printScope();
out.append(fieldToken.name())
.append('=')
.append(value)
.println();
}
private String determineName(
final int thresholdLevel, final Token fieldToken, final List<Token> tokens, final int fromIndex)
{
if (compositeLevel > thresholdLevel)
{
return tokens.get(fromIndex).name();
}
else
{
return fieldToken.name();
}
}
private static CharSequence readEncodingAsString(
final DirectBuffer buffer, final int index, final Token typeToken, final int actingVersion)
{
final PrimitiveValue constOrNotPresentValue = constOrNotPresentValue(typeToken, actingVersion);
if (null != constOrNotPresentValue)
{
if (constOrNotPresentValue.size() == 1)
{
try
{
final byte[] bytes = { (byte)constOrNotPresentValue.longValue() };
return new String(bytes, constOrNotPresentValue.characterEncoding());
}
catch (final UnsupportedEncodingException ex)
{
throw new RuntimeException(ex);
}
}
else
{
return constOrNotPresentValue.toString();
}
}
final StringBuilder sb = new StringBuilder();
final Encoding encoding = typeToken.encoding();
final int elementSize = encoding.primitiveType().size();
for (int i = 0, size = typeToken.arrayLength(); i < size; i++)
{
Types.appendAsString(sb, buffer, index + (i * elementSize), encoding);
sb.append(", ");
}
sb.setLength(sb.length() - 2);
return sb;
}
private static long readEncodingAsLong(
final DirectBuffer buffer, final int bufferIndex, final Token typeToken, final int actingVersion)
{
final PrimitiveValue constOrNotPresentValue = constOrNotPresentValue(typeToken, actingVersion);
if (null != constOrNotPresentValue)
{
return constOrNotPresentValue.longValue();
}
return Types.getLong(buffer, bufferIndex, typeToken.encoding());
}
private static PrimitiveValue constOrNotPresentValue(final Token token, final int actingVersion)
{
if (token.isConstantEncoding())
{
return token.encoding().constValue();
}
else if (token.isOptionalEncoding() && actingVersion < token.version())
{
return token.encoding().applicableNullValue();
}
return null;
}
private void printScope()
{
final Iterator<String> i = namedScope.descendingIterator();
while (i.hasNext())
{
out.print(i.next());
}
}
}
| {
"content_hash": "90c1556d9f3550917a631bebd178757e",
"timestamp": "",
"source": "github",
"line_count": 276,
"max_line_length": 120,
"avg_line_length": 29.92391304347826,
"alnum_prop": 0.5838479234774185,
"repo_name": "marksantos/simple-binary-encoding",
"id": "58a0124168367a18fd0acecd3da32730abf96ca9",
"size": "8858",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sbe-samples/src/main/java/uk/co/real_logic/sbe/examples/ExampleTokenListener.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "968"
},
{
"name": "C",
"bytes": "271"
},
{
"name": "C#",
"bytes": "234093"
},
{
"name": "C++",
"bytes": "335680"
},
{
"name": "CMake",
"bytes": "15908"
},
{
"name": "Go",
"bytes": "89617"
},
{
"name": "HTML",
"bytes": "259"
},
{
"name": "Java",
"bytes": "1338243"
},
{
"name": "Makefile",
"bytes": "2433"
},
{
"name": "Rust",
"bytes": "11288"
},
{
"name": "Shell",
"bytes": "2937"
}
],
"symlink_target": ""
} |
<?php
namespace App\Template;
use App\Model\AttendanceRecord;
class AttendanceTemplate
{
/**
* @var AttendanceRecord
*/
private $attendanceRecord;
public function __construct(AttendanceRecord $attendanceRecord)
{
$this->attendanceRecord = $attendanceRecord;
}
public function render()
{
return view('councillor.attendance-partial')
->with('rating_color', $this->ratingColor())
->with('attendanceRating', $this->attendanceRating())
->with('attendance_record', $this->attendanceRecord);
}
private function attendanceRating()
{
$percent = $this->attendanceRecord->votePercent();
if ($percent >= 99) {
return "Flawless";
}
if ($percent >= 85) {
return "Good";
}
if ($percent >= 70) {
return "Average";
}
return "Poor";
}
public function ratingColor()
{
$percent = $this->attendanceRecord->votePercent();
if ($percent >= 99) {
return "text-green-dark";
}
if ($percent >= 95) {
return "text-green-dark";
}
if ($percent >= 90) {
return "text-green";
}
if ($percent >= 85) {
return "text-green-light";
}
if ($percent >= 80) {
return "text-orange-light";
}
if ($percent >= 75) {
return "text-orange";
}
if ($percent >= 70) {
return "text-orange-dark";
}
if ($percent >= 65) {
return "text-red-light";
}
if ($percent >= 60) {
return "text-red";
}
return "text-red-dark";
}
}
| {
"content_hash": "7e1f801c1400298476db1e5784831d77",
"timestamp": "",
"source": "github",
"line_count": 91,
"max_line_length": 67,
"avg_line_length": 19.505494505494507,
"alnum_prop": 0.4856338028169014,
"repo_name": "tpavlek/YEGVotes",
"id": "3ecc2154801017505bbd6f84041c4852a84ed1ec",
"size": "1775",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/Template/AttendanceTemplate.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "58742"
},
{
"name": "HTML",
"bytes": "113160"
},
{
"name": "JavaScript",
"bytes": "27474"
},
{
"name": "PHP",
"bytes": "208529"
},
{
"name": "Vue",
"bytes": "1146"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.4"/>
<title>UE4AM: UE4AM_AppHandler Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { searchBox.OnSelectItem(0); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">UE4AM
 <span id="projectnumber">0.2</span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.4 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li class="current"><a href="annotated.html"><span>Data Structures</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Data Structures</span></a></li>
<li><a href="classes.html"><span>Data Structure Index</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Data Fields</span></a></li>
</ul>
</div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
<a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark"> </span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark"> </span>Data Structures</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark"> </span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark"> </span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark"> </span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark"> </span>Pages</a></div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
</div><!-- top -->
<div class="header">
<div class="summary">
<a href="#pub-methods">Public Member Functions</a> </div>
<div class="headertitle">
<div class="title">UE4AM_AppHandler Class Reference</div> </div>
</div><!--header-->
<div class="contents">
<p>The App Handler is for managing multiple apps and autorisations on the same server.
<a href="class_u_e4_a_m___app_handler.html#details">More...</a></p>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a>
Public Member Functions</h2></td></tr>
<tr class="memitem:a919f9fd314bea09db6a45a5f2bf4b28f"><td class="memItemLeft" align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="class_u_e4_a_m___app_handler.html#a919f9fd314bea09db6a45a5f2bf4b28f">AddApp</a> ($token)</td></tr>
<tr class="separator:a919f9fd314bea09db6a45a5f2bf4b28f"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a2de878e2040a5f01b8537a159cde6b91"><td class="memItemLeft" align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="class_u_e4_a_m___app_handler.html#a2de878e2040a5f01b8537a159cde6b91">Auth</a> ($appid, $token)</td></tr>
<tr class="separator:a2de878e2040a5f01b8537a159cde6b91"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a94694c6eb18f42b9ae57fb363541c3f4"><td class="memItemLeft" align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="class_u_e4_a_m___app_handler.html#a94694c6eb18f42b9ae57fb363541c3f4">RemoveApp</a> ($appid, $token)</td></tr>
<tr class="separator:a94694c6eb18f42b9ae57fb363541c3f4"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2>
<div class="textblock"><p>The App Handler is for managing multiple apps and autorisations on the same server. </p>
</div><h2 class="groupheader">Member Function Documentation</h2>
<a class="anchor" id="a919f9fd314bea09db6a45a5f2bf4b28f"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">AddApp </td>
<td>(</td>
<td class="paramtype"> </td>
<td class="paramname"><em>$token</em>)</td><td></td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
</div>
</div>
<a class="anchor" id="a2de878e2040a5f01b8537a159cde6b91"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">Auth </td>
<td>(</td>
<td class="paramtype"> </td>
<td class="paramname"><em>$appid</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype"> </td>
<td class="paramname"><em>$token</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
</div>
</div>
<a class="anchor" id="a94694c6eb18f42b9ae57fb363541c3f4"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">RemoveApp </td>
<td>(</td>
<td class="paramtype"> </td>
<td class="paramname"><em>$appid</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype"> </td>
<td class="paramname"><em>$token</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
</div>
</div>
<hr/>The documentation for this class was generated from the following file:<ul>
<li>inc/<a class="el" href="apphandler_8php.html">apphandler.php</a></li>
</ul>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Fri Mar 20 2015 17:25:42 for UE4AM by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.4
</small></address>
</body>
</html>
| {
"content_hash": "e405b1a0155a9b0ed767edf79b5b54cf",
"timestamp": "",
"source": "github",
"line_count": 187,
"max_line_length": 826,
"avg_line_length": 45.42245989304813,
"alnum_prop": 0.6351542265128326,
"repo_name": "xzessmedia/UE4AM",
"id": "f3cc239714146b704e5b3a8dbb1793038a6c0c3b",
"size": "8494",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "UE4AM/docs/html/class_u_e4_a_m___app_handler.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "926"
},
{
"name": "C++",
"bytes": "58981"
},
{
"name": "CSS",
"bytes": "384552"
},
{
"name": "HTML",
"bytes": "867040"
},
{
"name": "JavaScript",
"bytes": "1657620"
},
{
"name": "Makefile",
"bytes": "35856"
},
{
"name": "PHP",
"bytes": "67967"
},
{
"name": "PostScript",
"bytes": "23049"
},
{
"name": "QMake",
"bytes": "533"
},
{
"name": "Shell",
"bytes": "508"
},
{
"name": "TeX",
"bytes": "311147"
}
],
"symlink_target": ""
} |
angular.module(PKG.name + '.feature.streams')
.controller('StreamsCreateController', function($scope, MyCDAPDataSource, $modalInstance, caskFocusManager) {
caskFocusManager.focus('streamId');
var dataSrc = new MyCDAPDataSource($scope);
this.streamId = '';
this.createStream = function() {
dataSrc
.request({
_cdapNsPath: '/streams/' + $scope.streamId,
method: 'PUT'
})
.then(function(res) {
$modalInstance.close(res);
}, function(err) {
this.error = err;
}.bind(this));
};
this.closeModal = function() {
$modalInstance.close();
};
});
| {
"content_hash": "4f1bb114a5b1fd004ee79af403d456ff",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 111,
"avg_line_length": 23,
"alnum_prop": 0.5757121439280359,
"repo_name": "mpouttuclarke/cdap",
"id": "dd8f44a0cf699829083717519b2cdf9a6822cc25",
"size": "1264",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "cdap-ui/app/features/streams/controllers/create-ctrl.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "13173"
},
{
"name": "CSS",
"bytes": "206745"
},
{
"name": "HTML",
"bytes": "436495"
},
{
"name": "Java",
"bytes": "16032874"
},
{
"name": "JavaScript",
"bytes": "1119446"
},
{
"name": "Python",
"bytes": "90731"
},
{
"name": "Scala",
"bytes": "30287"
},
{
"name": "Shell",
"bytes": "177663"
}
],
"symlink_target": ""
} |
layout: post
title: The Drumms
category: music
---
<p>Para iniciar el año, les comparto el disco homonimo The Drumms</p>
<p>https://itunes.apple.com/mx/album/the-drums/id376081904?l=en</p>
<p>Vale mucho la pena y después de verlos en el Corona Capital gracias a la recomendación de mi padre me gusto mucho la canción Let's go surfing!</p>
<p>Es lo que yo puedo llamar un buen rock indie de actualidad.</p>
| {
"content_hash": "39e426432fbef37e244662bad8a911e2",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 149,
"avg_line_length": 50.75,
"alnum_prop": 0.7512315270935961,
"repo_name": "gzfrancisco/gzfrancisco.github.io",
"id": "8999748b194f4cc08f01e3f2e5b859e369bb9d02",
"size": "414",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_posts/2013-01-02-the-drumms.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "21105"
},
{
"name": "HTML",
"bytes": "49719"
},
{
"name": "JavaScript",
"bytes": "396"
},
{
"name": "Ruby",
"bytes": "1701"
}
],
"symlink_target": ""
} |
Jasper is a Java monadic parser, a CS2104R NUS project.
Built upon Parsec, Jasper is more of educational than high performance
parser.
This is a work in progress.
## License
MIT
| {
"content_hash": "239042fb85866247867b6d636a5cab37",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 70,
"avg_line_length": 22.5,
"alnum_prop": 0.7777777777777778,
"repo_name": "evansb/jasper",
"id": "0c31aa7c5ef1ab0f8b27150059400188e07ea3e8",
"size": "190",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Haskell",
"bytes": "82325"
},
{
"name": "Java",
"bytes": "3957"
},
{
"name": "Shell",
"bytes": "79"
}
],
"symlink_target": ""
} |
package jp.cafebabe.kunai.source.factories;
import static jp.cafebabe.kunai.util.AssertHelper.assertThrows;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.Before;
import org.junit.Test;
public class JarFileDataSourceFactoryTest {
private Path jarfile;
private Path directory;
private JarFileDataSourceFactory factory = new JarFileDataSourceFactory();
@Before
public void setUp(){
jarfile = Paths.get("target/test-classes/hello/target/hello-1.0-SNAPSHOT.jar");
directory = Paths.get("target/test-classes/hello/target/classes");
}
@Test
public void testBasic() throws Exception{
assertThat(factory.isTarget(jarfile), is(true));
assertThat(factory.isTarget(directory), is(false));
factory.build(new File(jarfile.toString()));
}
@Test
public void testThrows() throws Exception{
assertThrows(UnsupportedDataSourceException.class,
() -> factory.build(directory));
}
}
| {
"content_hash": "29e90f68a2a947e384df8d12a3f76250",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 87,
"avg_line_length": 29.63157894736842,
"alnum_prop": 0.7158081705150977,
"repo_name": "tamada/pochi",
"id": "2fe5048e0888af5120445b0b272499e2be278ac8",
"size": "1126",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "kunai2/src/test/java/jp/cafebabe/kunai/source/factories/JarFileDataSourceFactoryTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1335"
},
{
"name": "Dockerfile",
"bytes": "3554"
},
{
"name": "HTML",
"bytes": "5126"
},
{
"name": "Java",
"bytes": "333008"
},
{
"name": "JavaScript",
"bytes": "1067"
},
{
"name": "Shell",
"bytes": "5530"
}
],
"symlink_target": ""
} |
SET AUTOCOMMIT = 0;
START TRANSACTION;
--
-- Insert user information into the temporary tables. To add users to the HSQL database, edit things here.
--
INSERT INTO users_TEMP (username, password, enabled) VALUES
('admin','password',true),
('user','password',true);
INSERT INTO authorities_TEMP (username, authority) VALUES
('admin','ROLE_ADMIN'),
('admin','ROLE_USER'),
('user','ROLE_USER');
-- By default, the username column here has to match the username column in the users table, above
INSERT INTO user_info_TEMP (sub, preferred_username, name, email, email_verified) VALUES
('90342.ASDFJWFA','admin','Demo Admin','admin@example.com', true),
('01921.FLANRJQW','user','Demo User','user@example.com', true);
--
-- Merge the temporary users safely into the database. This is a two-step process to keep users from being created on every startup with a persistent store.
--
INSERT INTO users (username, password, enabled)
SELECT username, password, enabled FROM users_TEMP
ON DUPLICATE KEY UPDATE users.username = users.username;
INSERT INTO authorities (username,authority)
SELECT username, authority FROM authorities_TEMP
ON DUPLICATE KEY UPDATE authorities.username = authorities.username;
INSERT INTO user_info (sub, preferred_username, name, email, email_verified)
SELECT sub, preferred_username, name, email, email_verified FROM user_info_TEMP
ON DUPLICATE KEY UPDATE user_info.preferred_username = user_info.preferred_username;
--
-- Close the transaction and turn autocommit back on
--
COMMIT;
SET AUTOCOMMIT = 1;
| {
"content_hash": "9a7de063f590f3e085c3743b331d6c40",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 156,
"avg_line_length": 32.895833333333336,
"alnum_prop": 0.7365421152628245,
"repo_name": "uchicago/shibboleth-oidc",
"id": "fc82e4800664ffda66f6e5b75d432d2733c13c56",
"size": "1668",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "idp-webapp-overlay/src/main/webapp/idp/conf/schema/mysql/users.sql",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "46533"
},
{
"name": "CSS",
"bytes": "5601"
},
{
"name": "Dockerfile",
"bytes": "1214"
},
{
"name": "HTML",
"bytes": "2592"
},
{
"name": "Java",
"bytes": "226913"
},
{
"name": "JavaScript",
"bytes": "50610"
},
{
"name": "PHP",
"bytes": "100"
},
{
"name": "PLSQL",
"bytes": "7396"
},
{
"name": "Shell",
"bytes": "1533"
},
{
"name": "TSQL",
"bytes": "8936"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title></title>
<link rel="stylesheet" href="../../build/aui-css/css/bootstrap.css">
<script src="../../build/aui/aui.js"></script>
</head>
<body>
<h1>AlloyUI - Video</h1>
<div id="container">
<div id="demo"></div>
<br>
<a href="#" class="btn btn-success" id="play-btn">
<span class="glyphicon glyphicon-play"></span> Play
</a>
<a href="#" class="btn btn-danger" id="pause-btn">
<span class="glyphicon glyphicon-pause"></span> Pause
</a>
<a href="#" class="btn btn-info" id="change-video-btn">
<span class="glyphicon glyphicon-film"></span> Change video
</a>
</div>
<script>
YUI({ filter:'raw' }).use('aui-video', function(Y) {
var video = new Y.Video({
boundingBox: '#demo',
width: 640,
height: 368,
url: 'http://videos.liferay.com/webinars/2010-08-11.mp4',
ogvUrl: 'http://videos.liferay.com/webinars/2010-08-11.ogv',
swfUrl: 'http://videos.liferay.com/common/player.swf',
poster: 'assets/sample-jpg.jpg',
fixedAttributes: {
allowfullscreen: 'true'
}
}).render();
Y.one('#play-btn').on('click', function(e) {
e.preventDefault();
video.play();
});
Y.one('#pause-btn').on('click', function(e) {
e.preventDefault();
video.pause();
});
Y.one('#change-video-btn').on('click', function(e) {
e.preventDefault();
video.pause();
video.set('ogvUrl', 'assets/movie.ogv');
video.set('url', 'assets/movie.mp4');
video.load();
video.play();
});
});
</script>
</body>
</html> | {
"content_hash": "79316c4cc4db2a178360f7b490dde724",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 76,
"avg_line_length": 28.136363636363637,
"alnum_prop": 0.5325794291868605,
"repo_name": "ssmith353/alloy-ui",
"id": "86f8e8cce020fe372129665c30002bb9a4d713ae",
"size": "1857",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "demos/video/index.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using RolePlayingGameData;
#endregion
namespace RolePlaying
{
/// <summary>
/// Displays the gear in the party inventory and allows the user to sell them.
/// </summary>
class StoreSellScreen : InventoryScreen
{
#region Graphics Data
/// <summary>
/// The left-facing quantity arrow.
/// </summary>
private Texture2D leftQuantityArrow;
/// <summary>
/// The right-facing quantity arrow.
/// </summary>
private Texture2D rightQuantityArrow;
#endregion
#region Columns
private const int nameColumnInterval = 80;
private const int powerColumnInterval = 270;
private const int quantityColumnInterval = 340;
private string priceColumnText = "Price";
private const int priceColumnInterval = 120;
#endregion
#region Data Access
/// <summary>
/// The store whose goods are being displayed.
/// </summary>
private Store store;
/// <summary>
/// The selected quantity of the current entry.
/// </summary>
private int selectedQuantity = 0;
/// <summary>
/// Resets the selected quantity to the maximum value for the selected entry.
/// </summary>
private void ResetQuantities()
{
selectedQuantity = 1;
}
#endregion
#region List Navigation
/// <summary>
/// Move the current selection up one entry.
/// </summary>
protected override void MoveCursorUp()
{
base.MoveCursorUp();
ResetQuantities();
}
/// <summary>
/// Move the current selection down one entry.
/// </summary>
protected override void MoveCursorDown()
{
base.MoveCursorDown();
ResetQuantities();
}
/// <summary>
/// Decrease the selected quantity by one.
/// </summary>
protected override void MoveCursorLeft()
{
ReadOnlyCollection<ContentEntry<Gear>> entries = GetDataList();
if (entries.Count > 0)
{
// loop to one if the selected quantity is already at maximum.
if (selectedQuantity > 1)
{
selectedQuantity--;
}
else
{
selectedQuantity = entries[SelectedIndex].Count;
}
}
else
{
selectedQuantity = 0;
}
}
/// <summary>
/// Increase the selected quantity by one.
/// </summary>
protected override void MoveCursorRight()
{
ReadOnlyCollection<ContentEntry<Gear>> entries = GetDataList();
if (entries.Count > 0)
{
// loop to one if the selected quantity is already at maximum.
selectedQuantity = selectedQuantity < entries[SelectedIndex].Count ?
selectedQuantity + 1 : 1;
}
else
{
selectedQuantity = 0;
}
}
#endregion
#region Initialization
/// <summary>
/// Creates a new StoreSellScreen object for the given store.
/// </summary>
public StoreSellScreen(Store store)
: base(true)
{
// check the parameter
if ((store == null) || (store.StoreCategories.Count <= 0))
{
throw new ArgumentNullException("store");
}
this.store = store;
// configure the menu text
selectButtonText = "Sell";
backButtonText = "Back";
xButtonText = String.Empty;
yButtonText = String.Empty;
ResetQuantities();
}
/// <summary>
/// Load the graphics content from the content manager.
/// </summary>
public override void LoadContent()
{
base.LoadContent();
ContentManager content = ScreenManager.Game.Content;
leftQuantityArrow =
content.Load<Texture2D>(@"Textures\Buttons\QuantityArrowLeft");
rightQuantityArrow =
content.Load<Texture2D>(@"Textures\Buttons\QuantityArrowRight");
}
#endregion
#region Input Handling
/// <summary>
/// Respond to the triggering of the Select action.
/// </summary>
protected override void SelectTriggered(ContentEntry<Gear> entry)
{
// check the parameter
if ((entry == null) || (entry.Content == null))
{
return;
}
// make sure the selected quantity is valid
selectedQuantity = Math.Min(selectedQuantity, entry.Count);
// add the gold to the party's inventory
Session.Party.PartyGold += selectedQuantity *
(int)Math.Ceiling(entry.Content.GoldValue * store.SellMultiplier);
// remove the items from the party's inventory
Session.Party.RemoveFromInventory(entry.Content, selectedQuantity);
// reset the quantities - either gold has gone down or the total was bad
ResetQuantities();
}
/// <summary>
/// Switch to the previous store category.
/// </summary>
protected override void PageScreenLeft()
{
isItems = !isItems;
ResetTriggerText();
ResetQuantities();
}
/// <summary>
/// Switch to the next store category.
/// </summary>
protected override void PageScreenRight()
{
isItems = !isItems;
ResetTriggerText();
ResetQuantities();
}
/// <summary>
/// Reset the trigger button text to the names of the
/// previous and next UI screens.
/// </summary>
protected override void ResetTriggerText()
{
leftTriggerText = rightTriggerText = isItems ? "Equipment" : "Items";
}
#endregion
#region Drawing
/// <summary>
/// Draw the entry at the given position in the list.
/// </summary>
/// <param name="contentEntry">The entry to draw.</param>
/// <param name="position">The position to draw the entry at.</param>
/// <param name="isSelected">If true, this item is selected.</param>
protected override void DrawEntry(ContentEntry<Gear> entry, Vector2 position,
bool isSelected)
{
// check the parameter
if ((entry == null) || (entry.Content == null))
{
throw new ArgumentNullException("entry");
}
SpriteBatch spriteBatch = ScreenManager.SpriteBatch;
Vector2 drawPosition = position;
// draw the icon
spriteBatch.Draw(entry.Content.IconTexture, drawPosition + iconOffset,
Color.White);
// draw the name
Color color = isSelected ? Fonts.HighlightColor : Fonts.DisplayColor;
drawPosition.Y += listLineSpacing / 4;
drawPosition.X += nameColumnInterval;
spriteBatch.DrawString(Fonts.GearInfoFont, entry.Content.Name,
drawPosition, color);
// draw the power
drawPosition.X += powerColumnInterval;
string powerText = entry.Content.GetPowerText();
Vector2 powerTextSize = Fonts.GearInfoFont.MeasureString(powerText);
Vector2 powerPosition = drawPosition;
powerPosition.Y -= (float)Math.Ceiling((powerTextSize.Y - 30f) / 2);
spriteBatch.DrawString(Fonts.GearInfoFont, powerText,
powerPosition, color);
// draw the quantity
drawPosition.X += quantityColumnInterval;
if (isSelected)
{
Vector2 quantityPosition = drawPosition;
// draw the left selection arrow
quantityPosition.X -= leftQuantityArrow.Width;
spriteBatch.Draw(leftQuantityArrow,
new Vector2(quantityPosition.X, quantityPosition.Y - 4),
Color.White);
quantityPosition.X += leftQuantityArrow.Width;
// draw the selected quantity ratio
string quantityText = selectedQuantity.ToString() + "/" +
entry.Count.ToString();
spriteBatch.DrawString(Fonts.GearInfoFont, quantityText,
quantityPosition, color);
quantityPosition.X +=
Fonts.GearInfoFont.MeasureString(quantityText).X;
// draw the right selection arrow
spriteBatch.Draw(rightQuantityArrow,
new Vector2(quantityPosition.X, quantityPosition.Y - 4),
Color.White);
quantityPosition.X += rightQuantityArrow.Width;
// draw the purchase button
selectButtonText = "Sell";
}
else
{
spriteBatch.DrawString(Fonts.GearInfoFont, entry.Count.ToString(),
drawPosition, color);
}
// draw the price
drawPosition.X += priceColumnInterval;
string priceText = String.Empty;
if (isSelected)
{
int totalPrice = selectedQuantity *
(int)Math.Ceiling(entry.Content.GoldValue * store.SellMultiplier);
priceText = totalPrice.ToString();
}
else
{
priceText = ((int)Math.Ceiling(entry.Content.GoldValue *
store.SellMultiplier)).ToString();
}
spriteBatch.DrawString(Fonts.GearInfoFont, priceText,
drawPosition, color);
}
/// <summary>
/// Draw the description of the selected item.
/// </summary>
protected override void DrawSelectedDescription(ContentEntry<Gear> entry)
{
// check the parameter
if ((entry == null) || (entry.Content == null))
{
throw new ArgumentNullException("entry");
}
SpriteBatch spriteBatch = ScreenManager.SpriteBatch;
Vector2 position = descriptionTextPosition;
// draw the description
// -- it's up to the content owner to fit the description
string text = entry.Content.Description;
if (!String.IsNullOrEmpty(text))
{
spriteBatch.DrawString(Fonts.DescriptionFont, text, position,
Fonts.DescriptionColor);
position.Y += Fonts.DescriptionFont.LineSpacing;
}
// draw the modifiers
Equipment equipment = entry.Content as Equipment;
if (equipment != null)
{
text = equipment.OwnerBuffStatistics.GetModifierString();
if (!String.IsNullOrEmpty(text))
{
spriteBatch.DrawString(Fonts.DescriptionFont, text, position,
Fonts.DescriptionColor);
position.Y += Fonts.DescriptionFont.LineSpacing;
}
}
// draw the restrictions
text = entry.Content.GetRestrictionsText();
if (!String.IsNullOrEmpty(text))
{
spriteBatch.DrawString(Fonts.DescriptionFont, text, position,
Fonts.DescriptionColor);
position.Y += Fonts.DescriptionFont.LineSpacing;
}
}
/// <summary>
/// Draw the column headers above the list.
/// </summary>
protected override void DrawColumnHeaders()
{
SpriteBatch spriteBatch = ScreenManager.SpriteBatch;
Vector2 position = listEntryStartPosition;
position.X += nameColumnInterval;
if (!String.IsNullOrEmpty(nameColumnText))
{
spriteBatch.DrawString(Fonts.CaptionFont, nameColumnText, position,
Fonts.CaptionColor);
}
position.X += powerColumnInterval;
if (!String.IsNullOrEmpty(powerColumnText))
{
spriteBatch.DrawString(Fonts.CaptionFont, powerColumnText, position,
Fonts.CaptionColor);
}
position.X += quantityColumnInterval;
if (!String.IsNullOrEmpty(quantityColumnText))
{
spriteBatch.DrawString(Fonts.CaptionFont, quantityColumnText, position,
Fonts.CaptionColor);
}
position.X += priceColumnInterval;
if (!String.IsNullOrEmpty(priceColumnText))
{
spriteBatch.DrawString(Fonts.CaptionFont, priceColumnText, position,
Fonts.CaptionColor);
}
}
#endregion
}
}
| {
"content_hash": "5576b5c657aacc80d8400ace4ea535e0",
"timestamp": "",
"source": "github",
"line_count": 435,
"max_line_length": 87,
"avg_line_length": 31.011494252873565,
"alnum_prop": 0.5383988139362491,
"repo_name": "DDReaper/XNAGameStudio",
"id": "5fb482a2708c90bca08ea51d6ce8a4d59b52b031",
"size": "13839",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Samples/RolePlayingGame_4_0_Win_Xbox/RolePlayingGame_4_0_Win_Xbox/RolePlayingGame/GameScreens/StoreSellScreen.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "77207"
}
],
"symlink_target": ""
} |
title: Getting Started with Kong Studio
toc: false
---
## Introducing Kong Studio {{page.kong_version}}
Design, edit, and debug API specification files with Kong Studio! Features in Kong Studio {{page.kong_version}} include the ability to connect and sync files to Kong Enterprise and the Kong Developer Portal, debug and test with Insomnia, sync to your git repositories and more. Check out the full [Release Notes](/studio/{{page.kong_version}}/release-notes) for details.
<div class="docs-grid">
<div class="docs-grid-block">
<h3>
<img src="/assets/images/icons/documentation/icn-doc-reference.svg" />
<a href="/studio/{{page.kong_version}}/release-notes">Release Notes</a>
</h3>
<p></p>
<a href="/studio/{{page.kong_version}}/release-notes">
Read the Release Notes for Kong Studio {{page.kong_version}} →
</a>
</div>
<div class="docs-grid-block">
<h3>
<img src="/assets/images/icons/documentation/icn-quickstart.svg" />
<a href="/studio/{{page.kong_version}}/download-install">Download & Install</a>
</h3>
<p></p>
<a href="/studio/{{page.kong_version}}/download-install">
Download and Install Kong Studio →
</a>
</div>
<div class="docs-grid-block">
<h3>
<img src="/assets/images/icons/documentation/icn-doc-reference.svg" />
<a href="/studio/{{page.kong_version}}/editing-specs">Editing Spec Files</a>
</h3>
<p></p>
<a href="/studio/{{page.kong_version}}/editing-specs">
Edit OpenAPI specifications with Kong Studio →
</a>
</div>
<div class="docs-grid-block">
<h3>
<img src="/assets/images/icons/documentation/icn-doc-reference.svg" />
<a href="/studio/{{page.kong_version}}/live-preview">Enable Live Preview</a>
</h3>
<p></p>
<a href="/studio/{{page.kong_version}}/live-preview">
Enable Live Preview and see output as you edit →
</a>
</div>
<div class="docs-grid-block">
<h3>
<img src="/assets/images/icons/documentation/icn-doc-reference.svg" />
<a href="/studio/{{page.kong_version}}/graphql">OpenAPI GraphQL</a>
</h3>
<p></p>
<a href="/studio/{{page.kong_version}}/graphql">
Use GraphQL with Kong Studio and Insomnia →
</a>
</div>
<div class="docs-grid-block">
<h3>
<img src="/assets/images/icons/documentation/icn-doc-reference.svg" />
<a href="/studio/{{page.kong_version}}/debugging-with-insomnia">Debugging with Insomnia</a>
</h3>
<p></p>
<a href="/studio/{{page.kong_version}}/debugging-with-insomnia">
Debug and Test Specs with Insomnia →
</a>
</div>
<div class="docs-grid-block">
<h3>
<img src="/assets/images/icons/documentation/icn-doc-reference.svg" />
<a href="/studio/{{page.kong_version}}/git-sync">Git Sync with Studio</a>
</h3>
<p></p>
<a href="/studio/{{page.kong_version}}/git-sync">
Sync Kong Studio with your Git Repositories →
</a>
</div>
<div class="docs-grid-block">
<h3>
<img src="/assets/images/icons/documentation/icn-doc-reference.svg" />
<a href="/studio/{{page.kong_version}}/deploy-to-dev-portal">Deploy to the Dev Portal</a>
</h3>
<p></p>
<a href="/studio/{{page.kong_version}}/deploy-to-dev-portal">
Connect to Kong Enterprise and Deploy Specs to the Kong Developer Portal →
</a>
</div>
</div>
| {
"content_hash": "70586a9288ac45a4bb4426f1b87823e0",
"timestamp": "",
"source": "github",
"line_count": 100,
"max_line_length": 370,
"avg_line_length": 34.71,
"alnum_prop": 0.6260443676174013,
"repo_name": "Mashape/getkong.org",
"id": "15249074a4a250e82f288371114f1c136f45391e",
"size": "3475",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "app/studio/old/1.2.x/overview.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "57774"
},
{
"name": "HTML",
"bytes": "600842"
},
{
"name": "JavaScript",
"bytes": "12051"
},
{
"name": "Ruby",
"bytes": "7640"
}
],
"symlink_target": ""
} |
package gunlee.scouter.demo.commondemo.interfaces.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
/**
* @author Gun Lee (gunlee01@gmail.com) on 2018. 7. 1.
*/
@Service
public class AsyncSimulateDelayServiceStep2 {
@Autowired
UserService userService;
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void modifyUserNameTx(String userId) {
String userName = "nameZ" + String.valueOf(ThreadLocalRandom.current().nextInt(201, 300));
userService.modifyUserName(userId, userName);
sleepThousands();
userService.findUserById(userId);
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void modifyUserNameTxShort(String userId) {
String userName = "nameZ" + String.valueOf(ThreadLocalRandom.current().nextInt(201, 300));
userService.modifyUserName(userId, userName);
sleepShort();
userService.findUserById(userId);
}
public void sleepShort() {
sleep(ThreadLocalRandom.current().nextInt(210, 1200));
}
public void sleepThousands() {
sleep(ThreadLocalRandom.current().nextInt(1800, 4200));
}
private void sleep(int millis) {
try {
TimeUnit.MILLISECONDS.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| {
"content_hash": "5a83c69f9136deb3d6c70597397bf4a5",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 98,
"avg_line_length": 31.26923076923077,
"alnum_prop": 0.7084870848708487,
"repo_name": "gunlee01/scouter-demo-web",
"id": "19920eaec2d14b77a09a28deef92c8d39d3c3508",
"size": "2297",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/gunlee/scouter/demo/commondemo/interfaces/service/AsyncSimulateDelayServiceStep2.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Groovy",
"bytes": "2014"
},
{
"name": "HTML",
"bytes": "7917"
},
{
"name": "Java",
"bytes": "64847"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta name="generator" content="Asciidoctor 2.0.10"/>
<title>git-pack-redundant(1)</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:300,300italic,400,400italic,600,600italic%7CNoto+Serif:400,400italic,700,700italic%7CDroid+Sans+Mono:400,700"/>
<style>
/* Asciidoctor default stylesheet | MIT License | https://asciidoctor.org */
/* Uncomment @import statement to use as custom stylesheet */
/*@import "https://fonts.googleapis.com/css?family=Open+Sans:300,300italic,400,400italic,600,600italic%7CNoto+Serif:400,400italic,700,700italic%7CDroid+Sans+Mono:400,700";*/
article,aside,details,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}
audio,video{display:inline-block}
audio:not([controls]){display:none;height:0}
html{font-family:sans-serif;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%}
a{background:none}
a:focus{outline:thin dotted}
a:active,a:hover{outline:0}
h1{font-size:2em;margin:.67em 0}
abbr[title]{border-bottom:1px dotted}
b,strong{font-weight:bold}
dfn{font-style:italic}
hr{-moz-box-sizing:content-box;box-sizing:content-box;height:0}
mark{background:#ff0;color:#000}
code,kbd,pre,samp{font-family:monospace;font-size:1em}
pre{white-space:pre-wrap}
q{quotes:"\201C" "\201D" "\2018" "\2019"}
small{font-size:80%}
sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}
sup{top:-.5em}
sub{bottom:-.25em}
img{border:0}
svg:not(:root){overflow:hidden}
figure{margin:0}
fieldset{border:1px solid silver;margin:0 2px;padding:.35em .625em .75em}
legend{border:0;padding:0}
button,input,select,textarea{font-family:inherit;font-size:100%;margin:0}
button,input{line-height:normal}
button,select{text-transform:none}
button,html input[type="button"],input[type="reset"],input[type="submit"]{-webkit-appearance:button;cursor:pointer}
button[disabled],html input[disabled]{cursor:default}
input[type="checkbox"],input[type="radio"]{box-sizing:border-box;padding:0}
button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0}
textarea{overflow:auto;vertical-align:top}
table{border-collapse:collapse;border-spacing:0}
*,*::before,*::after{-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box}
html,body{font-size:100%}
body{background:#fff;color:rgba(0,0,0,.8);padding:0;margin:0;font-family:"Noto Serif","DejaVu Serif",serif;font-weight:400;font-style:normal;line-height:1;position:relative;cursor:auto;tab-size:4;-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased}
a:hover{cursor:pointer}
img,object,embed{max-width:100%;height:auto}
object,embed{height:100%}
img{-ms-interpolation-mode:bicubic}
.left{float:left!important}
.right{float:right!important}
.text-left{text-align:left!important}
.text-right{text-align:right!important}
.text-center{text-align:center!important}
.text-justify{text-align:justify!important}
.hide{display:none}
img,object,svg{display:inline-block;vertical-align:middle}
textarea{height:auto;min-height:50px}
select{width:100%}
.center{margin-left:auto;margin-right:auto}
.stretch{width:100%}
.subheader,.admonitionblock td.content>.title,.audioblock>.title,.exampleblock>.title,.imageblock>.title,.listingblock>.title,.literalblock>.title,.stemblock>.title,.openblock>.title,.paragraph>.title,.quoteblock>.title,table.tableblock>.title,.verseblock>.title,.videoblock>.title,.dlist>.title,.olist>.title,.ulist>.title,.qlist>.title,.hdlist>.title{line-height:1.45;color:#7a2518;font-weight:400;margin-top:0;margin-bottom:.25em}
div,dl,dt,dd,ul,ol,li,h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6,pre,form,p,blockquote,th,td{margin:0;padding:0;direction:ltr}
a{color:#2156a5;text-decoration:underline;line-height:inherit}
a:hover,a:focus{color:#1d4b8f}
a img{border:0}
p{font-family:inherit;font-weight:400;font-size:1em;line-height:1.6;margin-bottom:1.25em;text-rendering:optimizeLegibility}
p aside{font-size:.875em;line-height:1.35;font-style:italic}
h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{font-family:"Open Sans","DejaVu Sans",sans-serif;font-weight:300;font-style:normal;color:#ba3925;text-rendering:optimizeLegibility;margin-top:1em;margin-bottom:.5em;line-height:1.0125em}
h1 small,h2 small,h3 small,#toctitle small,.sidebarblock>.content>.title small,h4 small,h5 small,h6 small{font-size:60%;color:#e99b8f;line-height:0}
h1{font-size:2.125em}
h2{font-size:1.6875em}
h3,#toctitle,.sidebarblock>.content>.title{font-size:1.375em}
h4,h5{font-size:1.125em}
h6{font-size:1em}
hr{border:solid #dddddf;border-width:1px 0 0;clear:both;margin:1.25em 0 1.1875em;height:0}
em,i{font-style:italic;line-height:inherit}
strong,b{font-weight:bold;line-height:inherit}
small{font-size:60%;line-height:inherit}
code{font-family:"Droid Sans Mono","DejaVu Sans Mono",monospace;font-weight:400;color:rgba(0,0,0,.9)}
ul,ol,dl{font-size:1em;line-height:1.6;margin-bottom:1.25em;list-style-position:outside;font-family:inherit}
ul,ol{margin-left:1.5em}
ul li ul,ul li ol{margin-left:1.25em;margin-bottom:0;font-size:1em}
ul.square li ul,ul.circle li ul,ul.disc li ul{list-style:inherit}
ul.square{list-style-type:square}
ul.circle{list-style-type:circle}
ul.disc{list-style-type:disc}
ol li ul,ol li ol{margin-left:1.25em;margin-bottom:0}
dl dt{margin-bottom:.3125em;font-weight:bold}
dl dd{margin-bottom:1.25em}
abbr,acronym{text-transform:uppercase;font-size:90%;color:rgba(0,0,0,.8);border-bottom:1px dotted #ddd;cursor:help}
abbr{text-transform:none}
blockquote{margin:0 0 1.25em;padding:.5625em 1.25em 0 1.1875em;border-left:1px solid #ddd}
blockquote cite{display:block;font-size:.9375em;color:rgba(0,0,0,.6)}
blockquote cite::before{content:"\2014 \0020"}
blockquote cite a,blockquote cite a:visited{color:rgba(0,0,0,.6)}
blockquote,blockquote p{line-height:1.6;color:rgba(0,0,0,.85)}
@media screen and (min-width:768px){h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{line-height:1.2}
h1{font-size:2.75em}
h2{font-size:2.3125em}
h3,#toctitle,.sidebarblock>.content>.title{font-size:1.6875em}
h4{font-size:1.4375em}}
table{background:#fff;margin-bottom:1.25em;border:solid 1px #dedede}
table thead,table tfoot{background:#f7f8f7}
table thead tr th,table thead tr td,table tfoot tr th,table tfoot tr td{padding:.5em .625em .625em;font-size:inherit;color:rgba(0,0,0,.8);text-align:left}
table tr th,table tr td{padding:.5625em .625em;font-size:inherit;color:rgba(0,0,0,.8)}
table tr.even,table tr.alt{background:#f8f8f7}
table thead tr th,table tfoot tr th,table tbody tr td,table tr td,table tfoot tr td{display:table-cell;line-height:1.6}
h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{line-height:1.2;word-spacing:-.05em}
h1 strong,h2 strong,h3 strong,#toctitle strong,.sidebarblock>.content>.title strong,h4 strong,h5 strong,h6 strong{font-weight:400}
.clearfix::before,.clearfix::after,.float-group::before,.float-group::after{content:" ";display:table}
.clearfix::after,.float-group::after{clear:both}
:not(pre):not([class^=L])>code{font-size:.9375em;font-style:normal!important;letter-spacing:0;padding:.1em .5ex;word-spacing:-.15em;background:#f7f7f8;-webkit-border-radius:4px;border-radius:4px;line-height:1.45;text-rendering:optimizeSpeed;word-wrap:break-word}
:not(pre)>code.nobreak{word-wrap:normal}
:not(pre)>code.nowrap{white-space:nowrap}
pre{color:rgba(0,0,0,.9);font-family:"Droid Sans Mono","DejaVu Sans Mono",monospace;line-height:1.45;text-rendering:optimizeSpeed}
pre code,pre pre{color:inherit;font-size:inherit;line-height:inherit}
pre>code{display:block}
pre.nowrap,pre.nowrap pre{white-space:pre;word-wrap:normal}
em em{font-style:normal}
strong strong{font-weight:400}
.keyseq{color:rgba(51,51,51,.8)}
kbd{font-family:"Droid Sans Mono","DejaVu Sans Mono",monospace;display:inline-block;color:rgba(0,0,0,.8);font-size:.65em;line-height:1.45;background:#f7f7f7;border:1px solid #ccc;-webkit-border-radius:3px;border-radius:3px;-webkit-box-shadow:0 1px 0 rgba(0,0,0,.2),0 0 0 .1em white inset;box-shadow:0 1px 0 rgba(0,0,0,.2),0 0 0 .1em #fff inset;margin:0 .15em;padding:.2em .5em;vertical-align:middle;position:relative;top:-.1em;white-space:nowrap}
.keyseq kbd:first-child{margin-left:0}
.keyseq kbd:last-child{margin-right:0}
.menuseq,.menuref{color:#000}
.menuseq b:not(.caret),.menuref{font-weight:inherit}
.menuseq{word-spacing:-.02em}
.menuseq b.caret{font-size:1.25em;line-height:.8}
.menuseq i.caret{font-weight:bold;text-align:center;width:.45em}
b.button::before,b.button::after{position:relative;top:-1px;font-weight:400}
b.button::before{content:"[";padding:0 3px 0 2px}
b.button::after{content:"]";padding:0 2px 0 3px}
p a>code:hover{color:rgba(0,0,0,.9)}
#header,#content,#footnotes,#footer{width:100%;margin-left:auto;margin-right:auto;margin-top:0;margin-bottom:0;max-width:62.5em;*zoom:1;position:relative;padding-left:.9375em;padding-right:.9375em}
#header::before,#header::after,#content::before,#content::after,#footnotes::before,#footnotes::after,#footer::before,#footer::after{content:" ";display:table}
#header::after,#content::after,#footnotes::after,#footer::after{clear:both}
#content{margin-top:1.25em}
#content::before{content:none}
#header>h1:first-child{color:rgba(0,0,0,.85);margin-top:2.25rem;margin-bottom:0}
#header>h1:first-child+#toc{margin-top:8px;border-top:1px solid #dddddf}
#header>h1:only-child,body.toc2 #header>h1:nth-last-child(2){border-bottom:1px solid #dddddf;padding-bottom:8px}
#header .details{border-bottom:1px solid #dddddf;line-height:1.45;padding-top:.25em;padding-bottom:.25em;padding-left:.25em;color:rgba(0,0,0,.6);display:-ms-flexbox;display:-webkit-flex;display:flex;-ms-flex-flow:row wrap;-webkit-flex-flow:row wrap;flex-flow:row wrap}
#header .details span:first-child{margin-left:-.125em}
#header .details span.email a{color:rgba(0,0,0,.85)}
#header .details br{display:none}
#header .details br+span::before{content:"\00a0\2013\00a0"}
#header .details br+span.author::before{content:"\00a0\22c5\00a0";color:rgba(0,0,0,.85)}
#header .details br+span#revremark::before{content:"\00a0|\00a0"}
#header #revnumber{text-transform:capitalize}
#header #revnumber::after{content:"\00a0"}
#content>h1:first-child:not([class]){color:rgba(0,0,0,.85);border-bottom:1px solid #dddddf;padding-bottom:8px;margin-top:0;padding-top:1rem;margin-bottom:1.25rem}
#toc{border-bottom:1px solid #e7e7e9;padding-bottom:.5em}
#toc>ul{margin-left:.125em}
#toc ul.sectlevel0>li>a{font-style:italic}
#toc ul.sectlevel0 ul.sectlevel1{margin:.5em 0}
#toc ul{font-family:"Open Sans","DejaVu Sans",sans-serif;list-style-type:none}
#toc li{line-height:1.3334;margin-top:.3334em}
#toc a{text-decoration:none}
#toc a:active{text-decoration:underline}
#toctitle{color:#7a2518;font-size:1.2em}
@media screen and (min-width:768px){#toctitle{font-size:1.375em}
body.toc2{padding-left:15em;padding-right:0}
#toc.toc2{margin-top:0!important;background:#f8f8f7;position:fixed;width:15em;left:0;top:0;border-right:1px solid #e7e7e9;border-top-width:0!important;border-bottom-width:0!important;z-index:1000;padding:1.25em 1em;height:100%;overflow:auto}
#toc.toc2 #toctitle{margin-top:0;margin-bottom:.8rem;font-size:1.2em}
#toc.toc2>ul{font-size:.9em;margin-bottom:0}
#toc.toc2 ul ul{margin-left:0;padding-left:1em}
#toc.toc2 ul.sectlevel0 ul.sectlevel1{padding-left:0;margin-top:.5em;margin-bottom:.5em}
body.toc2.toc-right{padding-left:0;padding-right:15em}
body.toc2.toc-right #toc.toc2{border-right-width:0;border-left:1px solid #e7e7e9;left:auto;right:0}}
@media screen and (min-width:1280px){body.toc2{padding-left:20em;padding-right:0}
#toc.toc2{width:20em}
#toc.toc2 #toctitle{font-size:1.375em}
#toc.toc2>ul{font-size:.95em}
#toc.toc2 ul ul{padding-left:1.25em}
body.toc2.toc-right{padding-left:0;padding-right:20em}}
#content #toc{border-style:solid;border-width:1px;border-color:#e0e0dc;margin-bottom:1.25em;padding:1.25em;background:#f8f8f7;-webkit-border-radius:4px;border-radius:4px}
#content #toc>:first-child{margin-top:0}
#content #toc>:last-child{margin-bottom:0}
#footer{max-width:100%;background:rgba(0,0,0,.8);padding:1.25em}
#footer-text{color:rgba(255,255,255,.8);line-height:1.44}
#content{margin-bottom:.625em}
.sect1{padding-bottom:.625em}
@media screen and (min-width:768px){#content{margin-bottom:1.25em}
.sect1{padding-bottom:1.25em}}
.sect1:last-child{padding-bottom:0}
.sect1+.sect1{border-top:1px solid #e7e7e9}
#content h1>a.anchor,h2>a.anchor,h3>a.anchor,#toctitle>a.anchor,.sidebarblock>.content>.title>a.anchor,h4>a.anchor,h5>a.anchor,h6>a.anchor{position:absolute;z-index:1001;width:1.5ex;margin-left:-1.5ex;display:block;text-decoration:none!important;visibility:hidden;text-align:center;font-weight:400}
#content h1>a.anchor::before,h2>a.anchor::before,h3>a.anchor::before,#toctitle>a.anchor::before,.sidebarblock>.content>.title>a.anchor::before,h4>a.anchor::before,h5>a.anchor::before,h6>a.anchor::before{content:"\00A7";font-size:.85em;display:block;padding-top:.1em}
#content h1:hover>a.anchor,#content h1>a.anchor:hover,h2:hover>a.anchor,h2>a.anchor:hover,h3:hover>a.anchor,#toctitle:hover>a.anchor,.sidebarblock>.content>.title:hover>a.anchor,h3>a.anchor:hover,#toctitle>a.anchor:hover,.sidebarblock>.content>.title>a.anchor:hover,h4:hover>a.anchor,h4>a.anchor:hover,h5:hover>a.anchor,h5>a.anchor:hover,h6:hover>a.anchor,h6>a.anchor:hover{visibility:visible}
#content h1>a.link,h2>a.link,h3>a.link,#toctitle>a.link,.sidebarblock>.content>.title>a.link,h4>a.link,h5>a.link,h6>a.link{color:#ba3925;text-decoration:none}
#content h1>a.link:hover,h2>a.link:hover,h3>a.link:hover,#toctitle>a.link:hover,.sidebarblock>.content>.title>a.link:hover,h4>a.link:hover,h5>a.link:hover,h6>a.link:hover{color:#a53221}
details,.audioblock,.imageblock,.literalblock,.listingblock,.stemblock,.videoblock{margin-bottom:1.25em}
details>summary:first-of-type{cursor:pointer;display:list-item;outline:none;margin-bottom:.75em}
.admonitionblock td.content>.title,.audioblock>.title,.exampleblock>.title,.imageblock>.title,.listingblock>.title,.literalblock>.title,.stemblock>.title,.openblock>.title,.paragraph>.title,.quoteblock>.title,table.tableblock>.title,.verseblock>.title,.videoblock>.title,.dlist>.title,.olist>.title,.ulist>.title,.qlist>.title,.hdlist>.title{text-rendering:optimizeLegibility;text-align:left;font-family:"Noto Serif","DejaVu Serif",serif;font-size:1rem;font-style:italic}
table.tableblock.fit-content>caption.title{white-space:nowrap;width:0}
.paragraph.lead>p,#preamble>.sectionbody>[class="paragraph"]:first-of-type p{font-size:1.21875em;line-height:1.6;color:rgba(0,0,0,.85)}
table.tableblock #preamble>.sectionbody>[class="paragraph"]:first-of-type p{font-size:inherit}
.admonitionblock>table{border-collapse:separate;border:0;background:none;width:100%}
.admonitionblock>table td.icon{text-align:center;width:80px}
.admonitionblock>table td.icon img{max-width:none}
.admonitionblock>table td.icon .title{font-weight:bold;font-family:"Open Sans","DejaVu Sans",sans-serif;text-transform:uppercase}
.admonitionblock>table td.content{padding-left:1.125em;padding-right:1.25em;border-left:1px solid #dddddf;color:rgba(0,0,0,.6)}
.admonitionblock>table td.content>:last-child>:last-child{margin-bottom:0}
.exampleblock>.content{border-style:solid;border-width:1px;border-color:#e6e6e6;margin-bottom:1.25em;padding:1.25em;background:#fff;-webkit-border-radius:4px;border-radius:4px}
.exampleblock>.content>:first-child{margin-top:0}
.exampleblock>.content>:last-child{margin-bottom:0}
.sidebarblock{border-style:solid;border-width:1px;border-color:#dbdbd6;margin-bottom:1.25em;padding:1.25em;background:#f3f3f2;-webkit-border-radius:4px;border-radius:4px}
.sidebarblock>:first-child{margin-top:0}
.sidebarblock>:last-child{margin-bottom:0}
.sidebarblock>.content>.title{color:#7a2518;margin-top:0;text-align:center}
.exampleblock>.content>:last-child>:last-child,.exampleblock>.content .olist>ol>li:last-child>:last-child,.exampleblock>.content .ulist>ul>li:last-child>:last-child,.exampleblock>.content .qlist>ol>li:last-child>:last-child,.sidebarblock>.content>:last-child>:last-child,.sidebarblock>.content .olist>ol>li:last-child>:last-child,.sidebarblock>.content .ulist>ul>li:last-child>:last-child,.sidebarblock>.content .qlist>ol>li:last-child>:last-child{margin-bottom:0}
.literalblock pre,.listingblock>.content>pre{-webkit-border-radius:4px;border-radius:4px;word-wrap:break-word;overflow-x:auto;padding:1em;font-size:.8125em}
@media screen and (min-width:768px){.literalblock pre,.listingblock>.content>pre{font-size:.90625em}}
@media screen and (min-width:1280px){.literalblock pre,.listingblock>.content>pre{font-size:1em}}
.literalblock pre,.listingblock>.content>pre:not(.highlight),.listingblock>.content>pre[class="highlight"],.listingblock>.content>pre[class^="highlight "]{background:#f7f7f8}
.literalblock.output pre{color:#f7f7f8;background:rgba(0,0,0,.9)}
.listingblock>.content{position:relative}
.listingblock code[data-lang]::before{display:none;content:attr(data-lang);position:absolute;font-size:.75em;top:.425rem;right:.5rem;line-height:1;text-transform:uppercase;color:inherit;opacity:.5}
.listingblock:hover code[data-lang]::before{display:block}
.listingblock.terminal pre .command::before{content:attr(data-prompt);padding-right:.5em;color:inherit;opacity:.5}
.listingblock.terminal pre .command:not([data-prompt])::before{content:"$"}
.listingblock pre.highlightjs{padding:0}
.listingblock pre.highlightjs>code{padding:1em;-webkit-border-radius:4px;border-radius:4px}
.listingblock pre.prettyprint{border-width:0}
.prettyprint{background:#f7f7f8}
pre.prettyprint .linenums{line-height:1.45;margin-left:2em}
pre.prettyprint li{background:none;list-style-type:inherit;padding-left:0}
pre.prettyprint li code[data-lang]::before{opacity:1}
pre.prettyprint li:not(:first-child) code[data-lang]::before{display:none}
table.linenotable{border-collapse:separate;border:0;margin-bottom:0;background:none}
table.linenotable td[class]{color:inherit;vertical-align:top;padding:0;line-height:inherit;white-space:normal}
table.linenotable td.code{padding-left:.75em}
table.linenotable td.linenos{border-right:1px solid currentColor;opacity:.35;padding-right:.5em}
pre.pygments .lineno{border-right:1px solid currentColor;opacity:.35;display:inline-block;margin-right:.75em}
pre.pygments .lineno::before{content:"";margin-right:-.125em}
.quoteblock{margin:0 1em 1.25em 1.5em;display:table}
.quoteblock:not(.excerpt)>.title{margin-left:-1.5em;margin-bottom:.75em}
.quoteblock blockquote,.quoteblock p{color:rgba(0,0,0,.85);font-size:1.15rem;line-height:1.75;word-spacing:.1em;letter-spacing:0;font-style:italic;text-align:justify}
.quoteblock blockquote{margin:0;padding:0;border:0}
.quoteblock blockquote::before{content:"\201c";float:left;font-size:2.75em;font-weight:bold;line-height:.6em;margin-left:-.6em;color:#7a2518;text-shadow:0 1px 2px rgba(0,0,0,.1)}
.quoteblock blockquote>.paragraph:last-child p{margin-bottom:0}
.quoteblock .attribution{margin-top:.75em;margin-right:.5ex;text-align:right}
.verseblock{margin:0 1em 1.25em}
.verseblock pre{font-family:"Open Sans","DejaVu Sans",sans;font-size:1.15rem;color:rgba(0,0,0,.85);font-weight:300;text-rendering:optimizeLegibility}
.verseblock pre strong{font-weight:400}
.verseblock .attribution{margin-top:1.25rem;margin-left:.5ex}
.quoteblock .attribution,.verseblock .attribution{font-size:.9375em;line-height:1.45;font-style:italic}
.quoteblock .attribution br,.verseblock .attribution br{display:none}
.quoteblock .attribution cite,.verseblock .attribution cite{display:block;letter-spacing:-.025em;color:rgba(0,0,0,.6)}
.quoteblock.abstract blockquote::before,.quoteblock.excerpt blockquote::before,.quoteblock .quoteblock blockquote::before{display:none}
.quoteblock.abstract blockquote,.quoteblock.abstract p,.quoteblock.excerpt blockquote,.quoteblock.excerpt p,.quoteblock .quoteblock blockquote,.quoteblock .quoteblock p{line-height:1.6;word-spacing:0}
.quoteblock.abstract{margin:0 1em 1.25em;display:block}
.quoteblock.abstract>.title{margin:0 0 .375em;font-size:1.15em;text-align:center}
.quoteblock.excerpt>blockquote,.quoteblock .quoteblock{padding:0 0 .25em 1em;border-left:.25em solid #dddddf}
.quoteblock.excerpt,.quoteblock .quoteblock{margin-left:0}
.quoteblock.excerpt blockquote,.quoteblock.excerpt p,.quoteblock .quoteblock blockquote,.quoteblock .quoteblock p{color:inherit;font-size:1.0625rem}
.quoteblock.excerpt .attribution,.quoteblock .quoteblock .attribution{color:inherit;text-align:left;margin-right:0}
table.tableblock{max-width:100%;border-collapse:separate}
p.tableblock:last-child{margin-bottom:0}
td.tableblock>.content>:last-child{margin-bottom:-1.25em}
td.tableblock>.content>:last-child.sidebarblock{margin-bottom:0}
table.tableblock,th.tableblock,td.tableblock{border:0 solid #dedede}
table.grid-all>thead>tr>.tableblock,table.grid-all>tbody>tr>.tableblock{border-width:0 1px 1px 0}
table.grid-all>tfoot>tr>.tableblock{border-width:1px 1px 0 0}
table.grid-cols>*>tr>.tableblock{border-width:0 1px 0 0}
table.grid-rows>thead>tr>.tableblock,table.grid-rows>tbody>tr>.tableblock{border-width:0 0 1px}
table.grid-rows>tfoot>tr>.tableblock{border-width:1px 0 0}
table.grid-all>*>tr>.tableblock:last-child,table.grid-cols>*>tr>.tableblock:last-child{border-right-width:0}
table.grid-all>tbody>tr:last-child>.tableblock,table.grid-all>thead:last-child>tr>.tableblock,table.grid-rows>tbody>tr:last-child>.tableblock,table.grid-rows>thead:last-child>tr>.tableblock{border-bottom-width:0}
table.frame-all{border-width:1px}
table.frame-sides{border-width:0 1px}
table.frame-topbot,table.frame-ends{border-width:1px 0}
table.stripes-all tr,table.stripes-odd tr:nth-of-type(odd),table.stripes-even tr:nth-of-type(even),table.stripes-hover tr:hover{background:#f8f8f7}
th.halign-left,td.halign-left{text-align:left}
th.halign-right,td.halign-right{text-align:right}
th.halign-center,td.halign-center{text-align:center}
th.valign-top,td.valign-top{vertical-align:top}
th.valign-bottom,td.valign-bottom{vertical-align:bottom}
th.valign-middle,td.valign-middle{vertical-align:middle}
table thead th,table tfoot th{font-weight:bold}
tbody tr th{display:table-cell;line-height:1.6;background:#f7f8f7}
tbody tr th,tbody tr th p,tfoot tr th,tfoot tr th p{color:rgba(0,0,0,.8);font-weight:bold}
p.tableblock>code:only-child{background:none;padding:0}
p.tableblock{font-size:1em}
ol{margin-left:1.75em}
ul li ol{margin-left:1.5em}
dl dd{margin-left:1.125em}
dl dd:last-child,dl dd:last-child>:last-child{margin-bottom:0}
ol>li p,ul>li p,ul dd,ol dd,.olist .olist,.ulist .ulist,.ulist .olist,.olist .ulist{margin-bottom:.625em}
ul.checklist,ul.none,ol.none,ul.no-bullet,ol.no-bullet,ol.unnumbered,ul.unstyled,ol.unstyled{list-style-type:none}
ul.no-bullet,ol.no-bullet,ol.unnumbered{margin-left:.625em}
ul.unstyled,ol.unstyled{margin-left:0}
ul.checklist{margin-left:.625em}
ul.checklist li>p:first-child>.fa-square-o:first-child,ul.checklist li>p:first-child>.fa-check-square-o:first-child{width:1.25em;font-size:.8em;position:relative;bottom:.125em}
ul.checklist li>p:first-child>input[type="checkbox"]:first-child{margin-right:.25em}
ul.inline{display:-ms-flexbox;display:-webkit-box;display:flex;-ms-flex-flow:row wrap;-webkit-flex-flow:row wrap;flex-flow:row wrap;list-style:none;margin:0 0 .625em -1.25em}
ul.inline>li{margin-left:1.25em}
.unstyled dl dt{font-weight:400;font-style:normal}
ol.arabic{list-style-type:decimal}
ol.decimal{list-style-type:decimal-leading-zero}
ol.loweralpha{list-style-type:lower-alpha}
ol.upperalpha{list-style-type:upper-alpha}
ol.lowerroman{list-style-type:lower-roman}
ol.upperroman{list-style-type:upper-roman}
ol.lowergreek{list-style-type:lower-greek}
.hdlist>table,.colist>table{border:0;background:none}
.hdlist>table>tbody>tr,.colist>table>tbody>tr{background:none}
td.hdlist1,td.hdlist2{vertical-align:top;padding:0 .625em}
td.hdlist1{font-weight:bold;padding-bottom:1.25em}
.literalblock+.colist,.listingblock+.colist{margin-top:-.5em}
.colist td:not([class]):first-child{padding:.4em .75em 0;line-height:1;vertical-align:top}
.colist td:not([class]):first-child img{max-width:none}
.colist td:not([class]):last-child{padding:.25em 0}
.thumb,.th{line-height:0;display:inline-block;border:solid 4px #fff;-webkit-box-shadow:0 0 0 1px #ddd;box-shadow:0 0 0 1px #ddd}
.imageblock.left{margin:.25em .625em 1.25em 0}
.imageblock.right{margin:.25em 0 1.25em .625em}
.imageblock>.title{margin-bottom:0}
.imageblock.thumb,.imageblock.th{border-width:6px}
.imageblock.thumb>.title,.imageblock.th>.title{padding:0 .125em}
.image.left,.image.right{margin-top:.25em;margin-bottom:.25em;display:inline-block;line-height:0}
.image.left{margin-right:.625em}
.image.right{margin-left:.625em}
a.image{text-decoration:none;display:inline-block}
a.image object{pointer-events:none}
sup.footnote,sup.footnoteref{font-size:.875em;position:static;vertical-align:super}
sup.footnote a,sup.footnoteref a{text-decoration:none}
sup.footnote a:active,sup.footnoteref a:active{text-decoration:underline}
#footnotes{padding-top:.75em;padding-bottom:.75em;margin-bottom:.625em}
#footnotes hr{width:20%;min-width:6.25em;margin:-.25em 0 .75em;border-width:1px 0 0}
#footnotes .footnote{padding:0 .375em 0 .225em;line-height:1.3334;font-size:.875em;margin-left:1.2em;margin-bottom:.2em}
#footnotes .footnote a:first-of-type{font-weight:bold;text-decoration:none;margin-left:-1.05em}
#footnotes .footnote:last-of-type{margin-bottom:0}
#content #footnotes{margin-top:-.625em;margin-bottom:0;padding:.75em 0}
.gist .file-data>table{border:0;background:#fff;width:100%;margin-bottom:0}
.gist .file-data>table td.line-data{width:99%}
div.unbreakable{page-break-inside:avoid}
.big{font-size:larger}
.small{font-size:smaller}
.underline{text-decoration:underline}
.overline{text-decoration:overline}
.line-through{text-decoration:line-through}
.aqua{color:#00bfbf}
.aqua-background{background:#00fafa}
.black{color:#000}
.black-background{background:#000}
.blue{color:#0000bf}
.blue-background{background:#0000fa}
.fuchsia{color:#bf00bf}
.fuchsia-background{background:#fa00fa}
.gray{color:#606060}
.gray-background{background:#7d7d7d}
.green{color:#006000}
.green-background{background:#007d00}
.lime{color:#00bf00}
.lime-background{background:#00fa00}
.maroon{color:#600000}
.maroon-background{background:#7d0000}
.navy{color:#000060}
.navy-background{background:#00007d}
.olive{color:#606000}
.olive-background{background:#7d7d00}
.purple{color:#600060}
.purple-background{background:#7d007d}
.red{color:#bf0000}
.red-background{background:#fa0000}
.silver{color:#909090}
.silver-background{background:#bcbcbc}
.teal{color:#006060}
.teal-background{background:#007d7d}
.white{color:#bfbfbf}
.white-background{background:#fafafa}
.yellow{color:#bfbf00}
.yellow-background{background:#fafa00}
span.icon>.fa{cursor:default}
a span.icon>.fa{cursor:inherit}
.admonitionblock td.icon [class^="fa icon-"]{font-size:2.5em;text-shadow:1px 1px 2px rgba(0,0,0,.5);cursor:default}
.admonitionblock td.icon .icon-note::before{content:"\f05a";color:#19407c}
.admonitionblock td.icon .icon-tip::before{content:"\f0eb";text-shadow:1px 1px 2px rgba(155,155,0,.8);color:#111}
.admonitionblock td.icon .icon-warning::before{content:"\f071";color:#bf6900}
.admonitionblock td.icon .icon-caution::before{content:"\f06d";color:#bf3400}
.admonitionblock td.icon .icon-important::before{content:"\f06a";color:#bf0000}
.conum[data-value]{display:inline-block;color:#fff!important;background:rgba(0,0,0,.8);-webkit-border-radius:100px;border-radius:100px;text-align:center;font-size:.75em;width:1.67em;height:1.67em;line-height:1.67em;font-family:"Open Sans","DejaVu Sans",sans-serif;font-style:normal;font-weight:bold}
.conum[data-value] *{color:#fff!important}
.conum[data-value]+b{display:none}
.conum[data-value]::after{content:attr(data-value)}
pre .conum[data-value]{position:relative;top:-.125em}
b.conum *{color:inherit!important}
.conum:not([data-value]):empty{display:none}
dt,th.tableblock,td.content,div.footnote{text-rendering:optimizeLegibility}
h1,h2,p,td.content,span.alt{letter-spacing:-.01em}
p strong,td.content strong,div.footnote strong{letter-spacing:-.005em}
p,blockquote,dt,td.content,span.alt{font-size:1.0625rem}
p{margin-bottom:1.25rem}
.sidebarblock p,.sidebarblock dt,.sidebarblock td.content,p.tableblock{font-size:1em}
.exampleblock>.content{background:#fffef7;border-color:#e0e0dc;-webkit-box-shadow:0 1px 4px #e0e0dc;box-shadow:0 1px 4px #e0e0dc}
.print-only{display:none!important}
@page{margin:1.25cm .75cm}
@media print{*{-webkit-box-shadow:none!important;box-shadow:none!important;text-shadow:none!important}
html{font-size:80%}
a{color:inherit!important;text-decoration:underline!important}
a.bare,a[href^="#"],a[href^="mailto:"]{text-decoration:none!important}
a[href^="http:"]:not(.bare)::after,a[href^="https:"]:not(.bare)::after{content:"(" attr(href) ")";display:inline-block;font-size:.875em;padding-left:.25em}
abbr[title]::after{content:" (" attr(title) ")"}
pre,blockquote,tr,img,object,svg{page-break-inside:avoid}
thead{display:table-header-group}
svg{max-width:100%}
p,blockquote,dt,td.content{font-size:1em;orphans:3;widows:3}
h2,h3,#toctitle,.sidebarblock>.content>.title{page-break-after:avoid}
#toc,.sidebarblock,.exampleblock>.content{background:none!important}
#toc{border-bottom:1px solid #dddddf!important;padding-bottom:0!important}
body.book #header{text-align:center}
body.book #header>h1:first-child{border:0!important;margin:2.5em 0 1em}
body.book #header .details{border:0!important;display:block;padding:0!important}
body.book #header .details span:first-child{margin-left:0!important}
body.book #header .details br{display:block}
body.book #header .details br+span::before{content:none!important}
body.book #toc{border:0!important;text-align:left!important;padding:0!important;margin:0!important}
body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-break-before:always}
.listingblock code[data-lang]::before{display:block}
#footer{padding:0 .9375em}
.hide-on-print{display:none!important}
.print-only{display:block!important}
.hide-for-print{display:none!important}
.show-for-print{display:inherit!important}}
@media print,amzn-kf8{#header>h1:first-child{margin-top:1.25rem}
.sect1{padding:0!important}
.sect1+.sect1{border:0}
#footer{background:none}
#footer-text{color:rgba(0,0,0,.6);font-size:.9em}}
@media amzn-kf8{#header,#content,#footnotes,#footer{padding:0}}
</style>
</head>
<body class="manpage">
<div id="header">
<h1>git-pack-redundant(1) Manual Page</h1>
<h2 id="_name">NAME</h2>
<div class="sectionbody">
<p>git-pack-redundant - Find redundant pack files</p>
</div>
</div>
<div id="content">
<div class="sect1">
<h2 id="_synopsis">SYNOPSIS</h2>
<div class="sectionbody">
<div class="verseblock">
<pre class="content"><em>git pack-redundant</em> [ --verbose ] [ --alt-odb ] < --all | .pack filename …​ ></pre>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_description">DESCRIPTION</h2>
<div class="sectionbody">
<div class="paragraph">
<p>This program computes which packs in your repository
are redundant. The output is suitable for piping to
<code>xargs rm</code> if you are in the root of the repository.</p>
</div>
<div class="paragraph">
<p><em>git pack-redundant</em> accepts a list of objects on standard input. Any objects
given will be ignored when checking which packs are required. This makes the
following command useful when wanting to remove packs which contain unreachable
objects.</p>
</div>
<div class="paragraph">
<p>git fsck --full --unreachable | cut -d ' ' -f3 | \
git pack-redundant --all | xargs rm</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_options">OPTIONS</h2>
<div class="sectionbody">
<div class="dlist">
<dl>
<dt class="hdlist1">--all</dt>
<dd>
<p>Processes all packs. Any filenames on the command line are ignored.</p>
</dd>
<dt class="hdlist1">--alt-odb</dt>
<dd>
<p>Don’t require objects present in packs from alternate object
directories to be present in local packs.</p>
</dd>
<dt class="hdlist1">--verbose</dt>
<dd>
<p>Outputs some statistics to stderr. Has a small performance penalty.</p>
</dd>
</dl>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_see_also">SEE ALSO</h2>
<div class="sectionbody">
<div class="paragraph">
<p><a href="git-pack-objects.html">git-pack-objects(1)</a>
<a href="git-repack.html">git-repack(1)</a>
<a href="git-prune-packed.html">git-prune-packed(1)</a></p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_git">GIT</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Part of the <a href="git.html">git(1)</a> suite</p>
</div>
</div>
</div>
</div>
<div id="footer">
<div id="footer-text">
Last updated 2020-06-01 18:38:37 UTC
</div>
</div>
</body>
</html> | {
"content_hash": "d6b29830879c6eeb9b1ab3700df120e0",
"timestamp": "",
"source": "github",
"line_count": 523,
"max_line_length": 471,
"avg_line_length": 62.88336520076482,
"alnum_prop": 0.7716492337630747,
"repo_name": "operepo/ope",
"id": "25edc30d30b56710bd098519d34100fa4f3d97e0",
"size": "32888",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client_tools/svc/rc/mingw32/share/doc/git-doc/git-pack-redundant.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "AL",
"bytes": "40379"
},
{
"name": "Awk",
"bytes": "22377"
},
{
"name": "Batchfile",
"bytes": "81725"
},
{
"name": "C",
"bytes": "655"
},
{
"name": "C++",
"bytes": "200907"
},
{
"name": "CMake",
"bytes": "8149"
},
{
"name": "CSS",
"bytes": "103747"
},
{
"name": "Dockerfile",
"bytes": "47152"
},
{
"name": "Emacs Lisp",
"bytes": "90665"
},
{
"name": "HTML",
"bytes": "37373861"
},
{
"name": "Java",
"bytes": "916104"
},
{
"name": "JavaScript",
"bytes": "9115492"
},
{
"name": "Makefile",
"bytes": "7428"
},
{
"name": "NewLisp",
"bytes": "111955"
},
{
"name": "PHP",
"bytes": "5053"
},
{
"name": "Perl",
"bytes": "45839826"
},
{
"name": "PostScript",
"bytes": "192210"
},
{
"name": "PowerShell",
"bytes": "2870"
},
{
"name": "Procfile",
"bytes": "114"
},
{
"name": "Prolog",
"bytes": "248055"
},
{
"name": "Python",
"bytes": "9037346"
},
{
"name": "QML",
"bytes": "125647"
},
{
"name": "QMake",
"bytes": "7566"
},
{
"name": "Raku",
"bytes": "7174577"
},
{
"name": "Roff",
"bytes": "25148"
},
{
"name": "Ruby",
"bytes": "162111"
},
{
"name": "Shell",
"bytes": "2574077"
},
{
"name": "Smalltalk",
"bytes": "77031"
},
{
"name": "SystemVerilog",
"bytes": "83394"
},
{
"name": "Tcl",
"bytes": "7061959"
},
{
"name": "Vim script",
"bytes": "27705984"
},
{
"name": "kvlang",
"bytes": "60630"
}
],
"symlink_target": ""
} |
[](https://travis-ci.org/abdennour/react-progressbar)
[](https://coveralls.io/github/abdennour/react-progressbar?branch=master)
[](https://npmjs.org/package/react-progressbar)
Basic progress bar in React.js.

Demo: http://abdennour.github.io/react-progressbar/
# Usage
Simply `require('react-progressbar')` and pass in `completed` property as a number between 0 and 100.
You may additionally pass in a CSS color string for the `color` property.
```js
var Progress = require('react-progressbar');
var component = React.createClass({
render: function() {
return (
<div>
<Progress completed={75} />
</div>
);
}
});
```
it was "babelified" also , thus, the following syntax is supported :
```js
import Progress from 'react-progressbar';
class OtherComponent extends React.Component {
render () {
return (
<div>
<Progress completed={75} />
</div>
)
}
}
```
# Donation
If this project help you reduce time to develop, you can give me a cup of coffee 🍵 :)
[](https://www.paypal.me/AbdennourT/1)
| {
"content_hash": "c1cfad2750fa51a595ed493d7e560ccc",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 178,
"avg_line_length": 25.64406779661017,
"alnum_prop": 0.7045604758757436,
"repo_name": "paramaggarwal/react-progressbar",
"id": "c054ffa2f8884fea4b9c0bea0847472fdd69596e",
"size": "1537",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "173"
},
{
"name": "JavaScript",
"bytes": "584681"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Extrovert3D - Smoke Tests</title>
<link rel="stylesheet" href="//code.jquery.com/qunit/qunit-1.17.1.css">
<script src="//code.jquery.com/qunit/qunit-1.17.1.js"></script>
<script src="../bower_components/threejs/build/three.min.js"></script>
<script src="../bower_components/physijs/physi.js"></script>
<script src="../dist/extrovert.js"></script>
<style>
img {
width: 20%;
margin-left: 4%;
}
#source, #target {
position: absolute;
left: 0; top: 0;
}
</style>
</head>
<body>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
<script>
var opts = {
target: { container: '#target' },
objects: [{ type: 'extrude', src: 'img', container: '#source' }]
bkcolor: 0xFFAA00
};
QUnit.test( "Verify WebGL support.", function( assert ) {
assert.ok( EXTROVERT.Utils.detect_webgl() );
});
QUnit.test( "Initialize the Extrovert library.", function( assert ) {
var ret = EXTROVERT.init( opts );
assert.ok( ret );
});
QUnit.test( "Verify canvas.", function( assert ) {
var elems = document.getElementsByTagName('canvas');
assert.strictEqual( elems.length, 1 );
});
</script>
<div style="position: relative;">
<div id="source">
<img src="img/ace_of_spades.png">
<img src="img/ace_of_hearts.png">
<img src="img/ace_of_diamonds.png">
<img src="img/ace_of_clubs.png">
</div>
<div id="target">
</div>
</div>
</body>
</html> | {
"content_hash": "be4c024c0331754800d909da6b59deef",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 73,
"avg_line_length": 26.135593220338983,
"alnum_prop": 0.5907911802853437,
"repo_name": "devlinjd/extrovert-priv.js",
"id": "111f8a5a53eeed1a06eac080a17414a0b1fbd11a",
"size": "1542",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "test/browser-tests.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "3377"
},
{
"name": "JavaScript",
"bytes": "126913"
}
],
"symlink_target": ""
} |
package org.pentaho.di.ui.trans.steps.ldifinput;
import java.text.SimpleDateFormat;
import java.util.Enumeration;
import java.util.HashSet;
import netscape.ldap.LDAPAttribute;
import netscape.ldap.util.LDIF;
import netscape.ldap.util.LDIFAttributeContent;
import netscape.ldap.util.LDIFContent;
import netscape.ldap.util.LDIFRecord;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Props;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.fileinput.FileInputList;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.TransPreviewFactory;
import org.pentaho.di.trans.step.BaseStepMeta;
import org.pentaho.di.trans.step.StepDialogInterface;
import org.pentaho.di.trans.steps.ldifinput.LDIFInputField;
import org.pentaho.di.trans.steps.ldifinput.LDIFInputMeta;
import org.pentaho.di.ui.core.dialog.EnterNumberDialog;
import org.pentaho.di.ui.core.dialog.EnterSelectionDialog;
import org.pentaho.di.ui.core.dialog.EnterTextDialog;
import org.pentaho.di.ui.core.dialog.ErrorDialog;
import org.pentaho.di.ui.core.dialog.PreviewRowsDialog;
import org.pentaho.di.ui.core.widget.ColumnInfo;
import org.pentaho.di.ui.core.widget.TableView;
import org.pentaho.di.ui.core.widget.TextVar;
import org.pentaho.di.ui.trans.dialog.TransPreviewProgressDialog;
import org.pentaho.di.ui.trans.step.BaseStepDialog;
public class LDIFInputDialog extends BaseStepDialog implements
StepDialogInterface {
private static Class<?> PKG = LDIFInputMeta.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$
private CTabFolder wTabFolder;
private FormData fdTabFolder;
private CTabItem wFileTab, wContentTab, wFieldsTab;
private Composite wFileComp, wContentComp, wFieldsComp;
private FormData fdFileComp, fdContentComp, fdFieldsComp,fdlAddResult;
private Label wlFilename,wlAddResult;
private Button wbbFilename; // Browse: add file or directory
private Button wbdFilename; // Delete
private Button wbeFilename; // Edit
private Button wbaFilename; // Add or change
private TextVar wFilename;
private FormData fdlFilename, fdbFilename, fdbdFilename, fdbeFilename,
fdbaFilename, fdFilename;
private Label wlFilenameList;
private TableView wFilenameList;
private FormData fdlFilenameList, fdFilenameList;
private Label wlFilemask;
private TextVar wFilemask;
private FormData fdlFilemask, fdFilemask;
private Label wlExcludeFilemask;
private TextVar wExcludeFilemask;
private FormData fdlExcludeFilemask, fdExcludeFilemask;
private Button wbShowFiles;
private FormData fdbShowFiles;
private Label wlInclFilename, wlInclDNField;
private Button wInclFilename,wInclContentType,wInclDN;
private FormData fdlInclFilename, fdInclFilename,fdInclContentType, fdInclDN, fdlInclDNField, fdlInclDN;
private Label wlInclFilenameField,wlInclContentType, wlInclDN;
private TextVar wInclFilenameField,wInclContentTypeField, wInclDNField;
private FormData fdlInclFilenameField, fdInclFilenameField,fdlInclContentType, fdInclDNField;
private Label wlInclRownum;
private Button wInclRownum;
private FormData fdlInclRownum, fdRownum;
private Label wlInclRownumField;
private TextVar wInclRownumField;
private FormData fdlInclRownumField, fdInclRownumField;
private Label wlLimit;
private Text wLimit;
private FormData fdlLimit, fdLimit;
private TableView wFields;
private FormData fdFields,fdAddFileResult,fdAddResult,fdInclContentTypeField,fdlInclContentTypeField;
private LDIFInputMeta input;
private Group wAddFileResult;
private Button wAddResult;
private Label wlMultiValuedSeparator,wlInclContentTypeField;
private TextVar wMultiValuedSeparator;
private FormData fdlMultiValuedSeparator, fdMultiValuedSeparator;
private FormData fdOriginFiles;
private Group wOriginFiles;
private Label wlFileField,wlFilenameField;
private CCombo wFilenameField;
private FormData fdlFileField,fdFileField;
private FormData fdFilenameField,fdlFilenameField;
private Button wFileField;
private boolean gotPreviousField=false;
private CTabItem wAdditionalFieldsTab;
private Composite wAdditionalFieldsComp;
private FormData fdAdditionalFieldsComp;
private Label wlShortFileFieldName;
private FormData fdlShortFileFieldName;
private TextVar wShortFileFieldName;
private FormData fdShortFileFieldName;
private Label wlPathFieldName;
private FormData fdlPathFieldName;
private TextVar wPathFieldName;
private FormData fdPathFieldName;
private Label wlIsHiddenName;
private FormData fdlIsHiddenName;
private TextVar wIsHiddenName;
private FormData fdIsHiddenName;
private Label wlLastModificationTimeName;
private FormData fdlLastModificationTimeName;
private TextVar wLastModificationTimeName;
private FormData fdLastModificationTimeName;
private Label wlUriName;
private FormData fdlUriName;
private TextVar wUriName;
private FormData fdUriName;
private Label wlRootUriName;
private FormData fdlRootUriName;
private TextVar wRootUriName;
private FormData fdRootUriName;
private Label wlExtensionFieldName;
private FormData fdlExtensionFieldName;
private TextVar wExtensionFieldName;
private FormData fdExtensionFieldName;
private Label wlSizeFieldName;
private FormData fdlSizeFieldName;
private TextVar wSizeFieldName;
private FormData fdSizeFieldName;
private int middle;
private int margin;
private ModifyListener lsMod;
public static final int dateLengths[] = new int[] { 23, 19, 14, 10, 10, 10,
10, 8, 8, 8, 8, 6, 6 };
public LDIFInputDialog(Shell parent, Object in, TransMeta transMeta,
String sname) {
super(parent, (BaseStepMeta) in, transMeta, sname);
input = (LDIFInputMeta) in;
}
public String open() {
Shell parent = getParent();
Display display = parent.getDisplay();
shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX
| SWT.MIN);
props.setLook(shell);
setShellImage(shell, input);
lsMod = new ModifyListener() {
public void modifyText(ModifyEvent e) {
input.setChanged();
}
};
changed = input.hasChanged();
FormLayout formLayout = new FormLayout();
formLayout.marginWidth = Const.FORM_MARGIN;
formLayout.marginHeight = Const.FORM_MARGIN;
shell.setLayout(formLayout);
shell.setText(BaseMessages.getString(PKG, "LDIFInputDialog.DialogTitle"));
middle = props.getMiddlePct();
margin = Const.MARGIN;
// Stepname line
wlStepname = new Label(shell, SWT.RIGHT);
wlStepname.setText(BaseMessages.getString(PKG, "System.Label.StepName"));
props.setLook(wlStepname);
fdlStepname = new FormData();
fdlStepname.left = new FormAttachment(0, 0);
fdlStepname.top = new FormAttachment(0, margin);
fdlStepname.right = new FormAttachment(middle, -margin);
wlStepname.setLayoutData(fdlStepname);
wStepname = new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wStepname.setText(stepname);
props.setLook(wStepname);
wStepname.addModifyListener(lsMod);
fdStepname = new FormData();
fdStepname.left = new FormAttachment(middle, 0);
fdStepname.top = new FormAttachment(0, margin);
fdStepname.right = new FormAttachment(100, 0);
wStepname.setLayoutData(fdStepname);
wTabFolder = new CTabFolder(shell, SWT.BORDER);
props.setLook(wTabFolder, Props.WIDGET_STYLE_TAB);
// ////////////////////////
// START OF FILE TAB ///
// ////////////////////////
wFileTab = new CTabItem(wTabFolder, SWT.NONE);
wFileTab.setText(BaseMessages.getString(PKG, "LDIFInputDialog.File.Tab"));
wFileComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wFileComp);
FormLayout fileLayout = new FormLayout();
fileLayout.marginWidth = 3;
fileLayout.marginHeight = 3;
wFileComp.setLayout(fileLayout);
// ///////////////////////////////
// START OF Origin files GROUP //
/////////////////////////////////
wOriginFiles = new Group(wFileComp, SWT.SHADOW_NONE);
props.setLook(wOriginFiles);
wOriginFiles.setText(BaseMessages.getString(PKG, "LDIFInputDialog.wOriginFiles.Label"));
FormLayout OriginFilesgroupLayout = new FormLayout();
OriginFilesgroupLayout.marginWidth = 10;
OriginFilesgroupLayout.marginHeight = 10;
wOriginFiles.setLayout(OriginFilesgroupLayout);
//Is Filename defined in a Field
wlFileField = new Label(wOriginFiles, SWT.RIGHT);
wlFileField.setText(BaseMessages.getString(PKG, "LDIFInputDialog.FileField.Label"));
props.setLook(wlFileField);
fdlFileField = new FormData();
fdlFileField.left = new FormAttachment(0, -margin);
fdlFileField.top = new FormAttachment(0, margin);
fdlFileField.right = new FormAttachment(middle, -2*margin);
wlFileField.setLayoutData(fdlFileField);
wFileField = new Button(wOriginFiles, SWT.CHECK);
props.setLook(wFileField);
wFileField.setToolTipText(BaseMessages.getString(PKG, "LDIFInputDialog.FileField.Tooltip"));
fdFileField = new FormData();
fdFileField.left = new FormAttachment(middle, -margin);
fdFileField.top = new FormAttachment(0, margin);
wFileField.setLayoutData(fdFileField);
SelectionAdapter lfilefield = new SelectionAdapter()
{
public void widgetSelected(SelectionEvent arg0)
{
ActiveFileField();
input.setChanged();
}
};
wFileField.addSelectionListener(lfilefield);
// Filename field
wlFilenameField=new Label(wOriginFiles, SWT.RIGHT);
wlFilenameField.setText(BaseMessages.getString(PKG, "LDIFInputDialog.wlFilenameField.Label"));
props.setLook(wlFilenameField);
fdlFilenameField=new FormData();
fdlFilenameField.left = new FormAttachment(0, -margin);
fdlFilenameField.top = new FormAttachment(wFileField, margin);
fdlFilenameField.right= new FormAttachment(middle, -2*margin);
wlFilenameField.setLayoutData(fdlFilenameField);
wFilenameField=new CCombo(wOriginFiles, SWT.BORDER | SWT.READ_ONLY);
wFilenameField.setEditable(true);
props.setLook(wFilenameField);
wFilenameField.addModifyListener(lsMod);
fdFilenameField=new FormData();
fdFilenameField.left = new FormAttachment(middle, -margin);
fdFilenameField.top = new FormAttachment(wFileField, margin);
fdFilenameField.right= new FormAttachment(100, -margin);
wFilenameField.setLayoutData(fdFilenameField);
wFilenameField.addFocusListener(new FocusListener()
{
public void focusLost(org.eclipse.swt.events.FocusEvent e)
{
}
public void focusGained(org.eclipse.swt.events.FocusEvent e)
{
Cursor busy = new Cursor(shell.getDisplay(), SWT.CURSOR_WAIT);
shell.setCursor(busy);
setFileField();
shell.setCursor(null);
busy.dispose();
}
}
);
fdOriginFiles = new FormData();
fdOriginFiles.left = new FormAttachment(0, margin);
fdOriginFiles.top = new FormAttachment(wFilenameList, margin);
fdOriginFiles.right = new FormAttachment(100, -margin);
wOriginFiles.setLayoutData(fdOriginFiles);
// ///////////////////////////////////////////////////////////
// / END OF Origin files GROUP
// ///////////////////////////////////////////////////////////
// Filename line
wlFilename = new Label(wFileComp, SWT.RIGHT);
wlFilename
.setText(BaseMessages.getString(PKG, "LDIFInputDialog.Filename.Label"));
props.setLook(wlFilename);
fdlFilename = new FormData();
fdlFilename.left = new FormAttachment(0, 0);
fdlFilename.top = new FormAttachment(wOriginFiles, margin);
fdlFilename.right = new FormAttachment(middle, -margin);
wlFilename.setLayoutData(fdlFilename);
wbbFilename = new Button(wFileComp, SWT.PUSH | SWT.CENTER);
props.setLook(wbbFilename);
wbbFilename.setText(BaseMessages.getString(PKG, "LDIFInputDialog.FilenameBrowse.Button"));
wbbFilename.setToolTipText(BaseMessages.getString(PKG, "System.Tooltip.BrowseForFileOrDirAndAdd"));
fdbFilename = new FormData();
fdbFilename.right = new FormAttachment(100, 0);
fdbFilename.top = new FormAttachment(wOriginFiles, margin);
wbbFilename.setLayoutData(fdbFilename);
wbaFilename = new Button(wFileComp, SWT.PUSH | SWT.CENTER);
props.setLook(wbaFilename);
wbaFilename.setText(BaseMessages.getString(PKG, "LDIFInputDialog.FilenameAdd.Button"));
wbaFilename.setToolTipText(BaseMessages.getString(PKG, "LDIFInputDialog.FilenameAdd.Tooltip"));
fdbaFilename = new FormData();
fdbaFilename.right = new FormAttachment(wbbFilename, -margin);
fdbaFilename.top = new FormAttachment(wOriginFiles, margin);
wbaFilename.setLayoutData(fdbaFilename);
wFilename = new TextVar(transMeta,wFileComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wFilename);
wFilename.addModifyListener(lsMod);
fdFilename = new FormData();
fdFilename.left = new FormAttachment(middle, 0);
fdFilename.right = new FormAttachment(wbaFilename, -margin);
fdFilename.top = new FormAttachment(wOriginFiles, margin);
wFilename.setLayoutData(fdFilename);
wlFilemask = new Label(wFileComp, SWT.RIGHT);
wlFilemask.setText(BaseMessages.getString(PKG, "LDIFInputDialog.RegExp.Label"));
props.setLook(wlFilemask);
fdlFilemask = new FormData();
fdlFilemask.left = new FormAttachment(0, 0);
fdlFilemask.top = new FormAttachment(wFilename, margin);
fdlFilemask.right = new FormAttachment(middle, -margin);
wlFilemask.setLayoutData(fdlFilemask);
wFilemask = new TextVar(transMeta,wFileComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wFilemask);
wFilemask.setToolTipText(BaseMessages.getString(PKG, "LDIFInputDialog.RegExp.Tooltip"));
wFilemask.addModifyListener(lsMod);
fdFilemask = new FormData();
fdFilemask.left = new FormAttachment(middle, 0);
fdFilemask.top = new FormAttachment(wFilename, margin);
fdFilemask.right = new FormAttachment(100, 0);
wFilemask.setLayoutData(fdFilemask);
wlExcludeFilemask = new Label(wFileComp, SWT.RIGHT);
wlExcludeFilemask.setText(BaseMessages.getString(PKG, "LDIFInputDialog.ExcludeFilemask.Label"));
props.setLook(wlExcludeFilemask);
fdlExcludeFilemask = new FormData();
fdlExcludeFilemask.left = new FormAttachment(0, 0);
fdlExcludeFilemask.top = new FormAttachment(wFilemask, margin);
fdlExcludeFilemask.right = new FormAttachment(middle, -margin);
wlExcludeFilemask.setLayoutData(fdlExcludeFilemask);
wExcludeFilemask = new TextVar(transMeta, wFileComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wExcludeFilemask);
wExcludeFilemask.addModifyListener(lsMod);
fdExcludeFilemask = new FormData();
fdExcludeFilemask.left = new FormAttachment(middle, 0);
fdExcludeFilemask.top = new FormAttachment(wFilemask, margin);
fdExcludeFilemask.right = new FormAttachment(wFilename, 0, SWT.RIGHT);
wExcludeFilemask.setLayoutData(fdExcludeFilemask);
// Filename list line
wlFilenameList = new Label(wFileComp, SWT.RIGHT);
wlFilenameList.setText(BaseMessages.getString(PKG, "LDIFInputDialog.FilenameList.Label"));
props.setLook(wlFilenameList);
fdlFilenameList = new FormData();
fdlFilenameList.left = new FormAttachment(0, 0);
fdlFilenameList.top = new FormAttachment(wExcludeFilemask, margin);
fdlFilenameList.right = new FormAttachment(middle, -margin);
wlFilenameList.setLayoutData(fdlFilenameList);
// Buttons to the right of the screen...
wbdFilename = new Button(wFileComp, SWT.PUSH | SWT.CENTER);
props.setLook(wbdFilename);
wbdFilename.setText(BaseMessages.getString(PKG, "LDIFInputDialog.FilenameRemove.Button"));
wbdFilename.setToolTipText(BaseMessages.getString(PKG, "LDIFInputDialog.FilenameRemove.Tooltip"));
fdbdFilename = new FormData();
fdbdFilename.right = new FormAttachment(100, 0);
fdbdFilename.top = new FormAttachment(wExcludeFilemask, 40);
wbdFilename.setLayoutData(fdbdFilename);
wbeFilename = new Button(wFileComp, SWT.PUSH | SWT.CENTER);
props.setLook(wbeFilename);
wbeFilename.setText(BaseMessages.getString(PKG, "LDIFInputDialog.FilenameEdit.Button"));
wbeFilename.setToolTipText(BaseMessages.getString(PKG, "LDIFInputDialog.FilenameEdit.Tooltip"));
fdbeFilename = new FormData();
fdbeFilename.right = new FormAttachment(100, 0);
fdbeFilename.top = new FormAttachment(wbdFilename, margin);
wbeFilename.setLayoutData(fdbeFilename);
wbShowFiles = new Button(wFileComp, SWT.PUSH | SWT.CENTER);
props.setLook(wbShowFiles);
wbShowFiles.setText(BaseMessages.getString(PKG, "LDIFInputDialog.ShowFiles.Button"));
fdbShowFiles = new FormData();
fdbShowFiles.left = new FormAttachment(middle, 0);
fdbShowFiles.bottom = new FormAttachment(100, 0);
wbShowFiles.setLayoutData(fdbShowFiles);
ColumnInfo[] colinfo = new ColumnInfo[5];
colinfo[0] = new ColumnInfo(BaseMessages.getString(PKG, "LDIFInputDialog.Files.Filename.Column"),
ColumnInfo.COLUMN_TYPE_TEXT, false);
colinfo[1] = new ColumnInfo(BaseMessages.getString(PKG, "LDIFInputDialog.Files.Wildcard.Column"),
ColumnInfo.COLUMN_TYPE_TEXT, false);
colinfo[ 2]=new ColumnInfo(BaseMessages.getString(PKG, "LDIFInputDialog.Files.ExcludeWildcard.Column"),
ColumnInfo.COLUMN_TYPE_TEXT, false);
colinfo[3]=new ColumnInfo(BaseMessages.getString(PKG, "LDIFInputDialog.Required.Column"),
ColumnInfo.COLUMN_TYPE_CCOMBO, LDIFInputMeta.RequiredFilesDesc );
colinfo[4]=new ColumnInfo(BaseMessages.getString(PKG, "LDIFInputDialog.IncludeSubDirs.Column"),
ColumnInfo.COLUMN_TYPE_CCOMBO, LDIFInputMeta.RequiredFilesDesc );
colinfo[0].setUsingVariables(true);
colinfo[1].setUsingVariables(true);
colinfo[1].setToolTip(BaseMessages.getString(PKG, "LDIFInputDialog.Files.Wildcard.Tooltip"));
colinfo[2].setToolTip(BaseMessages.getString(PKG, "LDIFInputDialog.Required.Tooltip"));
colinfo[2].setUsingVariables(true);
colinfo[2].setToolTip(BaseMessages.getString(PKG, "LDIFInputDialog.Files.ExcludeWildcard.Tooltip"));
colinfo[4].setToolTip(BaseMessages.getString(PKG, "LDIFInputDialog.IncludeSubDirs.Tooltip"));
wFilenameList = new TableView(transMeta,wFileComp, SWT.FULL_SELECTION
| SWT.SINGLE | SWT.BORDER, colinfo, 2, lsMod, props);
props.setLook(wFilenameList);
fdFilenameList = new FormData();
fdFilenameList.left = new FormAttachment(middle, 0);
fdFilenameList.right = new FormAttachment(wbdFilename, -margin);
fdFilenameList.top = new FormAttachment(wExcludeFilemask, margin);
fdFilenameList.bottom = new FormAttachment(wbShowFiles, -margin);
wFilenameList.setLayoutData(fdFilenameList);
fdFileComp = new FormData();
fdFileComp.left = new FormAttachment(0, 0);
fdFileComp.top = new FormAttachment(0, 0);
fdFileComp.right = new FormAttachment(100, 0);
fdFileComp.bottom = new FormAttachment(100, 0);
wFileComp.setLayoutData(fdFileComp);
wFileComp.layout();
wFileTab.setControl(wFileComp);
// ///////////////////////////////////////////////////////////
// / END OF FILE TAB
// ///////////////////////////////////////////////////////////
// ////////////////////////
// START OF CONTENT TAB///
// /
wContentTab = new CTabItem(wTabFolder, SWT.NONE);
wContentTab.setText(BaseMessages.getString(PKG, "LDIFInputDialog.Content.Tab"));
FormLayout contentLayout = new FormLayout();
contentLayout.marginWidth = 3;
contentLayout.marginHeight = 3;
wContentComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wContentComp);
wContentComp.setLayout(contentLayout);
wlInclFilename = new Label(wContentComp, SWT.RIGHT);
wlInclFilename.setText(BaseMessages.getString(PKG, "LDIFInputDialog.InclFilename.Label"));
props.setLook(wlInclFilename);
fdlInclFilename = new FormData();
fdlInclFilename.left = new FormAttachment(0, 0);
fdlInclFilename.top = new FormAttachment(0, 2 * margin);
fdlInclFilename.right = new FormAttachment(middle, -margin);
wlInclFilename.setLayoutData(fdlInclFilename);
wInclFilename = new Button(wContentComp, SWT.CHECK);
props.setLook(wInclFilename);
wInclFilename.setToolTipText(BaseMessages.getString(PKG, "LDIFInputDialog.InclFilename.Tooltip"));
fdInclFilename = new FormData();
fdInclFilename.left = new FormAttachment(middle, 0);
fdInclFilename.top = new FormAttachment(0, 2 * margin);
wInclFilename.setLayoutData(fdInclFilename);
wlInclFilenameField = new Label(wContentComp, SWT.LEFT);
wlInclFilenameField.setText(BaseMessages.getString(PKG, "LDIFInputDialog.InclFilenameField.Label"));
props.setLook(wlInclFilenameField);
fdlInclFilenameField = new FormData();
fdlInclFilenameField.left = new FormAttachment(wInclFilename, margin);
fdlInclFilenameField.top = new FormAttachment(0, 2 * margin);
wlInclFilenameField.setLayoutData(fdlInclFilenameField);
wInclFilenameField = new TextVar(transMeta,wContentComp, SWT.SINGLE | SWT.LEFT
| SWT.BORDER);
props.setLook(wInclFilenameField);
wInclFilenameField.addModifyListener(lsMod);
fdInclFilenameField = new FormData();
fdInclFilenameField.left = new FormAttachment(wlInclFilenameField,
margin);
fdInclFilenameField.top = new FormAttachment(0, 2 * margin);
fdInclFilenameField.right = new FormAttachment(100, 0);
wInclFilenameField.setLayoutData(fdInclFilenameField);
wlInclRownum = new Label(wContentComp, SWT.RIGHT);
wlInclRownum.setText(BaseMessages.getString(PKG, "LDIFInputDialog.InclRownum.Label"));
props.setLook(wlInclRownum);
fdlInclRownum = new FormData();
fdlInclRownum.left = new FormAttachment(0, 0);
fdlInclRownum.top = new FormAttachment(wInclFilenameField, margin);
fdlInclRownum.right = new FormAttachment(middle, -margin);
wlInclRownum.setLayoutData(fdlInclRownum);
wInclRownum = new Button(wContentComp, SWT.CHECK);
props.setLook(wInclRownum);
wInclRownum.setToolTipText(BaseMessages.getString(PKG, "LDIFInputDialog.InclRownum.Tooltip"));
fdRownum = new FormData();
fdRownum.left = new FormAttachment(middle, 0);
fdRownum.top = new FormAttachment(wInclFilenameField, margin);
wInclRownum.setLayoutData(fdRownum);
wlInclRownumField = new Label(wContentComp, SWT.RIGHT);
wlInclRownumField.setText(BaseMessages.getString(PKG, ("LDIFInputDialog.InclRownumField.Label")));
props.setLook(wlInclRownumField);
fdlInclRownumField = new FormData();
fdlInclRownumField.left = new FormAttachment(wInclRownum, margin);
fdlInclRownumField.top = new FormAttachment(wInclFilenameField, margin);
wlInclRownumField.setLayoutData(fdlInclRownumField);
wInclRownumField = new TextVar(transMeta,wContentComp, SWT.SINGLE | SWT.LEFT
| SWT.BORDER);
props.setLook(wInclRownumField);
wInclRownumField.addModifyListener(lsMod);
fdInclRownumField = new FormData();
fdInclRownumField.left = new FormAttachment(wlInclRownumField, margin);
fdInclRownumField.top = new FormAttachment(wInclFilenameField, margin);
fdInclRownumField.right = new FormAttachment(100, 0);
wInclRownumField.setLayoutData(fdInclRownumField);
// Add content type field?
wlInclContentType = new Label(wContentComp, SWT.RIGHT);
wlInclContentType.setText(BaseMessages.getString(PKG, "LDIFInputDialog.InclContentType.Label"));
props.setLook(wlInclContentType);
fdlInclContentType = new FormData();
fdlInclContentType.left = new FormAttachment(0, 0);
fdlInclContentType.top = new FormAttachment(wInclRownumField, margin);
fdlInclContentType.right = new FormAttachment(middle, -margin);
wlInclContentType.setLayoutData(fdlInclContentType);
wInclContentType = new Button(wContentComp, SWT.CHECK);
props.setLook(wInclContentType);
wInclContentType.setToolTipText(BaseMessages.getString(PKG, "LDIFInputDialog.InclContentType.Tooltip"));
fdInclContentType = new FormData();
fdInclContentType.left = new FormAttachment(middle, 0);
fdInclContentType.top = new FormAttachment(wInclRownumField, margin);
wInclContentType.setLayoutData(fdInclContentType);
// Content type field name
wlInclContentTypeField = new Label(wContentComp, SWT.LEFT);
wlInclContentTypeField.setText(BaseMessages.getString(PKG, "LDIFInputDialog.InclContentTypeField.Label"));
props.setLook(wlInclContentTypeField);
fdlInclContentTypeField = new FormData();
fdlInclContentTypeField.left = new FormAttachment(wInclContentType, margin);
fdlInclContentTypeField.top = new FormAttachment(wInclRownumField,margin);
wlInclContentTypeField.setLayoutData(fdlInclContentTypeField);
wInclContentTypeField = new TextVar(transMeta,wContentComp, SWT.SINGLE | SWT.LEFT| SWT.BORDER);
props.setLook(wInclContentTypeField);
wInclContentTypeField.addModifyListener(lsMod);
fdInclContentTypeField = new FormData();
fdInclContentTypeField.left = new FormAttachment(wlInclContentTypeField,margin);
fdInclContentTypeField.top = new FormAttachment(wInclRownumField, margin);
fdInclContentTypeField.right = new FormAttachment(100, 0);
wInclContentTypeField.setLayoutData(fdInclContentTypeField);
// Add content type field?
wlInclDN = new Label(wContentComp, SWT.RIGHT);
wlInclDN.setText(BaseMessages.getString(PKG, "LDIFInputDialog.InclDN.Label"));
props.setLook(wlInclDN);
fdlInclDN = new FormData();
fdlInclDN.left = new FormAttachment(0, 0);
fdlInclDN.top = new FormAttachment(wInclContentTypeField, margin);
fdlInclDN.right = new FormAttachment(middle, -margin);
wlInclDN.setLayoutData(fdlInclDN);
wInclDN = new Button(wContentComp, SWT.CHECK);
props.setLook(wInclDN);
wInclDN.setToolTipText(BaseMessages.getString(PKG, "LDIFInputDialog.InclDN.Tooltip"));
fdInclDN = new FormData();
fdInclDN.left = new FormAttachment(middle, 0);
fdInclDN.top = new FormAttachment(wInclContentTypeField, margin);
wInclDN.setLayoutData(fdInclDN);
// Content type field name
wlInclDNField = new Label(wContentComp, SWT.LEFT);
wlInclDNField.setText(BaseMessages.getString(PKG, "LDIFInputDialog.InclDNField.Label"));
props.setLook(wlInclDNField);
fdlInclDNField = new FormData();
fdlInclDNField.left = new FormAttachment(wInclDN, margin);
fdlInclDNField.top = new FormAttachment(wInclContentTypeField,margin);
wlInclDNField.setLayoutData(fdlInclDNField);
wInclDNField = new TextVar(transMeta,wContentComp, SWT.SINGLE | SWT.LEFT| SWT.BORDER);
props.setLook(wInclDNField);
wInclDNField.addModifyListener(lsMod);
fdInclDNField = new FormData();
fdInclDNField.left = new FormAttachment(wlInclDNField,margin);
fdInclDNField.top = new FormAttachment(wInclContentTypeField, margin);
fdInclDNField.right = new FormAttachment(100, 0);
wInclDNField.setLayoutData(fdInclDNField);
// Limit to preview
wlLimit = new Label(wContentComp, SWT.RIGHT);
wlLimit.setText(BaseMessages.getString(PKG, "LDIFInputDialog.Limit.Label"));
props.setLook(wlLimit);
fdlLimit = new FormData();
fdlLimit.left = new FormAttachment(0, 0);
fdlLimit.top = new FormAttachment(wInclDNField, margin);
fdlLimit.right = new FormAttachment(middle, -margin);
wlLimit.setLayoutData(fdlLimit);
wLimit = new Text(wContentComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wLimit);
wLimit.addModifyListener(lsMod);
fdLimit = new FormData();
fdLimit.left = new FormAttachment(middle, 0);
fdLimit.top = new FormAttachment(wInclDNField, margin);
fdLimit.right = new FormAttachment(100, 0);
wLimit.setLayoutData(fdLimit);
// Multi valued field separator
wlMultiValuedSeparator=new Label(wContentComp, SWT.RIGHT);
wlMultiValuedSeparator.setText(BaseMessages.getString(PKG, "LDIFInputDialog.MultiValuedSeparator.Label"));
props.setLook(wlMultiValuedSeparator);
fdlMultiValuedSeparator=new FormData();
fdlMultiValuedSeparator.left = new FormAttachment(0, 0);
fdlMultiValuedSeparator.top = new FormAttachment(wLimit, margin);
fdlMultiValuedSeparator.right= new FormAttachment(middle, -margin);
wlMultiValuedSeparator.setLayoutData(fdlMultiValuedSeparator);
wMultiValuedSeparator=new TextVar(transMeta,wContentComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wMultiValuedSeparator);
wMultiValuedSeparator.setToolTipText(BaseMessages.getString(PKG, "LDIFInputDialog.MultiValuedSeparator.Tooltip"));
wMultiValuedSeparator.addModifyListener(lsMod);
fdMultiValuedSeparator=new FormData();
fdMultiValuedSeparator.left = new FormAttachment(middle, 0);
fdMultiValuedSeparator.top = new FormAttachment(wLimit, margin);
fdMultiValuedSeparator.right= new FormAttachment(100, 0);
wMultiValuedSeparator.setLayoutData(fdMultiValuedSeparator);
// ///////////////////////////////
// START OF AddFileResult GROUP //
/////////////////////////////////
wAddFileResult = new Group(wContentComp, SWT.SHADOW_NONE);
props.setLook(wAddFileResult);
wAddFileResult.setText(BaseMessages.getString(PKG, "LDIFInputDialog.wAddFileResult.Label"));
FormLayout AddFileResultgroupLayout = new FormLayout();
AddFileResultgroupLayout.marginWidth = 10;
AddFileResultgroupLayout.marginHeight = 10;
wAddFileResult.setLayout(AddFileResultgroupLayout);
wlAddResult=new Label(wAddFileResult, SWT.RIGHT);
wlAddResult.setText(BaseMessages.getString(PKG, "LDIFInputDialog.AddResult.Label"));
props.setLook(wlAddResult);
fdlAddResult=new FormData();
fdlAddResult.left = new FormAttachment(0, 0);
fdlAddResult.top = new FormAttachment(wMultiValuedSeparator, margin);
fdlAddResult.right= new FormAttachment(middle, -margin);
wlAddResult.setLayoutData(fdlAddResult);
wAddResult=new Button(wAddFileResult, SWT.CHECK );
props.setLook(wAddResult);
wAddResult.setToolTipText(BaseMessages.getString(PKG, "LDIFInputDialog.AddResult.Tooltip"));
fdAddResult=new FormData();
fdAddResult.left = new FormAttachment(middle, 0);
fdAddResult.top = new FormAttachment(wMultiValuedSeparator, margin);
wAddResult.setLayoutData(fdAddResult);
fdAddFileResult = new FormData();
fdAddFileResult.left = new FormAttachment(0, margin);
fdAddFileResult.top = new FormAttachment(wMultiValuedSeparator, margin);
fdAddFileResult.right = new FormAttachment(100, -margin);
wAddFileResult.setLayoutData(fdAddFileResult);
// ///////////////////////////////////////////////////////////
// / END OF AddFileResult GROUP
// ///////////////////////////////////////////////////////////
fdContentComp = new FormData();
fdContentComp.left = new FormAttachment(0, 0);
fdContentComp.top = new FormAttachment(0, 0);
fdContentComp.right = new FormAttachment(100, 0);
fdContentComp.bottom = new FormAttachment(100, 0);
wContentComp.setLayoutData(fdContentComp);
wContentComp.layout();
wContentTab.setControl(wContentComp);
// ///////////////////////////////////////////////////////////
// / END OF CONTENT TAB
// ///////////////////////////////////////////////////////////
// Fields tab...
//
wFieldsTab = new CTabItem(wTabFolder, SWT.NONE);
wFieldsTab.setText(BaseMessages.getString(PKG, "LDIFInputDialog.Fields.Tab"));
FormLayout fieldsLayout = new FormLayout();
fieldsLayout.marginWidth = Const.FORM_MARGIN;
fieldsLayout.marginHeight = Const.FORM_MARGIN;
wFieldsComp = new Composite(wTabFolder, SWT.NONE);
wFieldsComp.setLayout(fieldsLayout);
props.setLook(wFieldsComp);
wGet = new Button(wFieldsComp, SWT.PUSH);
wGet.setText(BaseMessages.getString(PKG, "LDIFInputDialog.GetFields.Button"));
fdGet = new FormData();
fdGet.left = new FormAttachment(50, 0);
fdGet.bottom = new FormAttachment(100, 0);
wGet.setLayoutData(fdGet);
final int FieldsRows = input.getInputFields().length;
ColumnInfo[] colinf = new ColumnInfo[] {
new ColumnInfo(BaseMessages.getString(PKG, "LDIFInputDialog.FieldsTable.Name.Column"),
ColumnInfo.COLUMN_TYPE_TEXT, false),
new ColumnInfo(
BaseMessages.getString(PKG, "LDIFInputDialog.FieldsTable.Attribut.Column"),
ColumnInfo.COLUMN_TYPE_TEXT, false),
new ColumnInfo(BaseMessages.getString(PKG, "LDIFInputDialog.FieldsTable.Type.Column"),
ColumnInfo.COLUMN_TYPE_CCOMBO, ValueMeta.getTypes(), true),
new ColumnInfo(
BaseMessages.getString(PKG, "LDIFInputDialog.FieldsTable.Format.Column"),
ColumnInfo.COLUMN_TYPE_FORMAT, 3),
new ColumnInfo(
BaseMessages.getString(PKG, "LDIFInputDialog.FieldsTable.Length.Column"),
ColumnInfo.COLUMN_TYPE_TEXT, false),
new ColumnInfo(
BaseMessages.getString(PKG, "LDIFInputDialog.FieldsTable.Precision.Column"),
ColumnInfo.COLUMN_TYPE_TEXT, false),
new ColumnInfo(
BaseMessages.getString(PKG, "LDIFInputDialog.FieldsTable.Currency.Column"),
ColumnInfo.COLUMN_TYPE_TEXT, false),
new ColumnInfo(
BaseMessages.getString(PKG, "LDIFInputDialog.FieldsTable.Decimal.Column"),
ColumnInfo.COLUMN_TYPE_TEXT, false),
new ColumnInfo(BaseMessages.getString(PKG, "LDIFInputDialog.FieldsTable.Group.Column"),
ColumnInfo.COLUMN_TYPE_TEXT, false),
new ColumnInfo(
BaseMessages.getString(PKG, "LDIFInputDialog.FieldsTable.TrimType.Column"),
ColumnInfo.COLUMN_TYPE_CCOMBO,
LDIFInputField.trimTypeDesc, true),
new ColumnInfo(
BaseMessages.getString(PKG, "LDIFInputDialog.FieldsTable.Repeat.Column"),
ColumnInfo.COLUMN_TYPE_CCOMBO, new String[] {
BaseMessages.getString(PKG, "System.Combo.Yes"),
BaseMessages.getString(PKG, "System.Combo.No") }, true),
};
colinf[0].setUsingVariables(true);
colinf[0].setToolTip(BaseMessages.getString(PKG, "LDIFInputDialog.FieldsTable.Name.Column.Tooltip"));
colinf[1].setUsingVariables(true);
colinf[1]
.setToolTip(BaseMessages.getString(PKG, "LDIFInputDialog.FieldsTable.Attribut.Column.Tooltip"));
wFields = new TableView(transMeta,wFieldsComp, SWT.FULL_SELECTION | SWT.MULTI,
colinf, FieldsRows, lsMod, props);
fdFields = new FormData();
fdFields.left = new FormAttachment(0, 0);
fdFields.top = new FormAttachment(0, 0);
fdFields.right = new FormAttachment(100, 0);
fdFields.bottom = new FormAttachment(wGet, -margin);
wFields.setLayoutData(fdFields);
fdFieldsComp = new FormData();
fdFieldsComp.left = new FormAttachment(0, 0);
fdFieldsComp.top = new FormAttachment(0, 0);
fdFieldsComp.right = new FormAttachment(100, 0);
fdFieldsComp.bottom = new FormAttachment(100, 0);
wFieldsComp.setLayoutData(fdFieldsComp);
wFieldsComp.layout();
wFieldsTab.setControl(wFieldsComp);
addAdditionalFieldsTab();
fdTabFolder = new FormData();
fdTabFolder.left = new FormAttachment(0, 0);
fdTabFolder.top = new FormAttachment(wStepname, margin);
fdTabFolder.right = new FormAttachment(100, 0);
fdTabFolder.bottom = new FormAttachment(100, -50);
wTabFolder.setLayoutData(fdTabFolder);
wOK = new Button(shell, SWT.PUSH);
wOK.setText(BaseMessages.getString(PKG, "System.Button.OK"));
wPreview = new Button(shell, SWT.PUSH);
wPreview.setText(BaseMessages.getString(PKG, "LDIFInputDialog.Button.PreviewRows"));
wCancel = new Button(shell, SWT.PUSH);
wCancel.setText(BaseMessages.getString(PKG, "System.Button.Cancel"));
setButtonPositions(new Button[] { wOK, wPreview, wCancel }, margin,
wTabFolder);
// Add listeners
lsOK = new Listener() {
public void handleEvent(Event e) {
ok();
}
};
lsGet = new Listener() {
public void handleEvent(Event e) {
get();
}
};
lsPreview = new Listener() {
public void handleEvent(Event e) {
preview();
}
};
lsCancel = new Listener() {
public void handleEvent(Event e) {
cancel();
}
};
wOK.addListener(SWT.Selection, lsOK);
wGet.addListener(SWT.Selection, lsGet);
wPreview.addListener(SWT.Selection, lsPreview);
wCancel.addListener(SWT.Selection, lsCancel);
lsDef = new SelectionAdapter() {
public void widgetDefaultSelected(SelectionEvent e) {
ok();
}
};
wStepname.addSelectionListener(lsDef);
wLimit.addSelectionListener(lsDef);
wInclRownumField.addSelectionListener(lsDef);
wInclFilenameField.addSelectionListener(lsDef);
// Add the file to the list of files...
SelectionAdapter selA = new SelectionAdapter() {
public void widgetSelected(SelectionEvent arg0) {
wFilenameList.add(new String[] { wFilename.getText(), wFilemask.getText(), wExcludeFilemask.getText(), LDIFInputMeta.RequiredFilesCode[0], LDIFInputMeta.RequiredFilesCode[0]} );
wFilename.setText("");
wFilemask.setText("");
wExcludeFilemask.setText("");
wFilenameList.removeEmptyRows();
wFilenameList.setRowNums();
wFilenameList.optWidth(true);
}
};
wbaFilename.addSelectionListener(selA);
wFilename.addSelectionListener(selA);
// Delete files from the list of files...
wbdFilename.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent arg0) {
int idx[] = wFilenameList.getSelectionIndices();
wFilenameList.remove(idx);
wFilenameList.removeEmptyRows();
wFilenameList.setRowNums();
}
});
// Edit the selected file & remove from the list...
wbeFilename.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent arg0) {
int idx = wFilenameList.getSelectionIndex();
if (idx >= 0) {
String string[] = wFilenameList.getItem(idx);
wFilename.setText(string[0]);
wFilemask.setText(string[1]);
wExcludeFilemask.setText(string[2]);
wFilenameList.remove(idx);
}
wFilenameList.removeEmptyRows();
wFilenameList.setRowNums();
}
});
// Show the files that are selected at this time...
wbShowFiles.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
try {
LDIFInputMeta tfii = new LDIFInputMeta();
getInfo(tfii);
FileInputList fileInputList = tfii.getFiles(transMeta);
String files[] = fileInputList.getFileStrings();
if (files != null && files.length > 0) {
EnterSelectionDialog esd = new EnterSelectionDialog(
shell,
files,
BaseMessages.getString(PKG, "LDIFInputDialog.FilesReadSelection.DialogTitle"),
BaseMessages.getString(PKG, "LDIFInputDialog.FilesReadSelection.DialogMessage"));
esd.setViewOnly();
esd.open();
} else {
MessageBox mb = new MessageBox(shell, SWT.OK
| SWT.ICON_ERROR);
mb.setMessage(BaseMessages.getString(PKG, "LDIFInputDialog.NoFileFound.DialogMessage"));
mb.setText(BaseMessages.getString(PKG, "System.Dialog.Error.Title"));
mb.open();
}
} catch (KettleException ex) {
new ErrorDialog(
shell,
BaseMessages.getString(PKG, "LDIFInputDialog.ErrorParsingData.DialogTitle"),
BaseMessages.getString(PKG, "LDIFInputDialog.ErrorParsingData.DialogMessage"), ex);
}
}
});
// Enable/disable the right fields to allow a filename to be added to
// each row...
wInclFilename.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
setIncludeFilename();
}
});
// Enable/disable the right fields to allow a row number to be added to
// each row...
wInclRownum.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
setIncludeRownum();
}
});
// Enable/disable the right fields to allow a content type to be added to
// each row...
wInclContentType.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
setContenType();
}
});
// Enable/disable the right fields to allow a content type to be added to
// each row...
wInclDN.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
setDN();
}
});
// Whenever something changes, set the tooltip to the expanded version
// of the filename:
wFilename.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
wFilename.setToolTipText(transMeta.environmentSubstitute(wFilename.getText()));
}
});
// Listen to the Browse... button
wbbFilename.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if (!Const.isEmpty(wFilemask.getText()) || !Const.isEmpty(wExcludeFilemask.getText()))
{
DirectoryDialog dialog = new DirectoryDialog(shell,
SWT.OPEN);
if (wFilename.getText() != null) {
String fpath = transMeta.environmentSubstitute(wFilename.getText());
dialog.setFilterPath(fpath);
}
if (dialog.open() != null) {
String str = dialog.getFilterPath();
wFilename.setText(str);
}
} else {
FileDialog dialog = new FileDialog(shell, SWT.OPEN);
dialog.setFilterExtensions(new String[] { "*ldif;*.LDIF",
"*" });
if (wFilename.getText() != null) {
String fname = transMeta.environmentSubstitute(wFilename.getText());
dialog.setFileName(fname);
}
dialog.setFilterNames(new String[] {
BaseMessages.getString(PKG, "LDIFInputDialog.FileType"),
BaseMessages.getString(PKG, "System.FileType.AllFiles") });
if (dialog.open() != null) {
String str = dialog.getFilterPath()
+ System.getProperty("file.separator")
+ dialog.getFileName();
wFilename.setText(str);
}
}
}
});
// Detect X or ALT-F4 or something that kills this window...
shell.addShellListener(new ShellAdapter() {
public void shellClosed(ShellEvent e) {
cancel();
}
});
wTabFolder.setSelection(0);
// Set the shell size, based upon previous time...
setSize();
getData(input);
ActiveFileField();
setContenType();
setDN();
input.setChanged(changed);
wFields.optWidth(true);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
return stepname;
}
private void ActiveFileField()
{
wlFilenameField.setEnabled(wFileField.getSelection());
wFilenameField.setEnabled(wFileField.getSelection());
wlFilename.setEnabled(!wFileField.getSelection());
wbbFilename.setEnabled(!wFileField.getSelection());
wbaFilename.setEnabled(!wFileField.getSelection());
wFilename.setEnabled(!wFileField.getSelection());
wlFilemask.setEnabled(!wFileField.getSelection());
wFilemask.setEnabled(!wFileField.getSelection());
wlFilenameList.setEnabled(!wFileField.getSelection());
wbdFilename.setEnabled(!wFileField.getSelection());
wbeFilename.setEnabled(!wFileField.getSelection());
wbShowFiles.setEnabled(!wFileField.getSelection());
wlFilenameList.setEnabled(!wFileField.getSelection());
wFilenameList.setEnabled(!wFileField.getSelection());
if(wFileField.getSelection()) wInclFilename.setSelection(false);
wInclFilename.setEnabled(!wFileField.getSelection());
wlInclFilename.setEnabled(!wFileField.getSelection());
wLimit.setEnabled(!wFileField.getSelection());
wPreview.setEnabled(!wFileField.getSelection());
wGet.setEnabled(!wFileField.getSelection());
wLimit.setEnabled(!wFileField.getSelection());
wlLimit.setEnabled(!wFileField.getSelection());
}
private void setFileField()
{
if(!gotPreviousField)
{
try{
String value=wFilenameField.getText();
wFilenameField.removeAll();
RowMetaInterface r = transMeta.getPrevStepFields(stepname);
if (r!=null)
{
r.getFieldNames();
for (int i=0;i<r.getFieldNames().length;i++)
{
wFilenameField.add(r.getFieldNames()[i]);
}
}
gotPreviousField=true;
if(value!=null) wFilenameField.setText(value);
}catch(KettleException ke){
new ErrorDialog(shell, BaseMessages.getString(PKG, "LDIFInputDialog.FailedToGetFields.DialogTitle"), BaseMessages.getString(PKG, "LDIFInputDialog.FailedToGetFields.DialogMessage"), ke); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
private void get() {
try {
LDIFInputMeta meta = new LDIFInputMeta();
getInfo(meta);
FileInputList inputList = meta.getFiles(transMeta);
// Clear Fields Grid
wFields.removeAll();
if (inputList.getFiles().size() > 0) {
// Open the file (only first file)...
LDIF InputLDIF = new LDIF(KettleVFS.getFilename(inputList.getFile(0)));
HashSet<String> attributeSet = new HashSet<String>();
for (LDIFRecord recordLDIF = InputLDIF.nextRecord(); recordLDIF != null; recordLDIF = InputLDIF.nextRecord()) {
// Get LDIF Content
LDIFContent contentLDIF = recordLDIF.getContent();
if (contentLDIF.getType() == LDIFContent.ATTRIBUTE_CONTENT)
{
// Get only ATTRIBUTE_CONTENT
LDIFAttributeContent attrContentLDIF = (LDIFAttributeContent) contentLDIF;
LDAPAttribute[] attributes_LDIF = attrContentLDIF.getAttributes();
for (int j = 0; j < attributes_LDIF.length; j++)
{
LDAPAttribute attribute_DIF = attributes_LDIF[j];
String attributeName = attribute_DIF.getName();
if (!attributeSet.contains(attributeName))
{
// Get attribut Name
TableItem item = new TableItem(wFields.table,SWT.NONE);
item.setText(1, attributeName);
item.setText(2, attributeName);
String attributeValue = GetValue(attributes_LDIF, attributeName);
// Try to get the Type
if (IsDate(attributeValue)) {
item.setText(3, "Date");
} else if (IsInteger(attributeValue)) {
item.setText(3, "Integer");
} else if (IsNumber(attributeValue)) {
item.setText(3, "Number");
} else {
item.setText(3, "String");
}
attributeSet.add(attributeName);
}
}
}
}
}
wFields.removeEmptyRows();
wFields.setRowNums();
wFields.optWidth(true);
} catch (KettleException e) {
new ErrorDialog(
shell,
BaseMessages.getString(PKG, "LDIFInputMeta.ErrorRetrieveData.DialogTitle"),
BaseMessages.getString(PKG, "LDIFInputMeta.ErrorRetrieveData.DialogMessage"),
e);
} catch (Exception e) {
new ErrorDialog(
shell,
BaseMessages.getString(PKG, "LDIFInputMeta.ErrorRetrieveData.DialogTitle"),
BaseMessages.getString(PKG, "LDIFInputMeta.ErrorRetrieveData.DialogMessage"),
e);
}
}
private boolean IsInteger(String str) {
try {
Integer.parseInt(str);
} catch (NumberFormatException e) {
return false;
}
return true;
}
private boolean IsNumber(String str) {
try {
Float.parseFloat(str);
} catch (Exception e) {
return false;
}
return true;
}
private boolean IsDate(String str) {
// TODO: What about other dates? Maybe something for a CRQ
try {
SimpleDateFormat fdate = new SimpleDateFormat("yy-mm-dd");
fdate.parse(str);
} catch (Exception e) {
return false;
}
return true;
}
@SuppressWarnings("unchecked")
private String GetValue(LDAPAttribute[] attributes_LDIF,
String AttributValue) {
String Stringvalue = null;
for (int j = 0; j < attributes_LDIF.length; j++) {
LDAPAttribute attribute_DIF = attributes_LDIF[j];
if (attribute_DIF.getName().equalsIgnoreCase(AttributValue)) {
Enumeration<String> valuesLDIF = attribute_DIF.getStringValues();
// Get the first occurence
Stringvalue = valuesLDIF.nextElement();
}
}
return Stringvalue;
}
public void setIncludeFilename() {
wlInclFilenameField.setEnabled(wInclFilename.getSelection());
wInclFilenameField.setEnabled(wInclFilename.getSelection());
}
public void setIncludeRownum() {
wlInclRownumField.setEnabled(wInclRownum.getSelection());
wInclRownumField.setEnabled(wInclRownum.getSelection());
}
/**
* Read the data from the TextFileInputMeta object and show it in this
* dialog.
*
* @param in
* The TextFileInputMeta object to obtain the data from.
*/
public void getData(LDIFInputMeta in) {
wFileField.setSelection(in.isFileField());
if (in.getDynamicFilenameField()!=null) wFilenameField.setText(in.getDynamicFilenameField());
if (in.getFileName() != null) {
wFilenameList.removeAll();
for (int i=0;i<in.getFileName().length;i++)
{
wFilenameList.add(new String[] { in.getFileName()[i], in.getFileMask()[i] ,in.getExludeFileMask()[i],
in.getRequiredFilesDesc(in.getFileRequired()[i]), in.getRequiredFilesDesc(in.getIncludeSubFolders()[i])} );
}
wFilenameList.removeEmptyRows();
wFilenameList.setRowNums();
wFilenameList.optWidth(true);
}
wInclFilename.setSelection(in.includeFilename());
wInclRownum.setSelection(in.includeRowNumber());
wInclContentType.setSelection(in.includeContentType());
wInclDN.setSelection(in.IncludeDN());
if(in.getMultiValuedSeparator()!=null) wMultiValuedSeparator.setText(in.getMultiValuedSeparator());
if (in.getFilenameField() != null)
wInclFilenameField.setText(in.getFilenameField());
if (in.getRowNumberField() != null)
wInclRownumField.setText(in.getRowNumberField());
if (in.getContentTypeField() != null)
wInclContentTypeField.setText(in.getContentTypeField());
if (in.getDNField() != null)
wInclDNField.setText(in.getDNField());
wLimit.setText("" + in.getRowLimit());
wAddResult.setSelection(in.AddToResultFilename());
logDebug(BaseMessages.getString(PKG, "LDIFInputDialog.Log.GettingFieldsInfo"));
for (int i = 0; i < in.getInputFields().length; i++) {
LDIFInputField field = in.getInputFields()[i];
if (field != null) {
TableItem item = wFields.table.getItem(i);
String name = field.getName();
String xpath = field.getAttribut();
String type = field.getTypeDesc();
String format = field.getFormat();
String length = "" + field.getLength();
String prec = "" + field.getPrecision();
String curr = field.getCurrencySymbol();
String group = field.getGroupSymbol();
String decim = field.getDecimalSymbol();
String trim = field.getTrimTypeDesc();
String rep = field.isRepeated() ? BaseMessages.getString(PKG, "System.Combo.Yes") : BaseMessages.getString(PKG, "System.Combo.No");
if (name != null)
item.setText(1, name);
if (xpath != null)
item.setText(2, xpath);
if (type != null)
item.setText(3, type);
if (format != null)
item.setText(4, format);
if (length != null && !"-1".equals(length))
item.setText(5, length);
if (prec != null && !"-1".equals(prec))
item.setText(6, prec);
if (curr != null)
item.setText(7, curr);
if (decim != null)
item.setText(8, decim);
if (group != null)
item.setText(9, group);
if (trim != null)
item.setText(10, trim);
if (rep != null)
item.setText(11, rep);
}
}
wFields.removeEmptyRows();
wFields.setRowNums();
wFields.optWidth(true);
if(in.getShortFileNameField()!=null) wShortFileFieldName.setText(in.getShortFileNameField());
if(in.getPathField()!=null) wPathFieldName.setText(in.getPathField());
if(in.isHiddenField()!=null) wIsHiddenName.setText(in.isHiddenField());
if(in.getLastModificationDateField()!=null) wLastModificationTimeName.setText(in.getLastModificationDateField());
if(in.getUriField()!=null) wUriName.setText(in.getUriField());
if(in.getRootUriField()!=null) wRootUriName.setText(in.getRootUriField());
if(in.getExtensionField()!=null) wExtensionFieldName.setText(in.getExtensionField());
if(in.getSizeField()!=null) wSizeFieldName.setText(in.getSizeField());
setIncludeFilename();
setIncludeRownum();
wStepname.selectAll();
}
private void cancel() {
stepname = null;
input.setChanged(changed);
dispose();
}
private void ok() {
try {
getInfo(input);
} catch (KettleException e) {
new ErrorDialog(
shell,
BaseMessages.getString(PKG, "LDIFInputDialog.ErrorParsingData.DialogTitle"),
BaseMessages.getString(PKG, "LDIFInputDialog.ErrorParsingData.DialogMessage"),
e);
}
dispose();
}
private void setContenType()
{
wlInclContentTypeField.setEnabled(wInclContentType.getSelection());
wInclContentTypeField.setEnabled(wInclContentType.getSelection());
}
private void setDN()
{
wlInclDNField.setEnabled(wInclDN.getSelection());
wInclDNField.setEnabled(wInclDN.getSelection());
}
private void getInfo(LDIFInputMeta in) throws KettleException {
stepname = wStepname.getText(); // return value
// copy info to TextFileInputMeta class (input)
in.setDynamicFilenameField( wFilenameField.getText() );
in.setFileField(wFileField.getSelection() );
in.setRowLimit(Const.toLong(wLimit.getText(), 0L));
in.setFilenameField(wInclFilenameField.getText());
in.setRowNumberField(wInclRownumField.getText());
in.setContentTypeField(wInclContentTypeField.getText());
in.setDNField(wInclDNField.getText());
in.setIncludeFilename(wInclFilename.getSelection());
in.setIncludeRowNumber(wInclRownum.getSelection());
in.setIncludeContentType(wInclContentType.getSelection());
in.setIncludeDN(wInclDN.getSelection());
in.setAddToResultFilename(wAddResult.getSelection());
in.setMultiValuedSeparator(wMultiValuedSeparator.getText());
int nrFiles = wFilenameList.getItemCount();
int nrFields = wFields.nrNonEmpty();
in.allocate(nrFiles, nrFields);
in.setFileName(wFilenameList.getItems(0));
in.setFileMask(wFilenameList.getItems(1));
in.setExcludeFileMask(wFilenameList.getItems(2));
in.setFileRequired(wFilenameList.getItems(3));
in.setIncludeSubFolders(wFilenameList.getItems(4));
for (int i = 0; i < nrFields; i++) {
LDIFInputField field = new LDIFInputField();
TableItem item = wFields.getNonEmpty(i);
field.setName(item.getText(1));
field.setAttribut(item.getText(2));
field.setType(ValueMeta.getType(item.getText(3)));
field.setFormat(item.getText(4));
field.setLength(Const.toInt(item.getText(5), -1));
field.setPrecision(Const.toInt(item.getText(6), -1));
field.setCurrencySymbol(item.getText(7));
field.setDecimalSymbol(item.getText(8));
field.setGroupSymbol(item.getText(9));
field.setTrimType(LDIFInputField
.getTrimTypeByDesc(item.getText(10)));
field.setRepeated(BaseMessages.getString(PKG, "System.Combo.Yes")
.equalsIgnoreCase(item.getText(11)));
in.getInputFields()[i] = field;
}
in.setShortFileNameField(wShortFileFieldName.getText());
in.setPathField(wPathFieldName.getText());
in.setIsHiddenField(wIsHiddenName.getText());
in.setLastModificationDateField(wLastModificationTimeName.getText());
in.setUriField(wUriName.getText());
in.setRootUriField(wRootUriName.getText());
in.setExtensionField(wExtensionFieldName.getText());
in.setSizeField(wSizeFieldName.getText());
}
// Preview the data
private void preview() {
try {
// Create the LDIF input step
LDIFInputMeta oneMeta = new LDIFInputMeta();
getInfo(oneMeta);
TransMeta previewMeta = TransPreviewFactory.generatePreviewTransformation(transMeta, oneMeta, wStepname.getText());
EnterNumberDialog numberDialog = new EnterNumberDialog(
shell,
props.getDefaultPreviewSize(),
BaseMessages.getString(PKG, "LDIFInputDialog.NumberRows.DialogTitle"),
BaseMessages.getString(PKG, "LDIFInputDialog.NumberRows.DialogMessage"));
int previewSize = numberDialog.open();
if (previewSize > 0) {
TransPreviewProgressDialog progressDialog = new TransPreviewProgressDialog(
shell, previewMeta,
new String[] { wStepname.getText() },
new int[] { previewSize });
progressDialog.open();
if (!progressDialog.isCancelled()) {
Trans trans = progressDialog.getTrans();
String loggingText = progressDialog.getLoggingText();
if (trans.getResult() != null
&& trans.getResult().getNrErrors() > 0) {
EnterTextDialog etd = new EnterTextDialog(
shell,
BaseMessages.getString(PKG, "System.Dialog.PreviewError.Title"),
BaseMessages.getString(PKG, "System.Dialog.PreviewError.Message"),
loggingText, true);
etd.setReadOnly();
etd.open();
}
PreviewRowsDialog prd = new PreviewRowsDialog(shell, transMeta, SWT.NONE, wStepname.getText(),
progressDialog.getPreviewRowsMeta(wStepname.getText()), progressDialog
.getPreviewRows(wStepname.getText()), loggingText);
prd.open();
}
}
} catch (KettleException e) {
new ErrorDialog(
shell,
BaseMessages.getString(PKG, "LDIFInputDialog.ErrorPreviewingData.DialogTitle"),
BaseMessages.getString(PKG, "LDIFInputDialog.ErrorPreviewingData.DialogMessage"),e);
}
}
private void addAdditionalFieldsTab()
{
// ////////////////////////
// START OF ADDITIONAL FIELDS TAB ///
// ////////////////////////
wAdditionalFieldsTab = new CTabItem(wTabFolder, SWT.NONE);
wAdditionalFieldsTab.setText(BaseMessages.getString(PKG, "LDIFInputDialog.AdditionalFieldsTab.TabTitle"));
wAdditionalFieldsComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wAdditionalFieldsComp);
FormLayout fieldsLayout = new FormLayout();
fieldsLayout.marginWidth = 3;
fieldsLayout.marginHeight = 3;
wAdditionalFieldsComp.setLayout(fieldsLayout);
// ShortFileFieldName line
wlShortFileFieldName = new Label(wAdditionalFieldsComp, SWT.RIGHT);
wlShortFileFieldName.setText(BaseMessages.getString(PKG, "LDIFInputDialog.ShortFileFieldName.Label"));
props.setLook(wlShortFileFieldName);
fdlShortFileFieldName = new FormData();
fdlShortFileFieldName.left = new FormAttachment(0, 0);
fdlShortFileFieldName.top = new FormAttachment(wInclRownumField, margin);
fdlShortFileFieldName.right = new FormAttachment(middle, -margin);
wlShortFileFieldName.setLayoutData(fdlShortFileFieldName);
wShortFileFieldName = new TextVar(transMeta, wAdditionalFieldsComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wShortFileFieldName);
wShortFileFieldName.addModifyListener(lsMod);
fdShortFileFieldName = new FormData();
fdShortFileFieldName.left = new FormAttachment(middle, 0);
fdShortFileFieldName.right = new FormAttachment(100, -margin);
fdShortFileFieldName.top = new FormAttachment(wInclRownumField, margin);
wShortFileFieldName.setLayoutData(fdShortFileFieldName);
// ExtensionFieldName line
wlExtensionFieldName = new Label(wAdditionalFieldsComp, SWT.RIGHT);
wlExtensionFieldName.setText(BaseMessages.getString(PKG, "LDIFInputDialog.ExtensionFieldName.Label"));
props.setLook(wlExtensionFieldName);
fdlExtensionFieldName = new FormData();
fdlExtensionFieldName.left = new FormAttachment(0, 0);
fdlExtensionFieldName.top = new FormAttachment(wShortFileFieldName, margin);
fdlExtensionFieldName.right = new FormAttachment(middle, -margin);
wlExtensionFieldName.setLayoutData(fdlExtensionFieldName);
wExtensionFieldName = new TextVar(transMeta, wAdditionalFieldsComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wExtensionFieldName);
wExtensionFieldName.addModifyListener(lsMod);
fdExtensionFieldName = new FormData();
fdExtensionFieldName.left = new FormAttachment(middle, 0);
fdExtensionFieldName.right = new FormAttachment(100, -margin);
fdExtensionFieldName.top = new FormAttachment(wShortFileFieldName, margin);
wExtensionFieldName.setLayoutData(fdExtensionFieldName);
// PathFieldName line
wlPathFieldName = new Label(wAdditionalFieldsComp, SWT.RIGHT);
wlPathFieldName.setText(BaseMessages.getString(PKG, "LDIFInputDialog.PathFieldName.Label"));
props.setLook(wlPathFieldName);
fdlPathFieldName = new FormData();
fdlPathFieldName.left = new FormAttachment(0, 0);
fdlPathFieldName.top = new FormAttachment(wExtensionFieldName, margin);
fdlPathFieldName.right = new FormAttachment(middle, -margin);
wlPathFieldName.setLayoutData(fdlPathFieldName);
wPathFieldName = new TextVar(transMeta, wAdditionalFieldsComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wPathFieldName);
wPathFieldName.addModifyListener(lsMod);
fdPathFieldName = new FormData();
fdPathFieldName.left = new FormAttachment(middle, 0);
fdPathFieldName.right = new FormAttachment(100, -margin);
fdPathFieldName.top = new FormAttachment(wExtensionFieldName, margin);
wPathFieldName.setLayoutData(fdPathFieldName);
// SizeFieldName line
wlSizeFieldName = new Label(wAdditionalFieldsComp, SWT.RIGHT);
wlSizeFieldName.setText(BaseMessages.getString(PKG, "LDIFInputDialog.SizeFieldName.Label"));
props.setLook(wlSizeFieldName);
fdlSizeFieldName = new FormData();
fdlSizeFieldName.left = new FormAttachment(0, 0);
fdlSizeFieldName.top = new FormAttachment(wPathFieldName, margin);
fdlSizeFieldName.right = new FormAttachment(middle, -margin);
wlSizeFieldName.setLayoutData(fdlSizeFieldName);
wSizeFieldName = new TextVar(transMeta, wAdditionalFieldsComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wSizeFieldName);
wSizeFieldName.addModifyListener(lsMod);
fdSizeFieldName = new FormData();
fdSizeFieldName.left = new FormAttachment(middle, 0);
fdSizeFieldName.right = new FormAttachment(100, -margin);
fdSizeFieldName.top = new FormAttachment(wPathFieldName, margin);
wSizeFieldName.setLayoutData(fdSizeFieldName);
// IsHiddenName line
wlIsHiddenName = new Label(wAdditionalFieldsComp, SWT.RIGHT);
wlIsHiddenName.setText(BaseMessages.getString(PKG, "LDIFInputDialog.IsHiddenName.Label"));
props.setLook(wlIsHiddenName);
fdlIsHiddenName = new FormData();
fdlIsHiddenName.left = new FormAttachment(0, 0);
fdlIsHiddenName.top = new FormAttachment(wSizeFieldName, margin);
fdlIsHiddenName.right = new FormAttachment(middle, -margin);
wlIsHiddenName.setLayoutData(fdlIsHiddenName);
wIsHiddenName = new TextVar(transMeta, wAdditionalFieldsComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wIsHiddenName);
wIsHiddenName.addModifyListener(lsMod);
fdIsHiddenName = new FormData();
fdIsHiddenName.left = new FormAttachment(middle, 0);
fdIsHiddenName.right = new FormAttachment(100, -margin);
fdIsHiddenName.top = new FormAttachment(wSizeFieldName, margin);
wIsHiddenName.setLayoutData(fdIsHiddenName);
// LastModificationTimeName line
wlLastModificationTimeName = new Label(wAdditionalFieldsComp, SWT.RIGHT);
wlLastModificationTimeName.setText(BaseMessages.getString(PKG, "LDIFInputDialog.LastModificationTimeName.Label"));
props.setLook(wlLastModificationTimeName);
fdlLastModificationTimeName = new FormData();
fdlLastModificationTimeName.left = new FormAttachment(0, 0);
fdlLastModificationTimeName.top = new FormAttachment(wIsHiddenName, margin);
fdlLastModificationTimeName.right = new FormAttachment(middle, -margin);
wlLastModificationTimeName.setLayoutData(fdlLastModificationTimeName);
wLastModificationTimeName = new TextVar(transMeta, wAdditionalFieldsComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wLastModificationTimeName);
wLastModificationTimeName.addModifyListener(lsMod);
fdLastModificationTimeName = new FormData();
fdLastModificationTimeName.left = new FormAttachment(middle, 0);
fdLastModificationTimeName.right = new FormAttachment(100, -margin);
fdLastModificationTimeName.top = new FormAttachment(wIsHiddenName, margin);
wLastModificationTimeName.setLayoutData(fdLastModificationTimeName);
// UriName line
wlUriName = new Label(wAdditionalFieldsComp, SWT.RIGHT);
wlUriName.setText(BaseMessages.getString(PKG, "LDIFInputDialog.UriName.Label"));
props.setLook(wlUriName);
fdlUriName = new FormData();
fdlUriName.left = new FormAttachment(0, 0);
fdlUriName.top = new FormAttachment(wLastModificationTimeName, margin);
fdlUriName.right = new FormAttachment(middle, -margin);
wlUriName.setLayoutData(fdlUriName);
wUriName = new TextVar(transMeta, wAdditionalFieldsComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wUriName);
wUriName.addModifyListener(lsMod);
fdUriName = new FormData();
fdUriName.left = new FormAttachment(middle, 0);
fdUriName.right = new FormAttachment(100, -margin);
fdUriName.top = new FormAttachment(wLastModificationTimeName, margin);
wUriName.setLayoutData(fdUriName);
// RootUriName line
wlRootUriName = new Label(wAdditionalFieldsComp, SWT.RIGHT);
wlRootUriName.setText(BaseMessages.getString(PKG, "LDIFInputDialog.RootUriName.Label"));
props.setLook(wlRootUriName);
fdlRootUriName = new FormData();
fdlRootUriName.left = new FormAttachment(0, 0);
fdlRootUriName.top = new FormAttachment(wUriName, margin);
fdlRootUriName.right = new FormAttachment(middle, -margin);
wlRootUriName.setLayoutData(fdlRootUriName);
wRootUriName = new TextVar(transMeta, wAdditionalFieldsComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wRootUriName);
wRootUriName.addModifyListener(lsMod);
fdRootUriName = new FormData();
fdRootUriName.left = new FormAttachment(middle, 0);
fdRootUriName.right = new FormAttachment(100, -margin);
fdRootUriName.top = new FormAttachment(wUriName, margin);
wRootUriName.setLayoutData(fdRootUriName);
fdAdditionalFieldsComp = new FormData();
fdAdditionalFieldsComp.left = new FormAttachment(0, 0);
fdAdditionalFieldsComp.top = new FormAttachment(wStepname, margin);
fdAdditionalFieldsComp.right = new FormAttachment(100, 0);
fdAdditionalFieldsComp.bottom = new FormAttachment(100, 0);
wAdditionalFieldsComp.setLayoutData(fdAdditionalFieldsComp);
wAdditionalFieldsComp.layout();
wAdditionalFieldsTab.setControl(wAdditionalFieldsComp);
// ///////////////////////////////////////////////////////////
// / END OF ADDITIONAL FIELDS TAB
// ///////////////////////////////////////////////////////////
}
} | {
"content_hash": "6ac6737cef42be4d5d3b679589aa27f2",
"timestamp": "",
"source": "github",
"line_count": 1731,
"max_line_length": 218,
"avg_line_length": 38.699017908723285,
"alnum_prop": 0.7351316653729026,
"repo_name": "bsspirit/kettle-4.4.0-stable",
"id": "126d142e4d6fd8c9c14250d148ec23a3785ec41e",
"size": "67890",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "src-ui/org/pentaho/di/ui/trans/steps/ldifinput/LDIFInputDialog.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "8211"
},
{
"name": "Java",
"bytes": "27799868"
},
{
"name": "Shell",
"bytes": "41993"
},
{
"name": "XSLT",
"bytes": "1456"
}
],
"symlink_target": ""
} |
service "shibd" do
supports :status => true, :restart => true, :reload => true
action [ :enable, :start ]
end | {
"content_hash": "7cf620b500b94f13253a0fc76d06e76e",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 61,
"avg_line_length": 28.25,
"alnum_prop": 0.6460176991150443,
"repo_name": "universityofcalifornia/chef-NeXt",
"id": "c6aab79d20818284d89c4b4d4418b7f4ff036d62",
"size": "113",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "cookbooks/shibboleth-sp/recipes/service.rb",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "HTML",
"bytes": "30374"
},
{
"name": "Ruby",
"bytes": "30868"
},
{
"name": "Shell",
"bytes": "598"
}
],
"symlink_target": ""
} |
from __future__ import unicode_literals, division, absolute_import
import collections
from gatesym.gates import Switch
class BinaryIn(collections.Sequence):
def __init__(self, network, size, value=0):
self.switches = [Switch(network) for i in range(size)]
self.write(value)
def write(self, value):
for switch in self.switches:
switch.write(value % 2)
value //= 2
def read(self):
res = 0
idx = 1
for switch in self.switches:
if switch.read():
res += idx
idx *= 2
return res
def __iter__(self):
return iter(self.switches)
def __len__(self):
return len(self.switches)
def __getitem__(self, key):
return self.switches.__getitem__(key)
class BinaryOut(object):
def __init__(self, gates):
self.gates = gates
def read(self):
res = 0
idx = 1
for gate in self.gates:
if gate.read():
res += idx
idx *= 2
return res
| {
"content_hash": "94a84f54b4043cb208a9370ec92bb108",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 66,
"avg_line_length": 22.354166666666668,
"alnum_prop": 0.5340167753960857,
"repo_name": "babbageclunk/gatesym",
"id": "5fd3713bdb5a0dbdbf8fe2439348ff826a8ffa66",
"size": "1073",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gatesym/test_utils.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "53679"
}
],
"symlink_target": ""
} |
import * as t from "../lib/index.js";
import { parse } from "@babel/parser";
function parseCode(string) {
return parse(string, {
allowReturnOutsideFunction: true,
}).program.body[0];
}
describe("misc helpers", function () {
describe("matchesPattern", function () {
it("matches explicitly", function () {
const ast = parseCode("a.b.c.d").expression;
expect(t.matchesPattern(ast, "a.b.c.d")).toBeTruthy();
expect(t.matchesPattern(ast, "a.b.c")).toBe(false);
expect(t.matchesPattern(ast, "b.c.d")).toBe(false);
expect(t.matchesPattern(ast, "a.b.c.d.e")).toBe(false);
});
it("matches partially", function () {
const ast = parseCode("a.b.c.d").expression;
expect(t.matchesPattern(ast, "a.b.c.d", true)).toBeTruthy();
expect(t.matchesPattern(ast, "a.b.c", true)).toBeTruthy();
expect(t.matchesPattern(ast, "b.c.d", true)).toBe(false);
expect(t.matchesPattern(ast, "a.b.c.d.e", true)).toBe(false);
});
it("matches string literal expressions", function () {
const ast = parseCode("a['b'].c.d").expression;
expect(t.matchesPattern(ast, "a.b.c.d")).toBeTruthy();
expect(t.matchesPattern(ast, "a.b.c")).toBe(false);
expect(t.matchesPattern(ast, "b.c.d")).toBe(false);
expect(t.matchesPattern(ast, "a.b.c.d.e")).toBe(false);
});
it("matches string literal expressions partially", function () {
const ast = parseCode("a['b'].c.d").expression;
expect(t.matchesPattern(ast, "a.b.c.d", true)).toBeTruthy();
expect(t.matchesPattern(ast, "a.b.c", true)).toBeTruthy();
expect(t.matchesPattern(ast, "b.c.d", true)).toBe(false);
expect(t.matchesPattern(ast, "a.b.c.d.e", true)).toBe(false);
});
it("matches this expressions", function () {
const ast = parseCode("this.a.b.c.d").expression;
expect(t.matchesPattern(ast, "this.a.b.c.d")).toBeTruthy();
expect(t.matchesPattern(ast, "this.a.b.c")).toBe(false);
expect(t.matchesPattern(ast, "this.b.c.d")).toBe(false);
expect(t.matchesPattern(ast, "this.a.b.c.d.e")).toBe(false);
});
});
});
| {
"content_hash": "56a84990f2276865f733a82af190e68b",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 68,
"avg_line_length": 40.84615384615385,
"alnum_prop": 0.6181732580037664,
"repo_name": "babel/babel",
"id": "bf781a9499e039243b4de683c9dbf5ea4fcb4b1c",
"size": "2124",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "packages/babel-types/test/misc.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "43"
},
{
"name": "HTML",
"bytes": "3371"
},
{
"name": "JavaScript",
"bytes": "1235617"
},
{
"name": "Makefile",
"bytes": "5662"
},
{
"name": "Prolog",
"bytes": "5810"
},
{
"name": "Shell",
"bytes": "20543"
},
{
"name": "TypeScript",
"bytes": "3084308"
}
],
"symlink_target": ""
} |
Pedometer
=========
Lightweight pedometer app using the <b>hardware step-sensor</b> for minimal battery consumption.
This app is designed to be kept running all the time without having any impact on your battery life! It uses the hardware step detection sensor of the Nexus 5, which is already running even when not using any pedometer app. Therefore the app does not consume any additional battery drain. Unlike other pedometer apps, this app does <b>not</b> track your movement or your location so it doesn't need to turn on your GPS sensor (again: <b>no impact on your battery</b>).
Sign in with your Google+ account to unlock <b>achievements</b> and keep you motivated!
Pedometer uses the [EazeGraphLibrary](https://github.com/blackfizz/EazeGraph "EazeGraphLibrary") by Paul Cech and [ColorPickerPreference](https://github.com/attenzione/android-ColorPickerPreference "android-ColorPickerPreference: Android color picking library") by Sergey Margaritov.
<table sytle="border: 0px;">
<tr>
<td><img width="200px" src="screenshot1.png" /></td>
<td><img width="200px" src="screenshot2.png" /></td>
</tr>
</table>
Build
-----
To build the app, add [BaseGameUtils](https://developers.google.com/games/services/android/init "Google Play communication library"), [EazeGraphLibrary](https://github.com/blackfizz/EazeGraph "EazeGraphLibrary") and [ColorPickerPreference](https://github.com/attenzione/android-ColorPickerPreference "android-ColorPickerPreference: Android color picking library") as libraries to the project as well as the [DashClock API](https://code.google.com/p/dashclock/downloads/list "DashClock Lock screen clock widget for Android 4.2+").
| {
"content_hash": "33ee6b71b84b4386a98613bbd2a14936",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 529,
"avg_line_length": 61.74074074074074,
"alnum_prop": 0.7756448710257948,
"repo_name": "luinvacc/pedometer",
"id": "281598ac4c1ccb92d42826f5a0cd07a3676803a1",
"size": "1667",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "1437"
},
{
"name": "Java",
"bytes": "102218"
}
],
"symlink_target": ""
} |
=head1 LICENSE
Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2019] EMBL-European Bioinformatics Institute
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.
=cut
# $Id$
# This is a set of subroutines used for creating Xrefs based on
# coordinate overlaps.
package XrefMapper::VBCoordinateMapper;
use strict;
use warnings;
use Bio::EnsEMBL::DBSQL::DBAdaptor;
use Bio::EnsEMBL::Mapper::RangeRegistry;
use Carp;
use IO::File;
use File::Spec::Functions;
use vars '@ISA';
@ISA = qw{ XrefMapper::CoordinateMapper };
our @EXPORT = qw( run_coordinatemapping );
our $coding_weight = 2;
our $ens_weight = 3;
our $transcript_score_threshold = 0.75;
sub run_coordinatemapping {
print STDERR "RUNNING VB COORD MAPPING\n";
my ( $mapper, $do_upload ) = @_;
my $xref_db = $mapper->xref();
my $core_db = $mapper->core();
my $species = $core_db->species();
my $species_id =
XrefMapper::BasicMapper::get_species_id_from_species_name( $xref_db,
$species );
# We only do coordinate mapping for mouse and human for now.
if ( !( $species eq 'mus_musculus' || $species eq 'homo_sapiens' ) ) {
# return;
}
my $output_dir = $core_db->dir();
my $xref_filename = catfile( $output_dir, 'xref_coord.txt' );
my $object_xref_filename =
catfile( $output_dir, 'object_xref_coord.txt' );
my $unmapped_reason_filename =
catfile( $output_dir, 'unmapped_reason_coord.txt' );
my $unmapped_object_filename =
catfile( $output_dir, 'unmapped_object_coord.txt' );
my $xref_dbh = $xref_db->dbc()->db_handle();
my $core_dbh = $core_db->dbc()->db_handle();
######################################################################
# Figure out the last used 'xref_id', 'object_xref_id', #
# 'unmapped_object_id', and 'unmapped_reason_id' from the Core #
# database. #
######################################################################
my $xref_id =
$core_dbh->selectall_arrayref('SELECT MAX(xref_id) FROM xref')
->[0][0];
my $object_xref_id = $core_dbh->selectall_arrayref(
'SELECT MAX(object_xref_id) FROM object_xref')->[0][0];
my $unmapped_object_id = $core_dbh->selectall_arrayref(
'SELECT MAX(unmapped_object_id) FROM unmapped_object')->[0][0];
my $unmapped_reason_id = $core_dbh->selectall_arrayref(
'SELECT MAX(unmapped_reason_id) FROM unmapped_reason')->[0][0];
log_progress( "Last used xref_id is %d\n", $xref_id );
log_progress( "Last used object_xref_id is %d\n",
$object_xref_id );
log_progress( "Last used unmapped_object_id is %d\n",
$unmapped_object_id );
log_progress( "Last used unmapped_reason_id is %d\n",
$unmapped_reason_id );
######################################################################
# Get an 'analysis_id', or discover that we need to add our analysis #
# to the 'analyis' table later. #
######################################################################
my $analysis_params =
sprintf( "weights(coding,ensembl)="
. "%.2f,%.2f;"
. "transcript_score_threshold=" . "%.2f",
$coding_weight, $ens_weight, $transcript_score_threshold );
my $analysis_sql = qq(
SELECT analysis_id
FROM analysis
WHERE logic_name = 'xrefcoordinatemapping'
AND parameters = ?
);
my $analysis_sth = $core_dbh->prepare($analysis_sql);
$analysis_sth->execute($analysis_params);
my $analysis_id = $analysis_sth->fetchall_arrayref()->[0][0];
if ( !defined($analysis_id) ) {
$analysis_id =
$core_dbh->selectall_arrayref( "SELECT analysis_id FROM analysis "
. "WHERE logic_name = 'xrefcoordinatemapping'" )->[0][0];
if ( defined($analysis_id) && $do_upload ) {
log_progress( "Will update 'analysis' table "
. "with new parameter settings\n" );
#-----------------------------------------------------------------
# Update an existing analysis.
#-----------------------------------------------------------------
my $sql = qq(
UPDATE analysis
SET created = now(), parameters = ?
WHERE analysis_id = ?
);
$core_dbh->do( $sql, undef, $analysis_params, $analysis_id );
} else {
log_progress("Can not find analysis ID for this analysis:\n");
log_progress(" logic_name = 'xrefcoordinatemapping'\n");
log_progress( " parameters = '%s'\n", $analysis_params );
if ($do_upload) {
#---------------------------------------------------------------
# Store a new analysis.
#---------------------------------------------------------------
log_progress("A new analysis will be added\n");
$analysis_id = $core_dbh->selectall_arrayref(
'SELECT MAX(analysis_id) FROM analysis')->[0][0];
log_progress( "Last used analysis_id is %d\n", $analysis_id );
my $sql = 'INSERT INTO analysis '
. 'VALUES(?, now(), ?, \N, \N, \N, ?, \N, \N, ?, ?, \N, \N, \N)';
my $sth = $core_dbh->prepare($sql);
$sth->execute( ++$analysis_id, 'xrefcoordinatemapping',
'xref_mapper.pl', $analysis_params,
'CoordinateMapper.pm' );
}
} ## end else [ if ( defined($analysis_id...
} ## end if ( !defined($analysis_id...
if ( defined($analysis_id) ) {
log_progress( "Analysis ID is %d\n",
$analysis_id );
}
######################################################################
# Read and store available Xrefs from the Xref database. #
######################################################################
my %unmapped;
my %mapped;
my $xref_sql = qq(
SELECT coord_xref_id, source_id, accession
FROM coordinate_xref
WHERE species_id = ?
);
my $xref_sth = $xref_dbh->prepare($xref_sql);
$xref_sth->execute($species_id);
while ( my $xref = $xref_sth->fetchrow_hashref() ) {
$unmapped{ $xref->{'coord_xref_id'} } = {
'external_db_id' =>
$XrefMapper::BasicMapper::source_to_external_db{ $xref->{
'source_id'} }
|| 11000, # FIXME (11000 is 'UCSC')
'accession' => $xref->{'accession'},
'reason' => 'No overlap',
'reason_full' =>
'No coordinate overlap with any Ensembl transcript' };
}
$xref_sth->finish();
######################################################################
# Do coordinate matching. #
######################################################################
my $core_db_adaptor =
Bio::EnsEMBL::DBSQL::DBAdaptor->new(
-host => $core_db->dbc()->host(),
-port => $core_db->dbc()->port(),
-user => $core_db->dbc()->username(),
-pass => $core_db->dbc()->password(),
-dbname => $core_db->dbc()->dbname(),
);
my $slice_adaptor = $core_db_adaptor->get_SliceAdaptor();
my @chromosomes = @{ $slice_adaptor->fetch_all('Chromosome') };
my $sql = qq(
SELECT coord_xref_id, accession,
txStart, txEnd,
cdsStart, cdsEnd,
exonStarts, exonEnds
FROM coordinate_xref
WHERE species_id = ?
AND chromosome = ? AND strand = ?
AND ((txStart >= ? AND txStart <= ?) -- txStart in region
OR (txEnd >= ? AND txEnd <= ?) -- txEnd in region
OR (txStart <= ? AND txEnd >= ?)) -- region is contained
ORDER BY accession
);
foreach my $chromosome (@chromosomes) {
my $chr_name = $chromosome->seq_region_name();
log_progress( "Processing chromsome '%s'\n", $chr_name );
my @genes = @{ $chromosome->get_all_Genes( undef, undef, 1 ) };
log_progress( "There are %4d genes on chromosome '%s'\n",
scalar(@genes), $chr_name );
while ( my $gene = shift(@genes) ) {
my @transcripts = @{ $gene->get_all_Transcripts() };
my %gene_result;
foreach my $transcript ( sort { $a->start() <=> $b->start() }
@transcripts )
{
################################################################
# For each Ensembl transcript: #
# 1. Register all Ensembl exons in a RangeRegistry. #
# #
# 2. Find all transcripts in the external database that are #
# within the range of this Ensembl transcript. #
# #
# For each of those external transcripts: #
# 3. Calculate the overlap of the exons of the external #
# transcript with the Ensembl exons using the #
# overlap_size() method in the RangeRegistry. #
# #
# 4. Register the external exons in their own RangeRegistry. #
# #
# 5. Calculate the overlap of the Ensembl exons with the #
# external exons as in step 3. #
# #
# 6. Calculate the match score. #
# #
# 7. Decide whether or not to keep the match. #
################################################################
my @exons = @{ $transcript->get_all_Exons() };
my %transcript_result;
# '$rr1' is the RangeRegistry holding Ensembl exons for one
# transcript at a time.
my $rr1 = Bio::EnsEMBL::Mapper::RangeRegistry->new();
my $coding_transcript;
if ( defined( $transcript->translation() ) ) {
$coding_transcript = 1;
} else {
$coding_transcript = 0;
}
foreach my $exon (@exons) {
#-------------------------------------------------------------
# Register each exon in the RangeRegistry. Register both the
# total length of the exon and the coding range of the exon.
#-------------------------------------------------------------
$rr1->check_and_register( 'exon', $exon->start(),
$exon->end() );
if ( $coding_transcript
&& defined( $exon->coding_region_start($transcript) )
&& defined( $exon->coding_region_end($transcript) ) )
{
$rr1->check_and_register(
'coding',
$exon->coding_region_start($transcript),
$exon->coding_region_end($transcript) );
}
}
#---------------------------------------------------------------
# Get hold of all transcripts from the external database that
# overlaps with this Ensembl transcript.
#---------------------------------------------------------------
my $sth = $xref_dbh->prepare_cached($sql);
$sth->execute( $species_id, $chr_name,
$gene->strand(), $transcript->start(),
$transcript->end(), $transcript->start(),
$transcript->end(), $transcript->start(),
$transcript->end() );
my ( $coord_xref_id, $accession, $txStart, $txEnd, $cdsStart,
$cdsEnd, $exonStarts, $exonEnds );
$sth->bind_columns(
\( $coord_xref_id, $accession, $txStart, $txEnd,
$cdsStart, $cdsEnd, $exonStarts, $exonEnds
) );
while ( $sth->fetch() ) {
my @exonStarts = split( /,\s*/, $exonStarts );
my @exonEnds = split( /,\s*/, $exonEnds );
my $exonCount = scalar(@exonStarts);
# '$rr2' is the RangeRegistry holding exons from the external
# transcript, for one transcript at a time.
my $rr2 = Bio::EnsEMBL::Mapper::RangeRegistry->new();
my $exon_match = 0;
my $coding_match = 0;
my $coding_count = 0;
for ( my $i = 0 ; $i < $exonCount ; ++$i ) {
#-----------------------------------------------------------
# Register the exons from the external database in the same
# was as with the Ensembl exons, and calculate the overlap
# of the external exons with the previously registered
# Ensembl exons.
#-----------------------------------------------------------
my $overlap =
$rr1->overlap_size( 'exon', $exonStarts[$i],
$exonEnds[$i] );
$exon_match +=
$overlap/( $exonEnds[$i] - $exonStarts[$i] + 1 );
$rr2->check_and_register( 'exon', $exonStarts[$i],
$exonEnds[$i] );
if ( !defined($cdsStart) || !defined($cdsEnd) ) {
# Non-coding transcript.
} else {
my $codingStart = ( $exonStarts[$i] > $cdsStart
? $exonStarts[$i]
: $cdsStart );
my $codingEnd =
( $exonEnds[$i] < $cdsEnd ? $exonEnds[$i] : $cdsEnd );
if ( $codingStart < $codingEnd ) {
my $coding_overlap =
$rr1->overlap_size( 'coding', $codingStart,
$codingEnd );
$coding_match +=
$coding_overlap/( $codingEnd - $codingStart + 1 );
$rr2->check_and_register( 'coding', $codingStart,
$codingEnd );
++$coding_count;
}
}
} ## end for ( my $i = 0 ; $i < ...
my $rexon_match = 0;
my $rcoding_match = 0;
my $rcoding_count = 0;
foreach my $exon (@exons) {
#-----------------------------------------------------------
# Calculate the overlap of the Ensembl exons with the
# external exons.
#-----------------------------------------------------------
my $overlap =
$rr2->overlap_size( 'exon', $exon->start(),
$exon->end() );
$rexon_match +=
$overlap/( $exon->end() - $exon->start() + 1 );
if ( $coding_transcript
&& defined( $exon->coding_region_start($transcript) )
&& defined( $exon->coding_region_end($transcript) ) )
{
my $coding_overlap =
$rr2->overlap_size( 'coding',
$exon->coding_region_start(
$transcript),
$exon->coding_region_end(
$transcript)
);
$rcoding_match +=
$coding_overlap/
( $exon->coding_region_end($transcript) -
$exon->coding_region_start($transcript) +
1 );
++$rcoding_count;
}
} ## end foreach my $exon (@exons)
#-------------------------------------------------------------
# Calculate the match score.
#-------------------------------------------------------------
my $score = ( ( $exon_match + $ens_weight*$rexon_match ) +
$coding_weight*(
$coding_match + $ens_weight*$rcoding_match
)
)/( ( $exonCount + $ens_weight*scalar(@exons) ) +
$coding_weight*(
$coding_count + $ens_weight*$rcoding_count
) );
if ( !defined( $transcript_result{$coord_xref_id} )
|| $transcript_result{$coord_xref_id} < $score )
{
$transcript_result{$coord_xref_id} = $score;
}
} ## end while ( $sth->fetch() )
$sth->finish();
#---------------------------------------------------------------
# Apply transcript threshold and pick the best match(es) for
# this transcript.
#---------------------------------------------------------------
my $best_score;
foreach my $coord_xref_id (
sort( { $transcript_result{$b} <=> $transcript_result{$a} }
keys(%transcript_result) ) )
{
# my $score = $transcript_result{$coord_xref_id};
#
# if ( $score > $transcript_score_threshold ) {
# $best_score ||= $score;
#
# if ( sprintf( "%.3f", $score ) eq
# sprintf( "%.3f", $best_score ) )
# {
if ( exists( $unmapped{$coord_xref_id} ) ) {
$mapped{$coord_xref_id} = $unmapped{$coord_xref_id};
delete( $unmapped{$coord_xref_id} );
$mapped{$coord_xref_id}{'reason'} = undef;
$mapped{$coord_xref_id}{'reason_full'} = undef;
}
push( @{ $mapped{$coord_xref_id}{'mapped_to'} }, {
'ensembl_id' => $transcript->dbID(),
'ensembl_object_type' => 'Transcript'
} );
# # This is now a candidate Xref for the gene.
# if ( !defined( $gene_result{$coord_xref_id} )
# || $gene_result{$coord_xref_id} < $score )
# {
# $gene_result{$coord_xref_id} = $score;
# }
#
# } elsif ( exists( $unmapped{$coord_xref_id} ) ) {
# $unmapped{$coord_xref_id}{'reason'} =
# 'Was not best match';
# $unmapped{$coord_xref_id}{'reason_full'} =
# sprintf(
# "Did not top best transcript match score (%.2f)",
# $best_score );
# if ( !defined( $unmapped{$coord_xref_id}{'score'} )
# || $score > $unmapped{$coord_xref_id}{'score'} )
# {
# $unmapped{$coord_xref_id}{'score'} = $score;
# $unmapped{$coord_xref_id}{'ensembl_id'} =
# $transcript->dbID();
# }
# }
#
# } elsif ( exists( $unmapped{$coord_xref_id} )
# && $unmapped{$coord_xref_id}{'reason'} ne
# 'Was not best match' )
# {
# $unmapped{$coord_xref_id}{'reason'} =
# 'Did not meet threshold';
# $unmapped{$coord_xref_id}{'reason_full'} =
# sprintf( "Match score for transcript "
# . "lower than threshold (%.2f)",
# $transcript_score_threshold );
# if ( !defined( $unmapped{$coord_xref_id}{'score'} )
# || $score > $unmapped{$coord_xref_id}{'score'} )
# {
# $unmapped{$coord_xref_id}{'score'} = $score;
# $unmapped{$coord_xref_id}{'ensembl_id'} =
# $transcript->dbID();
# }
# }
} ## end foreach my $coord_xref_id (...
} ## end foreach my $transcript ( sort...
#-----------------------------------------------------------------
# Pick the best match(es) for this gene.
#-----------------------------------------------------------------
my $best_score;
foreach my $coord_xref_id (
sort( { $gene_result{$b} <=> $gene_result{$a} }
keys(%gene_result) ) )
{
# my $score = $gene_result{$coord_xref_id};
#
# $best_score ||= $score;
#
# if (
# sprintf( "%.3f", $score ) eq sprintf( "%.3f", $best_score ) )
# {
push( @{ $mapped{$coord_xref_id}{'mapped_to'} }, {
'ensembl_id' => $gene->dbID(),
'ensembl_object_type' => 'Gene'
} );
# }
}
} ## end while ( my $gene = shift(...
} ## end foreach my $chromosome (@chromosomes)
# Make all dumps. Order is important.
dump_xref( $xref_filename, $xref_id, \%mapped, \%unmapped );
dump_object_xref( $object_xref_filename, $object_xref_id, \%mapped );
dump_unmapped_reason( $unmapped_reason_filename, $unmapped_reason_id,
\%unmapped );
dump_unmapped_object( $unmapped_object_filename, $unmapped_object_id,
$analysis_id, \%unmapped );
if ($do_upload) {
upload_data( 'xref', $xref_filename, $core_dbh );
upload_data( 'object_xref', $object_xref_filename, $core_dbh );
upload_data( 'unmapped_reason', $unmapped_reason_filename,
$core_dbh );
upload_data( 'unmapped_object', $unmapped_object_filename,
$core_dbh );
}
} ## end sub run_coordinatemapping
#-----------------------------------------------------------------------
#-----------------------------------------------------------------------
sub dump_xref {
my ( $filename, $xref_id, $mapped, $unmapped ) = @_;
######################################################################
# Dump for 'xref'. #
######################################################################
my $fh = IO::File->new( '>' . $filename )
or croak( sprintf( "Can not open '%s' for writing", $filename ) );
log_progress( "Dumping for 'xref' to '%s'\n", $filename );
foreach my $xref ( values( %{$unmapped} ), values( %{$mapped} ) ) {
# Assign 'xref_id' to this Xref.
$xref->{'xref_id'} = ++$xref_id;
my $accession = $xref->{'accession'};
my ($version) = ( $accession =~ /\.(\d+)$/ );
$version ||= 0;
$fh->printf("%d\t%d\t%s\t%s\t%d\t%s\t%s\t%s\n",
$xref->{'xref_id'},
$xref->{'external_db_id'},
$accession,
$accession,
$version,
'\N',
'COORDINATE_OVERLAP',
'\N' # FIXME (possibly)
);
}
$fh->close();
log_progress("Dumping for 'xref' done\n");
} ## end sub dump_xref
#-----------------------------------------------------------------------
sub dump_object_xref {
my ( $filename, $object_xref_id, $mapped ) = @_;
######################################################################
# Dump for 'object_xref'. #
######################################################################
my $fh = IO::File->new( '>' . $filename )
or croak( sprintf( "Can not open '%s' for writing", $filename ) );
log_progress( "Dumping for 'object_xref' to '%s'\n", $filename );
foreach my $xref ( values( %{$mapped} ) ) {
foreach my $object_xref ( @{ $xref->{'mapped_to'} } ) {
# Assign 'object_xref_id' to this Object Xref.
$object_xref->{'object_xref_id'} = ++$object_xref_id;
$fh->printf( "%d\t%d\t%s\t%d\t%s\n",
$object_xref->{'object_xref_id'},
$object_xref->{'ensembl_id'},
$object_xref->{'ensembl_object_type'},
$xref->{'xref_id'},
'\N' );
}
}
$fh->close();
log_progress("Dumping for 'object_xref' done\n");
} ## end sub dump_objexref
#-----------------------------------------------------------------------
sub dump_unmapped_reason {
my ( $filename, $unmapped_reason_id, $unmapped ) = @_;
######################################################################
# Dump for 'unmapped_reason'. #
######################################################################
# Create a list of the unique reasons.
my %reasons;
foreach my $xref ( values( %{$unmapped} ) ) {
if ( !exists( $reasons{ $xref->{'reason_full'} } ) ) {
$reasons{ $xref->{'reason_full'} } = {
'summary' => $xref->{'reason'},
'full' => $xref->{'reason_full'}
};
}
}
my $fh = IO::File->new( '>' . $filename )
or croak( sprintf( "Can not open '%s' for writing", $filename ) );
log_progress( "Dumping for 'unmapped_reason' to '%s'\n", $filename );
foreach my $reason (
sort( { $a->{'full'} cmp $b->{'full'} } values(%reasons) ) )
{
# Assign 'unmapped_reason_id' to this reason.
$reason->{'unmapped_reason_id'} = ++$unmapped_reason_id;
$fh->printf( "%d\t%s\t%s\n", $reason->{'unmapped_reason_id'},
$reason->{'summary'}, $reason->{'full'} );
}
$fh->close();
log_progress("Dumping for 'unmapped_reason' done\n");
# Assign reasons to the unmapped Xrefs from %reasons.
foreach my $xref ( values( %{$unmapped} ) ) {
$xref->{'reason'} = $reasons{ $xref->{'reason_full'} };
$xref->{'reason_full'} = undef;
}
} ## end sub dump_unmapped_reason
#-----------------------------------------------------------------------
sub dump_unmapped_object {
my ( $filename, $unmapped_object_id, $analysis_id, $unmapped ) = @_;
######################################################################
# Dump for 'unmapped_object'. #
######################################################################
my $fh = IO::File->new( '>' . $filename )
or croak( sprintf( "Can not open '%s' for writing", $filename ) );
log_progress( "Dumping for 'unmapped_object' to '%s'\n", $filename );
foreach my $xref ( values( %{$unmapped} ) ) {
# Assign 'unmapped_object_id' to this Xref.
$xref->{'unmapped_object_id'} = ++$unmapped_object_id;
$fh->printf(
"%d\t%s\t%s\t%d\t%s\t%d\t%s\t%s\t%s\t%s\t%s\n",
$xref->{'unmapped_object_id'},
'xref',
$analysis_id || '\N', # '\N' (NULL) means no analysis exists
# and uploading this table will fail.
$xref->{'external_db_id'},
$xref->{'accession'},
$xref->{'reason'}->{'unmapped_reason_id'}, (
defined( $xref->{'score'} )
? sprintf( "%.3f", $xref->{'score'} )
: '\N'
),
'\N',
$xref->{'ensembl_id'} || '\N',
( defined( $xref->{'ensembl_id'} ) ? 'Transcript' : '\N' ),
'\N' );
}
$fh->close();
log_progress("Dumping for 'unmapped_object' done\n");
} ## end sub dump_unmapped_object
#-----------------------------------------------------------------------
sub upload_data {
my ( $table_name, $filename, $dbh ) = @_;
######################################################################
# Upload data from a file to a table. #
######################################################################
if ( !-r $filename ) {
croak( sprintf( "Can not open '%s' for reading", $filename ) );
}
log_progress( "Uploading for '%s' from '%s'\n",
$table_name, $filename );
my $sql =
sprintf( "LOAD DATA LOCAL INFILE ? REPLACE INTO TABLE %s", $table_name );
my $sth = $dbh->prepare($sql);
$sth->execute($filename);
log_progress( "Uploading for '%s' done\n", $table_name );
} ## end sub upload_data
#-----------------------------------------------------------------------
sub log_progress {
my ( $fmt, @params ) = @_;
printf( STDERR "COORD==> %s", sprintf( $fmt, @params ) );
}
1;
| {
"content_hash": "19fac36c2daf2b06d0f4921821aa1517",
"timestamp": "",
"source": "github",
"line_count": 769,
"max_line_length": 100,
"avg_line_length": 37.24057217165149,
"alnum_prop": 0.4306515818143725,
"repo_name": "muffato/ensembl",
"id": "eacecd811139b053f2bc5f37e5b3c67c2de9dc8d",
"size": "28638",
"binary": false,
"copies": "1",
"ref": "refs/heads/release/98",
"path": "misc-scripts/xref_mapping/XrefMapper/VBCoordinateMapper.pm",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "7944"
},
{
"name": "HTML",
"bytes": "1434"
},
{
"name": "PLSQL",
"bytes": "13121"
},
{
"name": "PLpgSQL",
"bytes": "290009"
},
{
"name": "Perl",
"bytes": "6433618"
},
{
"name": "Python",
"bytes": "519"
},
{
"name": "SQLPL",
"bytes": "10921"
},
{
"name": "Shell",
"bytes": "14143"
}
],
"symlink_target": ""
} |
<?php
namespace MTD\RegistroBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class MTDRegistroBundle extends Bundle
{
}
| {
"content_hash": "f35c324c6ff14ea1a7afd273fb1fb6b7",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 47,
"avg_line_length": 14.444444444444445,
"alnum_prop": 0.8076923076923077,
"repo_name": "marcelotorrico/SesionesSymfony",
"id": "3e79f265fc07d2280c82f6e4597f243990a92371",
"size": "130",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/MTD/RegistroBundle/MTDRegistroBundle.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "3606"
},
{
"name": "Batchfile",
"bytes": "385"
},
{
"name": "CSS",
"bytes": "14147"
},
{
"name": "HTML",
"bytes": "27088"
},
{
"name": "JavaScript",
"bytes": "3753"
},
{
"name": "PHP",
"bytes": "82604"
},
{
"name": "Shell",
"bytes": "617"
}
],
"symlink_target": ""
} |
package com.mes51.minecraft.mods.necktie.item;
import com.mes51.minecraft.mods.necktie.potion.PotionMuscle;
import com.mes51.minecraft.mods.necktie.recipe.RecipeAir;
import com.mes51.minecraft.mods.necktie.util.Const;
import com.mes51.minecraft.mods.necktie.util.NecktieCreativeTabs;
import com.mes51.minecraft.mods.necktie.util.Util;
import com.mes51.minecraft.mods.necktie.util.enumerable.Enumerable;
import com.mes51.minecraft.mods.necktie.util.enumerable.operator.Predicate;
import com.mes51.minecraft.mods.necktie.util.enumerable.operator.SingleArgFunc;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.common.registry.LanguageRegistry;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.EnumAction;
import net.minecraft.item.Item;
import net.minecraft.item.ItemFood;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.FurnaceRecipes;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.Icon;
import net.minecraft.world.World;
import java.util.List;
/**
* Package: com.mes51.minecraft.mods.necktie.item
* Date: 2014/04/20
* Time: 18:16
*/
public class ItemDopingFood extends Item
{
public static enum SubType
{
RAW_CONSOMME_SOUP(1, 0.6F, 1.0F, new PotionEffect[] { new PotionEffect(Potion.harm.getId(), 0, 1), new PotionEffect(Potion.poison.getId(), 200), new PotionEffect(Potion.hunger.getId(), 200) }, Item.bowlEmpty),
DOPING_CONSOMME_SOUP(3, 2.4F, 1.0F, new PotionEffect[] { new PotionEffect(Potion.harm.getId(), 0, 2), new PotionEffect(Potion.poison.getId(), 600, 1), new PotionEffect(PotionMuscle.getInstance().getId(), 1200), new PotionEffect(Potion.resistance.getId(), 1200, 1) }, Item.bowlEmpty),
PUDDING_INGREDIENTS(1, 0.6F, 1.0F, new PotionEffect[] { }, null),
PUDDING(2, 1.5F, 1.0F, new PotionEffect[] { new PotionEffect(Potion.regeneration.getId(), 100, 0) }, null),
BUCKET_PUDDING_INGREDIENTS(3, 1.5F, 1.0F, new PotionEffect[] { }, Item.bucketEmpty),
BUCKET_PUDDING(10, 3.0F, 1.0F, new PotionEffect[] { new PotionEffect(Potion.regeneration.getId(), 800, 0) }, Item.bucketEmpty),
AIR_MISO_SOUP(-1, 15.0F, 0.1F, new PotionEffect[] { new PotionEffect(PotionMuscle.getInstance().getId(), 600) }, null),
PROTEIN(3, 10.0F, 1.0F, new PotionEffect[] { new PotionEffect(Potion.resistance.getId(), 1200, 1) }, null);
public static SubType byDamage(int damage)
{
SubType[] types = values();
if (types.length <= damage)
{
damage = 0;
}
return types[damage];
}
private int amount = 0;
private float saturation = 0.0F;
private float potionEffectProbability = 0.0F;
private PotionEffect[] effects = null;
private Item container = null;
private SubType(int amount, float saturation, float potionEffectProbability, PotionEffect[] effects, Item container)
{
this.amount = amount;
this.saturation = saturation;
this.potionEffectProbability = potionEffectProbability;
this.effects = effects;
this.container = container;
}
public int getAmount()
{
return this.amount;
}
public float getSaturation()
{
return this.saturation;
}
public float getPotionEffectProbability()
{
return this.potionEffectProbability;
}
public PotionEffect[] getEffects()
{
return this.effects;
}
public Item getContainer()
{
return this.container;
}
public String getUnlocalizedName()
{
return Util.joinString(
Enumerable.from(name().split("_")).select(
new SingleArgFunc<String, String>()
{
@Override
public String func(String value)
{
return Util.pascalize(value);
}
}
).insert(0, Const.DOMAIN).insert(1, ":item"),
""
);
}
public String getDisplayName()
{
return Util.joinString(
Enumerable.from(name().split("_")).select(
new SingleArgFunc<String, String>()
{
@Override
public String func(String value)
{
return Util.pascalize(value);
}
}
),
" "
);
}
public ItemStack getItemStack()
{
return new ItemStack(ItemDopingFood.getInstance(), 1, ordinal());
}
}
private static Item instance = null;
private Icon[] icons = new Icon[SubType.values().length];
public static void register(int itemId)
{
instance = new ItemDopingFood(itemId);
GameRegistry.registerItem(instance, Const.Item.ItemName.DOPING_FOOD);
for (SubType type : SubType.values())
{
LanguageRegistry.addName(type.getItemStack(), type.getDisplayName());
}
}
public static void registerRecipe(int milkId)
{
GameRegistry.addShapelessRecipe(
SubType.RAW_CONSOMME_SOUP.getItemStack(),
new Object[] {
new ItemStack(Item.fermentedSpiderEye, 1),
new ItemStack(Item.rottenFlesh, 1),
new ItemStack(Item.beefCooked, 1),
new ItemStack(Item.potato, 1),
new ItemStack(Item.carrot, 1),
new ItemStack(Item.redstone, 1),
new ItemStack(Item.bowlEmpty, 1)
}
);
FurnaceRecipes.smelting().addSmelting(ItemDopingFood.getInstance().itemID, SubType.RAW_CONSOMME_SOUP.ordinal(), SubType.DOPING_CONSOMME_SOUP.getItemStack(), 0.0F);
GameRegistry.addRecipe(
SubType.PUDDING_INGREDIENTS.getItemStack(),
new Object[] {
"S",
"E",
"M",
'S', new ItemStack(Item.sugar, 1),
'E', new ItemStack(Item.egg, 1),
'M', new ItemStack(milkId, 1, 0)
}
);
FurnaceRecipes.smelting().addSmelting(ItemDopingFood.getInstance().itemID, SubType.PUDDING_INGREDIENTS.ordinal(), SubType.PUDDING.getItemStack(), 0.0F);
GameRegistry.addRecipe(
SubType.BUCKET_PUDDING_INGREDIENTS.getItemStack(),
new Object[] {
"PPP",
"PPP",
" B ",
'P', SubType.PUDDING_INGREDIENTS.getItemStack(),
'B', new ItemStack(Item.bucketEmpty, 1)
}
);
FurnaceRecipes.smelting().addSmelting(ItemDopingFood.getInstance().itemID, SubType.BUCKET_PUDDING_INGREDIENTS.ordinal(), SubType.BUCKET_PUDDING.getItemStack(), 0.0F);
GameRegistry.addRecipe(
new RecipeAir(
SubType.AIR_MISO_SOUP.getItemStack(),
new Predicate<ItemStack>()
{
@Override
public boolean predicate(ItemStack value)
{
return value.getItem() instanceof ItemFood || value.getItem() instanceof ItemDopingFood;
}
}
)
);
GameRegistry.addShapelessRecipe(
SubType.PROTEIN.getItemStack(),
new ItemStack(Item.potato, 1),
new ItemStack(Item.wheat, 1),
new ItemStack(Item.beefRaw, 1),
new ItemStack(Item.porkRaw, 1),
new ItemStack(Item.chickenRaw, 1),
new ItemStack(Item.egg, 1),
new ItemStack(Item.bucketMilk, 1)
);
}
public static Item getInstance()
{
return instance;
}
public ItemDopingFood(int itemId)
{
super(itemId);
setHasSubtypes(true);
setMaxDamage(0);
setMaxStackSize(1);
setCreativeTab(NecktieCreativeTabs.instance);
}
@Override
public String getUnlocalizedName(ItemStack par1ItemStack)
{
return SubType.byDamage(par1ItemStack.getItemDamage()).getUnlocalizedName();
}
@Override
public void getSubItems(int par1, CreativeTabs par2CreativeTabs, List par3List)
{
for (SubType s : SubType.values())
{
par3List.add(s.getItemStack());
}
}
@Override
public void registerIcons(IconRegister par1IconRegister)
{
for (SubType s : SubType.values())
{
this.icons[s.ordinal()] = par1IconRegister.registerIcon(s.getUnlocalizedName());
}
}
@Override
public Icon getIconFromDamage(int par1)
{
return this.icons[par1 % this.icons.length];
}
@Override
public int getMaxItemUseDuration(ItemStack par1ItemStack)
{
return 32;
}
@Override
public EnumAction getItemUseAction(ItemStack par1ItemStack)
{
return EnumAction.eat;
}
@Override
public ItemStack onItemRightClick(ItemStack par1ItemStack, World par2World, EntityPlayer par3EntityPlayer)
{
if (par3EntityPlayer.canEat(true))
{
par3EntityPlayer.setItemInUse(par1ItemStack, this.getMaxItemUseDuration(par1ItemStack));
}
return par1ItemStack;
}
@Override
public ItemStack onEaten(ItemStack par1ItemStack, World par2World, EntityPlayer par3EntityPlayer)
{
SubType type = SubType.byDamage(par1ItemStack.getItemDamage());
if (type.getAmount() > 0)
{
par3EntityPlayer.getFoodStats().addStats(type.getAmount(), type.getSaturation());
}
else
{
par3EntityPlayer.getFoodStats().addExhaustion(type.getSaturation());
}
par2World.playSoundAtEntity(par3EntityPlayer, "random.burp", 0.5F, par2World.rand.nextFloat() * 0.1F + 0.9F);
if (!par2World.isRemote && type.getPotionEffectProbability() >= par2World.rand.nextFloat())
{
for (PotionEffect effect : type.getEffects())
{
par3EntityPlayer.addPotionEffect(new PotionEffect(effect));
}
}
par1ItemStack.stackSize--;
if (type.getContainer() != null)
{
return new ItemStack(type.getContainer(), 1);
}
else
{
return par1ItemStack;
}
}
}
| {
"content_hash": "0039b0ba35732be5e4e48e1b4d81d313",
"timestamp": "",
"source": "github",
"line_count": 318,
"max_line_length": 291,
"avg_line_length": 36.40251572327044,
"alnum_prop": 0.5498445058742225,
"repo_name": "mes51/NecktieMod",
"id": "87e72b1d4166a192ddfaab8beced589d6dafad4c",
"size": "11576",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "com/mes51/minecraft/mods/necktie/item/ItemDopingFood.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "637869"
}
],
"symlink_target": ""
} |
module.exports = {
description: "",
ns: "react-material-ui",
type: "ReactNode",
dependencies: {
npm: {
"material-ui/svg-icons/hardware/headset-mic": require('material-ui/svg-icons/hardware/headset-mic')
}
},
name: "HardwareHeadsetMic",
ports: {
input: {},
output: {
component: {
title: "HardwareHeadsetMic",
type: "Component"
}
}
}
} | {
"content_hash": "d24e8f825b15c60e0ce2ae733cc5a844",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 105,
"avg_line_length": 20.15,
"alnum_prop": 0.5732009925558312,
"repo_name": "nodule/react-material-ui",
"id": "56b9031f8c2eaf923640af244a3ddbd3acb732b4",
"size": "403",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "HardwareHeadsetMic.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1678"
},
{
"name": "JavaScript",
"bytes": "614152"
}
],
"symlink_target": ""
} |
<?php
defined('_JEXEC') or die;
/**
* View for language overrides list
*
* @package Joomla.Administrator
* @subpackage com_languages
* @since 2.5
*/
class LanguagesViewOverrides extends JViewLegacy
{
/**
* The items to list
*
* @var array
* @since 2.5
*/
protected $items;
/**
* The pagination object
*
* @var object
* @since 2.5
*/
protected $pagination;
/**
* The model state
*
* @var object
* @since 2.5
*/
protected $state;
/**
* Displays the view
*
* @param string $tpl The name of the template file to parse
*
* @return void
*
* @since 2.5
*/
public function display($tpl = null)
{
$this->state = $this->get('State');
$this->items = $this->get('Overrides');
$this->languages = $this->get('Languages');
$this->pagination = $this->get('Pagination');
LanguagesHelper::addSubmenu('overrides');
// Check for errors
if (count($errors = $this->get('Errors')))
{
throw new Exception(implode("\n", $errors));
}
$this->addToolbar();
parent::display($tpl);
}
/**
* Adds the page title and toolbar
*
* @return void
*
* @since 2.5
*/
protected function addToolbar()
{
// Get the results for each action
$canDo = JHelperContent::getActions('com_languages');
JToolbarHelper::title(JText::_('COM_LANGUAGES_VIEW_OVERRIDES_TITLE'), 'comments-2 langmanager');
if ($canDo->get('core.create'))
{
JToolbarHelper::addNew('override.add');
}
if ($canDo->get('core.edit') && $this->pagination->total)
{
JToolbarHelper::editList('override.edit');
}
if ($canDo->get('core.delete') && $this->pagination->total)
{
JToolbarHelper::deleteList('', 'overrides.delete');
}
if ($canDo->get('core.admin'))
{
JToolbarHelper::preferences('com_languages');
}
JToolbarHelper::divider();
JToolbarHelper::help('JHELP_EXTENSIONS_LANGUAGE_MANAGER_OVERRIDES');
JHtmlSidebar::setAction('index.php?option=com_languages&view=overrides');
JHtmlSidebar::addFilter(
// @todo need a label here
'',
'filter_language_client',
JHtml::_('select.options', $this->languages, null, 'text', $this->state->get('filter.language_client')),
true
);
$this->sidebar = JHtmlSidebar::render();
}
}
| {
"content_hash": "78227e12929cb250fe0882fb8788539e",
"timestamp": "",
"source": "github",
"line_count": 115,
"max_line_length": 107,
"avg_line_length": 19.62608695652174,
"alnum_prop": 0.6211785556047851,
"repo_name": "monicadragan/HackathonZh2014",
"id": "18932118a039ed52f0aceefbad7deafc3b202af0",
"size": "2502",
"binary": false,
"copies": "310",
"ref": "refs/heads/master",
"path": "joomla/administrator/components/com_languages/views/overrides/view.html.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3051991"
},
{
"name": "JavaScript",
"bytes": "3274459"
},
{
"name": "PHP",
"bytes": "12853925"
},
{
"name": "Perl",
"bytes": "56400"
}
],
"symlink_target": ""
} |
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/bugtracker?serverTimezone=UTC</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">validate</property>
<!-- Names the annotated entity class -->
<mapping class="ru.stqa.pft.mantis.model.UserData"/>
</session-factory>
</hibernate-configuration> | {
"content_hash": "119d0f210a8bf40add8217734fb14707",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 108,
"avg_line_length": 35.64102564102564,
"alnum_prop": 0.6575539568345323,
"repo_name": "allimiko/java_pft",
"id": "56af4f3e059fea729a0cee9ca5a04cb2f1109c2d",
"size": "1390",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "mantis-tests/src/test/resources/hibernate.cfg.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "102002"
},
{
"name": "PHP",
"bytes": "287"
}
],
"symlink_target": ""
} |
D3 - Examples
=============
Program List
------------
[*Tutorials*](/D3/)
- **index**.html
- main page for all tutorials
- **00-dom**.html
- simple elements in the DOM
- **01-svg**.html
- simple demo of SVG elements
- **02-page-template**.html
- empty page for testing d3 code in the console
- **03-data-simple**.html
- how to generate data types and random values
- **04-data-from-csv**.html
- loading data from CSV or JSON files
- may not work without running a server
- **05-create-bars**.html
- creating SVG elements from data
- **06-add-scale**.html
- adding a scale for the data
- **07-add-hover**.html
- add mouse interactivity
- **08-transition-color**.html
- color transition
- **09-data-update**.html
- updating data over time (no transition)
- **10-data-transition**.html
- transition bars to new values
- **11-data-transition-with-key**.html
- use a key with a data join
- **12-exit**.html
- transition bars and remove outgoing elements
Compiling & Running Code
------------------------
Open the HTML files in a web browser.
Loading files in D3 (e.g. data) will require running a web server in some browsers.
Credit
------
The cheat sheet and tutorials provided from the *Introduction to Data Visualization on the Web with D3.js* workshop at IEEE VIS 2012 by **Jerome Cukier**, **Jeff Heer**, & **Scott Murray** and updated to d3v4 by **Sean McKenna**.
| {
"content_hash": "bb97fb55c73f9577b7160ffa8767de23",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 229,
"avg_line_length": 29.53061224489796,
"alnum_prop": 0.6496199032480995,
"repo_name": "mckennapsean/code-examples",
"id": "9ed8ee541ec4328db8b5d72746e4b42a48288bc0",
"size": "1447",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "D3/README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "50174"
},
{
"name": "GLSL",
"bytes": "10031"
},
{
"name": "HTML",
"bytes": "30746"
},
{
"name": "Hack",
"bytes": "973"
},
{
"name": "Java",
"bytes": "137070"
},
{
"name": "PHP",
"bytes": "4985"
},
{
"name": "Processing",
"bytes": "40280"
},
{
"name": "Python",
"bytes": "20047"
},
{
"name": "Ruby",
"bytes": "8977"
},
{
"name": "Scala",
"bytes": "5350"
},
{
"name": "Scheme",
"bytes": "7244"
},
{
"name": "Shell",
"bytes": "552"
},
{
"name": "TeX",
"bytes": "43099"
}
],
"symlink_target": ""
} |
/* globals describe, it, before, after*/
'use strict';
const chai = require('chai');
const driver = require('../index');
const chaiAsPromised = require('chai-as-promised');
chai.should();
chai.use(chaiAsPromised);
const expect = chai.expect;
describe('phantom.addCookie', function() {
let phantom;
before(function(done) {
// starting up phantom may take some time on the first run
this.timeout(5000);
driver.create().then((ph) => {
phantom = ph;
done();
});
});
let cookie1 = {
domain : '.phantomjs.com',
value : 'phantom-cookie-value',
name : 'phantom-cookie',
httponly: false,
path : '/',
secure : false
};
let cookie2 = {
domain : '.google.com',
value : 'google-cookie-value',
name : 'google-cookie',
httponly: false,
path : '/',
secure : false
};
it('should add a cookie and return true', function() {
return phantom.addCookie(cookie1).should.eventually.equal(true);
});
it('should add another cookie and return true', function() {
return phantom.addCookie(cookie2).should.eventually.equal(true);
});
it('should throw error on non-objects', function() {
expect(() => phantom.addCookie()).to.throw();
});
it('should throw error on invalid names', function() {
expect(() => phantom.addCookie({name: 5})).to.throw();
expect(() => phantom.addCookie({name: 'invalid name'})).to.throw();
});
it('should throw error on non-objects', function() {
expect(() => phantom.addCookie({name: 'valid', value: {}})).to.throw();
});
after(function stopPhantom(done) {
phantom.exit().then(() => done()).catch((err) => done(err));
});
});
| {
"content_hash": "98c909670a179b188013832375ae1676",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 75,
"avg_line_length": 25.772727272727273,
"alnum_prop": 0.6055261610817166,
"repo_name": "Reewr/promise-phantom",
"id": "9144f85b7d502d0fafa552f671194e3fc32ce48c",
"size": "1701",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/phantom_add_cookie.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "462"
},
{
"name": "JavaScript",
"bytes": "193467"
}
],
"symlink_target": ""
} |
require 'test_helper'
class BindingTest < Minitest::Test
include CarryOut
class Echo < Unit
parameter :message
def call; @message; end
end
def test_that_binding_is_maintained_for_single_unit
test_message = 'test'
result = CarryOut.call_unit(Echo) do
message echo(test_message)
return_as :echo
end
assert_equal test_message, result.artifacts[:echo]
end
def test_that_binding_is_maintained_in_plan
test_message = 'test'
plan = CarryOut.plan do
call Echo do
message echo(test_message)
return_as :echo
end
end
result = plan.call
assert_equal test_message, result.artifacts[:echo]
end
private
def echo(value)
value
end
end
| {
"content_hash": "692317c49ee65982358b12595cdc61be",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 54,
"avg_line_length": 17.785714285714285,
"alnum_prop": 0.6465863453815262,
"repo_name": "ryanfields/carry_out",
"id": "a0edfad837cdba1dc3a37ed686a4379b544f2ae4",
"size": "747",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/plans/binding_test.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "30621"
},
{
"name": "Shell",
"bytes": "131"
}
],
"symlink_target": ""
} |
require "spec_helper"
require "tiny_server"
describe Chef::Knife::Ssh do
before(:each) do
Chef::Knife::Ssh.load_deps
@server = TinyServer::Manager.new
@server.start
end
after(:each) do
@server.stop
end
let(:ssh_config) { {} }
before do
allow(Net::SSH).to receive(:configuration_for).and_return(ssh_config)
end
describe "identity file" do
context "when knife[:ssh_identity_file] is set" do
before do
Chef::Config[:knife][:ssh_identity_file] = "~/.ssh/aws.rsa"
setup_knife(["*:*", "uptime"])
end
it "uses the ssh_identity_file" do
@knife.run
expect(@knife.config[:ssh_identity_file]).to eq("~/.ssh/aws.rsa")
end
end
context "when knife[:ssh_identity_file] is set and frozen" do
before do
Chef::Config[:knife][:ssh_identity_file] = "~/.ssh/aws.rsa".freeze
setup_knife(["*:*", "uptime"])
end
it "uses the ssh_identity_file" do
@knife.run
expect(@knife.config[:ssh_identity_file]).to eq("~/.ssh/aws.rsa")
end
end
context "when -i is provided" do
before do
Chef::Config[:knife][:ssh_identity_file] = nil
setup_knife(["-i ~/.ssh/aws.rsa", "*:*", "uptime"])
end
it "should use the value on the command line" do
@knife.run
expect(@knife.config[:ssh_identity_file]).to eq("~/.ssh/aws.rsa")
end
it "should override what is set in knife.rb" do
Chef::Config[:knife][:ssh_identity_file] = "~/.ssh/other.rsa"
@knife.merge_configs
@knife.run
expect(@knife.config[:ssh_identity_file]).to eq("~/.ssh/aws.rsa")
end
end
context "when knife[:ssh_identity_file] is not provided]" do
before do
Chef::Config[:knife][:ssh_identity_file] = nil
setup_knife(["*:*", "uptime"])
end
it "uses the default" do
@knife.run
expect(@knife.config[:ssh_identity_file]).to eq(nil)
end
end
end
describe "port" do
context "when -p 31337 is provided" do
before do
setup_knife(["-p 31337", "*:*", "uptime"])
end
it "uses the ssh_port" do
@knife.run
expect(@knife.config[:ssh_port]).to eq("31337")
end
end
end
describe "user" do
context "when knife[:ssh_user] is set" do
before do
Chef::Config[:knife][:ssh_user] = "ubuntu"
setup_knife(["*:*", "uptime"])
end
it "uses the ssh_user" do
@knife.run
expect(@knife.config[:ssh_user]).to eq("ubuntu")
end
end
context "when knife[:ssh_user] is set and frozen" do
before do
Chef::Config[:knife][:ssh_user] = "ubuntu".freeze
setup_knife(["*:*", "uptime"])
end
it "uses the ssh_user" do
@knife.run
expect(@knife.config[:ssh_user]).to eq("ubuntu")
end
end
context "when -x is provided" do
before do
Chef::Config[:knife][:ssh_user] = nil
setup_knife(["-x ubuntu", "*:*", "uptime"])
end
it "should use the value on the command line" do
@knife.run
expect(@knife.config[:ssh_user]).to eq("ubuntu")
end
it "should override what is set in knife.rb" do
Chef::Config[:knife][:ssh_user] = "root"
@knife.merge_configs
@knife.run
expect(@knife.config[:ssh_user]).to eq("ubuntu")
end
end
context "when knife[:ssh_user] is not provided]" do
before do
Chef::Config[:knife][:ssh_user] = nil
setup_knife(["*:*", "uptime"])
end
it "uses the default (current user)" do
@knife.run
expect(@knife.config[:ssh_user]).to eq(nil)
end
end
end
describe "attribute" do
context "when knife[:ssh_attribute] is set" do
before do
Chef::Config[:knife][:ssh_attribute] = "ec2.public_hostname"
setup_knife(["*:*", "uptime"])
end
it "uses the ssh_attribute" do
@knife.run
expect(@knife.get_ssh_attribute({ "target" => "ec2.public_hostname" })).to eq("ec2.public_hostname")
end
end
context "when knife[:ssh_attribute] is not provided" do
before do
Chef::Config[:knife][:ssh_attribute] = nil
setup_knife(["*:*", "uptime"])
end
it "uses the default" do
@knife.run
expect(@knife.get_ssh_attribute({ "fqdn" => "fqdn" })).to eq("fqdn")
end
end
context "when -a ec2.public_public_hostname is provided" do
before do
Chef::Config[:knife][:ssh_attribute] = nil
setup_knife(["-a", "ec2.public_hostname", "*:*", "uptime"])
end
it "should use the value on the command line" do
@knife.run
expect(@knife.config[:ssh_attribute]).to eq("ec2.public_hostname")
end
it "should override what is set in knife.rb" do
# This is the setting imported from knife.rb
Chef::Config[:knife][:ssh_attribute] = "fqdn"
@knife.merge_configs
# Then we run knife with the -a flag, which sets the above variable
setup_knife(["-a", "ec2.public_hostname", "*:*", "uptime"])
@knife.run
expect(@knife.config[:ssh_attribute]).to eq("ec2.public_hostname")
end
end
end
describe "prefix" do
context "when knife[:prefix_attribute] is set" do
before do
Chef::Config[:knife][:prefix_attribute] = "name"
setup_knife(["*:*", "uptime"])
end
it "uses the prefix_attribute" do
@knife.run
expect(@knife.get_prefix_attribute({ "prefix" => "name" })).to eq("name")
end
end
context "when knife[:prefix_attribute] is not provided" do
before do
Chef::Config[:knife][:prefix_attribute] = nil
setup_knife(["*:*", "uptime"])
end
it "falls back to nil" do
@knife.run
expect(@knife.get_prefix_attribute({})).to eq(nil)
end
end
context "when --prefix-attribute ec2.public_public_hostname is provided" do
before do
Chef::Config[:knife][:prefix_attribute] = nil
setup_knife(["--prefix-attribute", "ec2.public_hostname", "*:*", "uptime"])
end
it "should use the value on the command line" do
@knife.run
expect(@knife.config[:prefix_attribute]).to eq("ec2.public_hostname")
end
it "should override what is set in knife.rb" do
# This is the setting imported from knife.rb
Chef::Config[:knife][:prefix_attribute] = "fqdn"
@knife.merge_configs
# Then we run knife with the -b flag, which sets the above variable
setup_knife(["--prefix-attribute", "ec2.public_hostname", "*:*", "uptime"])
@knife.run
expect(@knife.config[:prefix_attribute]).to eq("ec2.public_hostname")
end
end
end
describe "gateway" do
context "when knife[:ssh_gateway] is set" do
before do
Chef::Config[:knife][:ssh_gateway] = "user@ec2.public_hostname"
setup_knife(["*:*", "uptime"])
end
it "uses the ssh_gateway" do
expect(@knife.session).to receive(:via).with("ec2.public_hostname", "user", { append_all_supported_algorithms: true })
@knife.run
expect(@knife.config[:ssh_gateway]).to eq("user@ec2.public_hostname")
end
end
context "when -G user@ec2.public_hostname is provided" do
before do
Chef::Config[:knife][:ssh_gateway] = nil
setup_knife(["-G user@ec2.public_hostname", "*:*", "uptime"])
end
it "uses the ssh_gateway" do
expect(@knife.session).to receive(:via).with("ec2.public_hostname", "user", { append_all_supported_algorithms: true })
@knife.run
expect(@knife.config[:ssh_gateway]).to eq("user@ec2.public_hostname")
end
end
context "when knife[:ssh_gateway_identity] is set" do
before do
Chef::Config[:knife][:ssh_gateway] = "user@ec2.public_hostname"
Chef::Config[:knife][:ssh_gateway_identity] = "~/.ssh/aws-gateway.rsa"
setup_knife(["*:*", "uptime"])
end
it "uses the ssh_gateway_identity file" do
expect(@knife.session).to receive(:via).with("ec2.public_hostname", "user", { append_all_supported_algorithms: true, keys: File.expand_path("#{ENV["HOME"]}/.ssh/aws-gateway.rsa").squeeze("/"), keys_only: true })
@knife.run
expect(@knife.config[:ssh_gateway_identity]).to eq("~/.ssh/aws-gateway.rsa")
end
end
context "when -ssh-gateway-identity is provided and knife[:ssh_gateway] is set" do
before do
Chef::Config[:knife][:ssh_gateway] = "user@ec2.public_hostname"
Chef::Config[:knife][:ssh_gateway_identity] = nil
setup_knife(["--ssh-gateway-identity", "~/.ssh/aws-gateway.rsa", "*:*", "uptime"])
end
it "uses the ssh_gateway_identity file" do
expect(@knife.session).to receive(:via).with("ec2.public_hostname", "user", { append_all_supported_algorithms: true, keys: File.expand_path("#{ENV["HOME"]}/.ssh/aws-gateway.rsa").squeeze("/"), keys_only: true })
@knife.run
expect(@knife.config[:ssh_gateway_identity]).to eq("~/.ssh/aws-gateway.rsa")
end
end
context "when the gateway requires a password" do
before do
Chef::Config[:knife][:ssh_gateway] = nil
setup_knife(["-G user@ec2.public_hostname", "*:*", "uptime"])
allow(@knife.session).to receive(:via) do |host, user, options|
raise Net::SSH::AuthenticationFailed unless options[:password]
end
end
it "should prompt the user for a password" do
expect(@knife.ui).to receive(:ask).with("Enter the password for user@ec2.public_hostname: ", echo: false).and_return("password")
@knife.run
end
end
end
def setup_knife(params = [])
@knife = Chef::Knife::Ssh.new(params)
# We explicitly avoid running #configure_chef, which would read a knife.rb
# if available, but #merge_configs (which is called by #configure_chef) is
# necessary to have default options merged in.
@knife.merge_configs
allow(@knife).to receive(:ssh_command) { 0 }
@api = TinyServer::API.instance
@api.clear
Chef::Config[:node_name] = nil
Chef::Config[:client_key] = nil
Chef::Config[:chef_server_url] = "http://localhost:9000"
@api.post("/search/node?q=*:*&start=0&rows=1000", 200) do
%({"total":1, "start":0, "rows":[{"data": {"fqdn":"the.fqdn", "target": "the_public_hostname"}}]})
end
end
end
| {
"content_hash": "dd4edd0a4cc44735640b34c8b2f72536",
"timestamp": "",
"source": "github",
"line_count": 334,
"max_line_length": 219,
"avg_line_length": 31.505988023952096,
"alnum_prop": 0.5892806233963699,
"repo_name": "higanworks/chef",
"id": "1d4aff15b5acb604431cf0032fb88d95c3d9c9e9",
"size": "11201",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "spec/functional/knife/ssh_spec.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "1588"
},
{
"name": "HTML",
"bytes": "46531"
},
{
"name": "Makefile",
"bytes": "1326"
},
{
"name": "Perl",
"bytes": "64"
},
{
"name": "PowerShell",
"bytes": "34202"
},
{
"name": "Python",
"bytes": "54871"
},
{
"name": "Ruby",
"bytes": "9852328"
},
{
"name": "Shell",
"bytes": "28398"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
<csw:GetRecords xmlns:fgdc="http://www.opengis.net/cat/csw/csdgm" xmlns:csw="http://www.opengis.net/cat/csw/2.0.2" xmlns:ogc="http://www.opengis.net/ogc" service="CSW" version="2.0.2" resultType="results" startPosition="1" maxRecords="5" outputFormat="application/xml" outputSchema="http://www.interlis.ch/INTERLIS2.3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/cat/csw/2.0.2 http://schemas.opengis.net/csw/2.0.2/CSW-discovery.xsd" xmlns:gml="http://www.opengis.net/gml">
<csw:Query typeNames="csw:Record">
<csw:ElementSetName>brief</csw:ElementSetName>
<csw:Constraint version="1.1.0">
<ogc:Filter>
<ogc:BBOX>
<ogc:PropertyName>ows:BoundingBox</ogc:PropertyName>
<gml:Envelope>
<gml:lowerCorner>47 -5</gml:lowerCorner>
<gml:upperCorner>55 20</gml:upperCorner>
</gml:Envelope>
</ogc:BBOX>
</ogc:Filter>
</csw:Constraint>
</csw:Query>
</csw:GetRecords>
| {
"content_hash": "9cd970df2eaf2154bc96e831ae5ea28a",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 525,
"avg_line_length": 62.1764705882353,
"alnum_prop": 0.6773888363292336,
"repo_name": "kalxas/pycsw",
"id": "4b2319124a01946f8db68e7b2a66701445ab0a03",
"size": "1057",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "tests/functionaltests/suites/gm03/post/GetRecords-filter-bbox.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "2909"
},
{
"name": "HTML",
"bytes": "25468"
},
{
"name": "Makefile",
"bytes": "677"
},
{
"name": "Python",
"bytes": "881652"
},
{
"name": "Shell",
"bytes": "129"
},
{
"name": "XSLT",
"bytes": "357"
}
],
"symlink_target": ""
} |
package com.ruiking.coolweather;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | {
"content_hash": "47272f9ddd1b10ac13adddf6ff2e9cd2",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 81,
"avg_line_length": 24.529411764705884,
"alnum_prop": 0.6666666666666666,
"repo_name": "ruiking/coolweather",
"id": "490d7a46863e3b01ce7591c225312070135ee980",
"size": "417",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/test/java/com/ruiking/coolweather/ExampleUnitTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "33036"
}
],
"symlink_target": ""
} |
import React from 'react';
import { useComponents } from '@wq/react';
import PropTypes from 'prop-types';
export default function FieldsetArray({ label, children, addRow }) {
const { View, Button } = useComponents();
return (
<View>
{children}
{addRow && (
<Button onClick={() => addRow()}>{`Add ${label}`}</Button>
)}
</View>
);
}
FieldsetArray.propTypes = {
label: PropTypes.string,
children: PropTypes.node,
addRow: PropTypes.func
};
| {
"content_hash": "e1ce71964420fc1f4ecc50ae9202a220",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 74,
"avg_line_length": 25.285714285714285,
"alnum_prop": 0.568738229755179,
"repo_name": "wq/wq.app",
"id": "a809cdd07415a82adfa20845b557d22d081f6695",
"size": "531",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "packages/material-native/src/components/FieldsetArray.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "555"
},
{
"name": "JavaScript",
"bytes": "472069"
},
{
"name": "Makefile",
"bytes": "419"
},
{
"name": "Python",
"bytes": "7246"
},
{
"name": "Shell",
"bytes": "400"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>aac-tactics: Not compatible</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.10.1 / aac-tactics - 8.12.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
aac-tactics
<small>
8.12.0
<span class="label label-info">Not compatible</span>
</small>
</h1>
<p><em><script>document.write(moment("2020-08-05 02:20:17 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-08-05 02:20:17 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-m4 1 Virtual package relying on m4
coq 8.10.1 Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.05.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.05.0 Official 4.05.0 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.8.1 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "palmskog@gmail.com"
homepage: "https://github.com/coq-community/aac-tactics"
dev-repo: "git+https://github.com/coq-community/aac-tactics.git"
bug-reports: "https://github.com/coq-community/aac-tactics/issues"
license: "LGPL-3.0-or-later"
synopsis: "Coq plugin providing tactics for rewriting universally quantified equations, modulo associative (and possibly commutative) operators"
description: """
This Coq plugin provides tactics for rewriting universally quantified
equations, modulo associativity and commutativity of some operator.
The tactics can be applied for custom operators by registering the
operators and their properties as type class instances. Many common
operator instances, such as for Z binary arithmetic and booleans, are
provided with the plugin."""
build: [make "-j%{jobs}%"]
install: [make "install"]
depends: [
"ocaml" {>= "4.05.0"}
"coq" {>= "8.12" & < "8.13~"}
]
tags: [
"category:Miscellaneous/Coq Extensions"
"category:Computer Science/Decision Procedures and Certified Algorithms/Decision procedures"
"keyword:reflexive tactic"
"keyword:rewriting"
"keyword:rewriting modulo associativity and commutativity"
"keyword:rewriting modulo ac"
"keyword:decision procedure"
"logpath:AAC_tactics"
"date:2020-07-26"
]
authors: [
"Thomas Braibant"
"Damien Pous"
"Fabian Kunze"
]
url {
src: "https://github.com/coq-community/aac-tactics/archive/v8.12.0.tar.gz"
checksum: "sha512=53766331fa4a6bc1b72bedcad58f60a56a984fa7598417db2bf410db5624d80ec089b046b3a45fa4bfd139a4608763446ae07e22e7644fbca78eb2575d976135"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-aac-tactics.8.12.0 coq.8.10.1</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.10.1).
The following dependencies couldn't be met:
- coq-aac-tactics -> coq >= 8.12
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-aac-tactics.8.12.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
<small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small>
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "7e9e45be317f9c2015392f49b4053117",
"timestamp": "",
"source": "github",
"line_count": 181,
"max_line_length": 159,
"avg_line_length": 42.0828729281768,
"alnum_prop": 0.5726664040961008,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "83de5929eda6da494c01775c0df675e1c52c9692",
"size": "7619",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.05.0-2.0.6/released/8.10.1/aac-tactics/8.12.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
require_relative '../../spec_helper'
describe "Thread.handle_interrupt" do
def make_handle_interrupt_thread(interrupt_config, blocking = true)
interrupt_class = Class.new(RuntimeError)
ScratchPad.record []
in_handle_interrupt = Queue.new
can_continue = Queue.new
thread = Thread.new do
begin
Thread.handle_interrupt(interrupt_config) do
begin
in_handle_interrupt << true
if blocking
Thread.pass # Make it clearer the other thread needs to wait for this one to be in #pop
can_continue.pop
else
begin
can_continue.pop(true)
rescue ThreadError
Thread.pass
retry
end
end
rescue interrupt_class
ScratchPad << :interrupted
end
end
rescue interrupt_class
ScratchPad << :deferred
end
end
in_handle_interrupt.pop
if blocking
# Ensure the thread is inside Thread#pop, as if thread.raise is done before it would be deferred
Thread.pass until thread.stop?
end
thread.raise interrupt_class, "interrupt"
can_continue << true
thread.join
ScratchPad.recorded
end
before :each do
Thread.pending_interrupt?.should == false # sanity check
end
it "with :never defers interrupts until exiting the handle_interrupt block" do
make_handle_interrupt_thread(RuntimeError => :never).should == [:deferred]
end
it "with :on_blocking defers interrupts until the next blocking call" do
make_handle_interrupt_thread(RuntimeError => :on_blocking).should == [:interrupted]
make_handle_interrupt_thread({ RuntimeError => :on_blocking }, false).should == [:deferred]
end
it "with :immediate handles interrupts immediately" do
make_handle_interrupt_thread(RuntimeError => :immediate).should == [:interrupted]
end
it "with :immediate immediately runs pending interrupts, before the block" do
Thread.handle_interrupt(RuntimeError => :never) do
current = Thread.current
Thread.new {
current.raise "interrupt immediate"
}.join
Thread.pending_interrupt?.should == true
-> {
Thread.handle_interrupt(RuntimeError => :immediate) {
flunk "not reached"
}
}.should raise_error(RuntimeError, "interrupt immediate")
Thread.pending_interrupt?.should == false
end
end
it "also works with suspended Fibers and does not duplicate interrupts" do
fiber = Fiber.new { Fiber.yield }
fiber.resume
Thread.handle_interrupt(RuntimeError => :never) do
current = Thread.current
Thread.new {
current.raise "interrupt with fibers"
}.join
Thread.pending_interrupt?.should == true
-> {
Thread.handle_interrupt(RuntimeError => :immediate) {
flunk "not reached"
}
}.should raise_error(RuntimeError, "interrupt with fibers")
Thread.pending_interrupt?.should == false
end
fiber.resume
end
it "runs pending interrupts at the end of the block, even if there was an exception raised in the block" do
executed = false
-> {
Thread.handle_interrupt(RuntimeError => :never) do
current = Thread.current
Thread.new {
current.raise "interrupt exception"
}.join
Thread.pending_interrupt?.should == true
executed = true
raise "regular exception"
end
}.should raise_error(RuntimeError, "interrupt exception")
executed.should == true
end
it "supports multiple pairs in the Hash" do
make_handle_interrupt_thread(ArgumentError => :never, RuntimeError => :never).should == [:deferred]
end
end
| {
"content_hash": "a432596cc07688c9de4dcf207b7661c7",
"timestamp": "",
"source": "github",
"line_count": 125,
"max_line_length": 109,
"avg_line_length": 30.104,
"alnum_prop": 0.6404464522986979,
"repo_name": "nobu/rubyspec",
"id": "ea7e81cb989ce21ceef17c0e7727dcf8229309d1",
"size": "3763",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "core/thread/handle_interrupt_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "145966"
},
{
"name": "Ruby",
"bytes": "6187303"
},
{
"name": "Shell",
"bytes": "65"
}
],
"symlink_target": ""
} |
package ircclient
import (
"bufio"
"crypto/tls"
"fmt"
"net"
"strconv"
"strings"
"sync"
"github.com/goshuirc/irc-go/ircmsg"
)
type Socket struct {
Host string
Port int
TLS bool
TLSConfig *tls.Config
Conn net.Conn
ConnLock sync.Mutex
Connected bool
Connecting bool
MessagesIn chan ircmsg.IrcMessage
}
func NewSocket() *Socket {
return &Socket{}
}
func (socket *Socket) Connect() error {
socket.Connected = false
socket.Connecting = true
destination := net.JoinHostPort(socket.Host, strconv.Itoa(socket.Port))
// TODO: Timeouts
var conn net.Conn
var err error
if socket.TLS {
conn, err = tls.Dial("tcp", destination, socket.TLSConfig)
} else {
conn, err = net.Dial("tcp", destination)
}
socket.Connecting = false
if err != nil {
return err
}
socket.Connected = true
socket.Conn = conn
socket.MessagesIn = make(chan ircmsg.IrcMessage)
go socket.readInput()
return nil
}
func (socket *Socket) Close() error {
if socket.Connected {
return socket.Conn.Close()
}
return nil
}
func (socket *Socket) readInput() {
reader := bufio.NewReader(socket.Conn)
for {
line, err := reader.ReadString('\n')
if err != nil {
break
}
line = strings.Trim(line, "\r\n")
println("[S " + socket.Host + "] " + line)
message, parseErr := ircmsg.ParseLine(line)
if parseErr == nil {
socket.MessagesIn <- message
}
}
socket.Connected = false
close(socket.MessagesIn)
}
// WriteLine writes a raw IRC line to the server. Auto appends \n
func (socket *Socket) WriteLine(format string, args ...interface{}) (int, error) {
if !socket.Connected {
return 0, fmt.Errorf("not connected")
}
line := ""
if len(args) == 0 {
line = format
if !strings.HasSuffix(line, "\n") {
line += "\n"
}
} else {
if strings.HasSuffix(format, "\n") {
line = fmt.Sprintf(format, args...)
} else {
line = fmt.Sprintf(format+"\n", args...)
}
}
println("[C " + socket.Host + "] " + strings.Trim(line, "\n"))
return socket.Write([]byte(line))
}
func (socket *Socket) Write(p []byte) (n int, err error) {
socket.ConnLock.Lock()
defer socket.ConnLock.Unlock()
return socket.Conn.Write(p)
}
| {
"content_hash": "95119bfafd04c697f2fc83406cc2f74f",
"timestamp": "",
"source": "github",
"line_count": 118,
"max_line_length": 82,
"avg_line_length": 18.483050847457626,
"alnum_prop": 0.6497019715726731,
"repo_name": "goshuirc/bnc",
"id": "afdb5f1b3bb8f2dc52ab40ac5db37dd23f31345c",
"size": "2274",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lib/ircclient/socket.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "130239"
}
],
"symlink_target": ""
} |
"""
ZFS Storage Appliance NFS Cinder Volume Driver
"""
import base64
import datetime as dt
import errno
from oslo_config import cfg
from oslo_log import log
from oslo_utils import excutils
from oslo_utils import units
from cinder import exception
from cinder.i18n import _, _LE, _LI
from cinder.volume.drivers import nfs
from cinder.volume.drivers.san import san
from cinder.volume.drivers.zfssa import zfssarest
ZFSSA_OPTS = [
cfg.StrOpt('zfssa_data_ip',
help='Data path IP address'),
cfg.StrOpt('zfssa_https_port', default='443',
help='HTTPS port number'),
cfg.StrOpt('zfssa_nfs_mount_options', default='',
help='Options to be passed while mounting share over nfs'),
cfg.StrOpt('zfssa_nfs_pool', default='',
help='Storage pool name.'),
cfg.StrOpt('zfssa_nfs_project', default='NFSProject',
help='Project name.'),
cfg.StrOpt('zfssa_nfs_share', default='nfs_share',
help='Share name.'),
cfg.StrOpt('zfssa_nfs_share_compression', default='off',
choices=['off', 'lzjb', 'gzip-2', 'gzip', 'gzip-9'],
help='Data compression.'),
cfg.StrOpt('zfssa_nfs_share_logbias', default='latency',
choices=['latency', 'throughput'],
help='Synchronous write bias-latency, throughput.'),
cfg.IntOpt('zfssa_rest_timeout',
help='REST connection timeout. (seconds)')
]
LOG = log.getLogger(__name__)
CONF = cfg.CONF
CONF.register_opts(ZFSSA_OPTS)
def factory_zfssa():
return zfssarest.ZFSSANfsApi()
class ZFSSANFSDriver(nfs.NfsDriver):
VERSION = '1.0.0'
volume_backend_name = 'ZFSSA_NFS'
protocol = driver_prefix = driver_volume_type = 'nfs'
def __init__(self, *args, **kwargs):
super(ZFSSANFSDriver, self).__init__(*args, **kwargs)
self.configuration.append_config_values(ZFSSA_OPTS)
self.configuration.append_config_values(san.san_opts)
self.zfssa = None
self._stats = None
def do_setup(self, context):
if not self.configuration.nfs_oversub_ratio > 0:
msg = _("NFS config 'nfs_oversub_ratio' invalid. Must be > 0: "
"%s") % self.configuration.nfs_oversub_ratio
LOG.error(msg)
raise exception.NfsException(msg)
if ((not self.configuration.nfs_used_ratio > 0) and
(self.configuration.nfs_used_ratio <= 1)):
msg = _("NFS config 'nfs_used_ratio' invalid. Must be > 0 "
"and <= 1.0: %s") % self.configuration.nfs_used_ratio
LOG.error(msg)
raise exception.NfsException(msg)
package = 'mount.nfs'
try:
self._execute(package, check_exit_code=False, run_as_root=True)
except OSError as exc:
if exc.errno == errno.ENOENT:
msg = _('%s is not installed') % package
raise exception.NfsException(msg)
else:
raise exc
lcfg = self.configuration
LOG.info(_LI('Connecting to host: %s.'), lcfg.san_ip)
host = lcfg.san_ip
user = lcfg.san_login
password = lcfg.san_password
https_port = lcfg.zfssa_https_port
credentials = ['san_ip', 'san_login', 'san_password', 'zfssa_data_ip']
for cred in credentials:
if not getattr(lcfg, cred, None):
exception_msg = _('%s not set in cinder.conf') % cred
LOG.error(exception_msg)
raise exception.CinderException(exception_msg)
self.zfssa = factory_zfssa()
self.zfssa.set_host(host, timeout=lcfg.zfssa_rest_timeout)
auth_str = base64.encodestring('%s:%s' % (user, password))[:-1]
self.zfssa.login(auth_str)
self.zfssa.create_project(lcfg.zfssa_nfs_pool, lcfg.zfssa_nfs_project,
compression=lcfg.zfssa_nfs_share_compression,
logbias=lcfg.zfssa_nfs_share_logbias)
share_args = {
'sharedav': 'rw',
'sharenfs': 'rw',
'root_permissions': '777',
'compression': lcfg.zfssa_nfs_share_compression,
'logbias': lcfg.zfssa_nfs_share_logbias
}
self.zfssa.create_share(lcfg.zfssa_nfs_pool, lcfg.zfssa_nfs_project,
lcfg.zfssa_nfs_share, share_args)
share_details = self.zfssa.get_share(lcfg.zfssa_nfs_pool,
lcfg.zfssa_nfs_project,
lcfg.zfssa_nfs_share)
mountpoint = share_details['mountpoint']
self.mount_path = lcfg.zfssa_data_ip + ':' + mountpoint
https_path = 'https://' + lcfg.zfssa_data_ip + ':' + https_port + \
'/shares' + mountpoint
LOG.debug('NFS mount path: %s' % self.mount_path)
LOG.debug('WebDAV path to the share: %s' % https_path)
self.shares = {}
mnt_opts = self.configuration.zfssa_nfs_mount_options
self.shares[self.mount_path] = mnt_opts if len(mnt_opts) > 1 else None
# Initialize the WebDAV client
self.zfssa.set_webdav(https_path, auth_str)
# Edit http service so that WebDAV requests are always authenticated
args = {'https_port': https_port,
'require_login': True}
self.zfssa.modify_service('http', args)
self.zfssa.enable_service('http')
def _ensure_shares_mounted(self):
try:
self._ensure_share_mounted(self.mount_path)
except Exception as exc:
LOG.error(_LE('Exception during mounting %s.') % exc)
self._mounted_shares = [self.mount_path]
LOG.debug('Available shares %s' % self._mounted_shares)
def check_for_setup_error(self):
"""Check that driver can login.
Check also for properly configured pool, project and share
Check that the http and nfs services are enabled
"""
lcfg = self.configuration
self.zfssa.verify_pool(lcfg.zfssa_nfs_pool)
self.zfssa.verify_project(lcfg.zfssa_nfs_pool, lcfg.zfssa_nfs_project)
self.zfssa.verify_share(lcfg.zfssa_nfs_pool, lcfg.zfssa_nfs_project,
lcfg.zfssa_nfs_share)
self.zfssa.verify_service('http')
self.zfssa.verify_service('nfs')
def create_snapshot(self, snapshot):
"""Creates a snapshot of a volume."""
LOG.info(_LI('Creating snapshot: %s'), snapshot['name'])
lcfg = self.configuration
snap_name = self._create_snapshot_name()
self.zfssa.create_snapshot(lcfg.zfssa_nfs_pool, lcfg.zfssa_nfs_project,
lcfg.zfssa_nfs_share, snap_name)
src_file = snap_name + '/' + snapshot['volume_name']
try:
self.zfssa.create_snapshot_of_volume_file(src_file=src_file,
dst_file=
snapshot['name'])
except Exception:
with excutils.save_and_reraise_exception():
LOG.debug('Error thrown during snapshot: %s creation' %
snapshot['name'])
finally:
self.zfssa.delete_snapshot(lcfg.zfssa_nfs_pool,
lcfg.zfssa_nfs_project,
lcfg.zfssa_nfs_share, snap_name)
def delete_snapshot(self, snapshot):
"""Deletes a snapshot."""
LOG.info(_LI('Deleting snapshot: %s'), snapshot['name'])
self.zfssa.delete_snapshot_of_volume_file(src_file=snapshot['name'])
def create_volume_from_snapshot(self, volume, snapshot, method='COPY'):
LOG.info(_LI('Creatng volume from snapshot. volume: %s'),
volume['name'])
LOG.info(_LI('Source Snapshot: %s'), snapshot['name'])
self._ensure_shares_mounted()
self.zfssa.create_volume_from_snapshot_file(src_file=snapshot['name'],
dst_file=volume['name'],
method=method)
volume['provider_location'] = self.mount_path
if volume['size'] != snapshot['volume_size']:
try:
self.extend_volume(volume, volume['size'])
except Exception:
vol_path = self.local_path(volume)
exception_msg = (_('Error in extending volume size: '
'Volume: %(volume)s '
'Vol_Size: %(vol_size)d with '
'Snapshot: %(snapshot)s '
'Snap_Size: %(snap_size)d')
% {'volume': volume['name'],
'vol_size': volume['size'],
'snapshot': snapshot['name'],
'snap_size': snapshot['volume_size']})
with excutils.save_and_reraise_exception():
LOG.error(exception_msg)
self._execute('rm', '-f', vol_path, run_as_root=True)
return {'provider_location': volume['provider_location']}
def create_cloned_volume(self, volume, src_vref):
"""Creates a snapshot and then clones the snapshot into a volume."""
LOG.info(_LI('new cloned volume: %s'), volume['name'])
LOG.info(_LI('source volume for cloning: %s'), src_vref['name'])
snapshot = {'volume_name': src_vref['name'],
'volume_id': src_vref['id'],
'volume_size': src_vref['size'],
'name': self._create_snapshot_name()}
self.create_snapshot(snapshot)
return self.create_volume_from_snapshot(volume, snapshot,
method='MOVE')
def _create_snapshot_name(self):
"""Creates a snapshot name from the date and time."""
return ('cinder-zfssa-nfs-snapshot-%s' %
dt.datetime.utcnow().isoformat())
def _get_share_capacity_info(self):
"""Get available and used capacity info for the NFS share."""
lcfg = self.configuration
share_details = self.zfssa.get_share(lcfg.zfssa_nfs_pool,
lcfg.zfssa_nfs_project,
lcfg.zfssa_nfs_share)
free = share_details['space_available']
used = share_details['space_total']
return free, used
def _update_volume_stats(self):
"""Get volume stats from zfssa"""
self._ensure_shares_mounted()
data = {}
backend_name = self.configuration.safe_get('volume_backend_name')
data['volume_backend_name'] = backend_name or self.__class__.__name__
data['vendor_name'] = 'Oracle'
data['driver_version'] = self.VERSION
data['storage_protocol'] = self.protocol
free, used = self._get_share_capacity_info()
capacity = float(free) + float(used)
ratio_used = used / capacity
data['QoS_support'] = False
data['reserved_percentage'] = 0
if ratio_used > self.configuration.nfs_used_ratio or \
ratio_used >= self.configuration.nfs_oversub_ratio:
data['reserved_percentage'] = 100
data['total_capacity_gb'] = float(capacity) / units.Gi
data['free_capacity_gb'] = float(free) / units.Gi
self._stats = data
| {
"content_hash": "5997075a9a224490209d804f61fc32fe",
"timestamp": "",
"source": "github",
"line_count": 292,
"max_line_length": 79,
"avg_line_length": 39.5958904109589,
"alnum_prop": 0.5533644698149109,
"repo_name": "yanheven/cinder",
"id": "721f11c0a507fdb6dd7b40a3e1abfd9bf239f857",
"size": "12177",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "cinder/volume/drivers/zfssa/zfssanfs.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "PLpgSQL",
"bytes": "2511"
},
{
"name": "Python",
"bytes": "10655225"
},
{
"name": "Shell",
"bytes": "8111"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/swipeRefreshLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.v4.widget.SwipeRefreshLayout> | {
"content_hash": "0e0921a822a6a47f9812429ad3c1aff7",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 62,
"avg_line_length": 38.714285714285715,
"alnum_prop": 0.7011070110701108,
"repo_name": "WxSmile/SmileDaily",
"id": "f9ecaa6e70f61cdc791d52c34cbc5e773dc299f2",
"size": "542",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/res/layout/fragment_ganhuos.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "241686"
}
],
"symlink_target": ""
} |
'use strict';
if (process.env.NODE_ENV === 'production') {
module.exports = require('./cjs/react-pg.browser.production.min.server.js');
} else {
module.exports = require('./cjs/react-pg.browser.development.server.js');
}
| {
"content_hash": "10148ab088944a8f1af32e5bf0bfe60f",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 78,
"avg_line_length": 32.285714285714285,
"alnum_prop": 0.6902654867256637,
"repo_name": "yungsters/react",
"id": "175cec16ae3e6b3d446f599b4fb2f44e9672a288",
"size": "226",
"binary": false,
"copies": "8",
"ref": "refs/heads/main",
"path": "packages/react-pg/npm/index.browser.server.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "5225"
},
{
"name": "C++",
"bytes": "44278"
},
{
"name": "CSS",
"bytes": "63657"
},
{
"name": "CoffeeScript",
"bytes": "16826"
},
{
"name": "HTML",
"bytes": "118955"
},
{
"name": "JavaScript",
"bytes": "5908351"
},
{
"name": "Makefile",
"bytes": "189"
},
{
"name": "Python",
"bytes": "259"
},
{
"name": "Shell",
"bytes": "2331"
},
{
"name": "TypeScript",
"bytes": "20868"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Submission 254</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body topmargin="0" leftmargin="0" marginheight="0" marginwidth="0">
<img src="gallery/submissions/254.jpg" height="400">
</body>
</html>
| {
"content_hash": "b2f0d3856819396fc3ed90db25c0c210",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 102,
"avg_line_length": 33.36363636363637,
"alnum_prop": 0.7002724795640327,
"repo_name": "heyitsgarrett/envelopecollective",
"id": "cd489dd06e07173b8d2cb0d9ed99bf7c4a96a2fa",
"size": "367",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "gallery_submission.php-id=254.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "12048"
},
{
"name": "HTML",
"bytes": "110277612"
},
{
"name": "JavaScript",
"bytes": "13527"
}
],
"symlink_target": ""
} |
package net.minecraft.src;
import static net.minecraft.src.AutoRefereeHUD.*;
import java.util.ArrayList;
import java.util.HashMap;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.GL11;
public class AutoRefereeHUDRFWPlayerListGui extends GuiScreen{
private AutoReferee autoReferee;
private ScaledResolution scaledResolution;
private float scale;
private float height;
private void addPlayerButtons(ArrayList<AutoRefereePlayer> players, float xOffset){
float yPos = height + PLAYER_LIST_PLAYERS_Y_OFFSET*scale;
for(AutoRefereePlayer player : players){
this.buttonList.add(new AutoRefereeButton(xOffset + PLAYER_LIST_HEAD_X_OFFSET*scale, yPos + PLAYER_LIST_HEAD_Y_OFFSET*scale, scale, player, "TP"));
this.buttonList.add(new AutoRefereeButton(xOffset + PLAYER_LIST_BUTTONS_OFFSET*scale, yPos, scale, player, "TPDeath"));
this.buttonList.add(new AutoRefereeButton(xOffset + PLAYER_LIST_BUTTONS_OFFSET*scale, yPos + PLAYER_LIST_BED_BUTTON_OFFSET*scale, scale, player, "TPBed"));
this.buttonList.add(new AutoRefereeButton(xOffset + PLAYER_LIST_BUTTONS_OFFSET*scale, yPos + PLAYER_LIST_DOMINATION_Y_OFFSET*scale, scale, player, "VI"));
this.buttonList.add(new AutoRefereeButton(xOffset + PLAYER_LIST_BUTTONS_OFFSET*scale, yPos + PLAYER_LIST_DEATH_INV_BUTTON_OFFSET*scale, scale, player, "VIDeath"));
yPos += PLAYER_LIST_PLAYER_HEIGHT*scale;
}
}
public void initGui(){
autoReferee = AutoReferee.get();
scaledResolution = new ScaledResolution(mc.gameSettings, mc.displayWidth, mc.displayHeight);
scale = (float) (scaledResolution.getScaledHeight() - 45) / (float) PLAYER_LIST_BOX_HEIGHT;
scale = Math.min(scale, (float) (scaledResolution.getScaledWidth()) / (float) (PLAYER_LIST_BOX_WIDTH * 2 + 20));
height = (scaledResolution.getScaledHeight() - 35) / 2 - PLAYER_LIST_BOX_HEIGHT / 2 * scale;
height = Math.max(10, height);
AutoRefereeTeam at1 = autoReferee.getLeftTeam(mc.ingameGUI.updateCounter);
AutoRefereeTeam at2 = autoReferee.getRightTeam(mc.ingameGUI.updateCounter);
if(at1 != null)
addPlayerButtons(autoReferee.getPlayersOfTeam(at1),scaledResolution.getScaledWidth() / 2 - PLAYER_LIST_BOX_WIDTH * scale);
if(at2 != null)
addPlayerButtons(autoReferee.getPlayersOfTeam(at2),scaledResolution.getScaledWidth() / 2);
}
public void drawScreen(int par1, int par2, float par3){
if(!Keyboard.isKeyDown(mc.gameSettings.keyBindPlayerList.keyCode))
mc.displayGuiScreen((GuiScreen) null);
handleMovements();
GL11.glEnable(GL11.GL_ALPHA_TEST);
AutoRefereeTeam at1 = autoReferee.getLeftTeam(mc.ingameGUI.updateCounter);
AutoRefereeTeam at2 = autoReferee.getRightTeam(mc.ingameGUI.updateCounter);
// scale down if too large name
float widthName = 0, widthName2 = 0;
float scaleName = 1.7F;
if (at1 != null)
widthName = mc.fontRenderer.getStringWidth(at1.getName()) * scaleName;
if (at2 != null)
widthName2 = mc.fontRenderer.getStringWidth(at2.getName()) * scaleName;
if (widthName2 > widthName)
widthName = widthName2;
if (widthName > (PLAYER_LIST_BOX_WIDTH - PLAYER_LIST_BOX_PADDING * 2))
scaleName = (PLAYER_LIST_BOX_WIDTH - PLAYER_LIST_BOX_PADDING * 2) / widthName * scaleName;
if (at1 != null) {
GL11.glPushMatrix();
GL11.glTranslatef(scaledResolution.getScaledWidth() / 2 - PLAYER_LIST_BOX_WIDTH * scale, height, 0);
GL11.glScalef(scale, scale, scale);
AutoRefereeHUDRFW.renderTeamInPlayerList(at1, scaleName, mc);
GL11.glPopMatrix();
}
if (at2 != null) {
GL11.glPushMatrix();
GL11.glTranslatef(scaledResolution.getScaledWidth() / 2, height, 0);
GL11.glScalef(scale, scale, scale);
AutoRefereeHUDRFW.renderTeamInPlayerList(at2, scaleName, mc);
GL11.glPopMatrix();
}
super.drawScreen(par1, par2, par3);
}
private void handleMovements(){
this.mc.gameSettings.keyBindForward.pressed = Keyboard.isKeyDown(mc.gameSettings.keyBindForward.keyCode);
this.mc.gameSettings.keyBindBack.pressed = Keyboard.isKeyDown(mc.gameSettings.keyBindBack.keyCode);
this.mc.gameSettings.keyBindLeft.pressed = Keyboard.isKeyDown(mc.gameSettings.keyBindLeft.keyCode);
this.mc.gameSettings.keyBindRight.pressed = Keyboard.isKeyDown(mc.gameSettings.keyBindRight.keyCode);
this.mc.gameSettings.keyBindJump.pressed = Keyboard.isKeyDown(mc.gameSettings.keyBindJump.keyCode);
this.mc.gameSettings.keyBindSneak.pressed = Keyboard.isKeyDown(mc.gameSettings.keyBindSneak.keyCode);
}
protected void actionPerformed(GuiButton guiButton)
{
if (guiButton.getClass() != AutoRefereeButton.class)
return;
AutoRefereeButton button = (AutoRefereeButton) guiButton;
autoReferee.messageServer(button.message);
this.mc.displayGuiScreen((GuiScreen)null);
}
}
| {
"content_hash": "83a498777dfb297cd6ba962193f7d070",
"timestamp": "",
"source": "github",
"line_count": 105,
"max_line_length": 166,
"avg_line_length": 44.96190476190476,
"alnum_prop": 0.7551366235966956,
"repo_name": "rmct/AutoReferee-client",
"id": "3eba47d9a3c22a33851b43db6eddd82cac395d90",
"size": "4721",
"binary": false,
"copies": "1",
"ref": "refs/heads/mod",
"path": "net/minecraft/src/AutoRefereeHUDRFWPlayerListGui.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "458194"
},
{
"name": "Python",
"bytes": "4128"
}
],
"symlink_target": ""
} |
package api
import play.api.data.validation.ValidationError
import play.api.libs.json._
import play.api.libs.functional.syntax._
/**
*
*/
case class ApiSetStatusData(color: models.Color)
object ApiSetStatusData {
implicit val apiSetStatusDataReads: Reads[ApiSetStatusData] =
(__ \ "color")
.read(models.Color.readColor)
.map(ApiSetStatusData.apply(_))
}
/**
*
*/
case class ApiSetTagsData(tags: Seq[models.StreamTag])
object ApiSetTagsData {
implicit val apiSetStatusDataReads: Reads[ApiSetTagsData] =
Reads.list[models.StreamTag]
.filter(ValidationError("Too many tags."))(tags => tags.size <= models.Stream.maxTags)
.filter(ValidationError("Duplicate tags not allowed."))(tags => tags.distinct.size == tags.size)
.map(ApiSetTagsData(_))
}
/**
*
*/
case class ApiCreateStreamData(name: String, uri: String, status: Option[ApiSetStatusData], tags: Option[ApiSetTagsData])
object ApiCreateStreamData {
implicit val apiCreateStreamDataReads: Reads[ApiCreateStreamData] = (
(JsPath \ "name").read[String] and
(JsPath \ "uri").read[String] and
(JsPath \ "status").readNullable[ApiSetStatusData] and
(JsPath \ "tags").readNullable[ApiSetTagsData]
) (ApiCreateStreamData.apply _)
}
| {
"content_hash": "3357be3f1f507657414acf8683620072",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 121,
"avg_line_length": 28.75,
"alnum_prop": 0.7098814229249012,
"repo_name": "mattbierner/blotre",
"id": "8535ff89403f509e276b7d2400694e677fd37440",
"size": "1265",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "app/api/Requests.scala",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "38081"
},
{
"name": "HTML",
"bytes": "54046"
},
{
"name": "Java",
"bytes": "15203"
},
{
"name": "JavaScript",
"bytes": "64810"
},
{
"name": "Scala",
"bytes": "161549"
},
{
"name": "Shell",
"bytes": "239"
}
],
"symlink_target": ""
} |
module Roleable::Resource
def self.included(base)
base.has_many :applied_roles, :as => :resource, :dependent => :destroy
end
# Return a list of users that have the given role for this resource.
# If a list of role names is given, return users with any of those roles for this resource.
#
# ==== Examples
#
# page.subjects_with_role(:editor) # => [user1, user2, ...]
# page.subjects_with_role([:editor, :author]) # => [user1, user2, ...]
#
def subjects_with_role(role_name)
subject_class.joins(:applied_roles).
merge( ::AppliedRole.with_role_name(role_name).with_resource(self) )
end
private
def subject_class
Roleable.configuration.subject_class_name.classify.constantize
end
end
| {
"content_hash": "f24b825fb5a19b7d445ea2afc71559b3",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 93,
"avg_line_length": 28.76923076923077,
"alnum_prop": 0.6644385026737968,
"repo_name": "mcrowe/roleable",
"id": "9193c8076db7bc7034d84980037e4cf34b93e046",
"size": "748",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/roleable/resource.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "16038"
}
],
"symlink_target": ""
} |
goog.provide('shaka.util.MapUtils');
/**
* @namespace shaka.util.MapUtils
* @summary A set of map/object utility functions.
*/
/**
* Returns true if the map is empty; otherwise, returns false.
*
* @param {!Object.<string, T>} object
* @return {boolean}
* @template T
*/
shaka.util.MapUtils.empty = function(object) {
return Object.keys(object).length == 0;
};
/**
* Gets the map's values.
*
* @param {!Object.<string, T>} object
* @return {!Array.<T>}
* @template T
*/
shaka.util.MapUtils.values = function(object) {
return Object.keys(object).map(function(key) { return object[key]; });
};
| {
"content_hash": "f514256eefb2b9f02138f34718e4d9aa",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 72,
"avg_line_length": 19.205882352941178,
"alnum_prop": 0.6125574272588055,
"repo_name": "rodrigoramos/shaka-player",
"id": "a3358ba8c9425d27c4939eb9ad9beac416b83926",
"size": "1307",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/util/map_utils.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "139"
},
{
"name": "CSS",
"bytes": "6475"
},
{
"name": "HTML",
"bytes": "114269"
},
{
"name": "JavaScript",
"bytes": "918945"
},
{
"name": "Python",
"bytes": "3656"
},
{
"name": "Shell",
"bytes": "10958"
}
],
"symlink_target": ""
} |
<?php
/**
* @see Zend_Filter_HtmlEntities
*/
require_once 'Zend/Filter/HtmlEntities.php';
/**
* @category Zend
* @package Zend_Filter
* @subpackage UnitTests
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @group Zend_Filter
*/
class Zend_Filter_HtmlEntitiesTest extends PHPUnit_Framework_TestCase
{
/**
* Zend_Filter_HtmlEntities object
*
* @var Zend_Filter_HtmlEntities
*/
protected $_filter;
/**
* Creates a new Zend_Filter_HtmlEntities object for each test method
*
* @return void
*/
public function setUp()
{
$this->_filter = new Zend_Filter_HtmlEntities();
}
/**
* Ensures that the filter follows expected behavior
*
* @return void
*/
public function testBasic()
{
$valuesExpected = array(
'string' => 'string',
'<' => '<',
'>' => '>',
'\'' => '\'',
'"' => '"',
'&' => '&'
);
foreach ($valuesExpected as $input => $output) {
$this->assertEquals($output, $this->_filter->filter($input));
}
}
/**
* Ensures that getQuoteStyle() returns expected default value
*
* @return void
*/
public function testGetQuoteStyle()
{
$this->assertEquals(ENT_COMPAT, $this->_filter->getQuoteStyle());
}
/**
* Ensures that setQuoteStyle() follows expected behavior
*
* @return void
*/
public function testSetQuoteStyle()
{
$this->_filter->setQuoteStyle(ENT_QUOTES);
$this->assertEquals(ENT_QUOTES, $this->_filter->getQuoteStyle());
}
/**
* Ensures that getCharSet() returns expected default value
*
* @group ZF-8715
* @return void
*/
public function testGetCharSet()
{
$this->assertEquals('UTF-8', $this->_filter->getCharSet());
}
/**
* Ensures that setCharSet() follows expected behavior
*
* @return void
*/
public function testSetCharSet()
{
$this->_filter->setCharSet('UTF-8');
$this->assertEquals('UTF-8', $this->_filter->getCharSet());
}
/**
* Ensures that getDoubleQuote() returns expected default value
*
* @return void
*/
public function testGetDoubleQuote()
{
$this->assertEquals(true, $this->_filter->getDoubleQuote());
}
/**
* Ensures that setDoubleQuote() follows expected behavior
*
* @return void
*/
public function testSetDoubleQuote()
{
$this->_filter->setDoubleQuote(false);
$this->assertEquals(false, $this->_filter->getDoubleQuote());
}
/**
* Ensure that fluent interfaces are supported
*
* @group ZF-3172
*/
public function testFluentInterface()
{
$instance = $this->_filter->setCharSet('UTF-8')->setQuoteStyle(ENT_QUOTES)->setDoubleQuote(false);
$this->assertTrue($instance instanceof Zend_Filter_HtmlEntities);
}
/**
* @group ZF-8995
*/
public function testConfigObject()
{
require_once 'Zend/Config.php';
$options = array('quotestyle' => 5, 'encoding' => 'ISO-8859-1');
$config = new Zend_Config($options);
$filter = new Zend_Filter_HtmlEntities(
$config
);
$this->assertEquals('ISO-8859-1', $filter->getEncoding());
$this->assertEquals(5, $filter->getQuoteStyle());
}
/**
* Ensures that when ENT_QUOTES is set, the filtered value has both 'single' and "double" quotes encoded
*
* @group ZF-8962
* @return void
*/
public function testQuoteStyleQuotesEncodeBoth()
{
$input = "A 'single' and " . '"double"';
$result = 'A 'single' and "double"';
$this->_filter->setQuoteStyle(ENT_QUOTES);
$this->assertEquals($result, $this->_filter->filter($input));
}
/**
* Ensures that when ENT_COMPAT is set, the filtered value has only "double" quotes encoded
*
* @group ZF-8962
* @return void
*/
public function testQuoteStyleQuotesEncodeDouble()
{
$input = "A 'single' and " . '"double"';
$result = "A 'single' and "double"";
$this->_filter->setQuoteStyle(ENT_COMPAT);
$this->assertEquals($result, $this->_filter->filter($input));
}
/**
* Ensures that when ENT_NOQUOTES is set, the filtered value leaves both "double" and 'single' quotes un-altered
*
* @group ZF-8962
* @return void
*/
public function testQuoteStyleQuotesEncodeNone()
{
$input = "A 'single' and " . '"double"';
$result = "A 'single' and " . '"double"';
$this->_filter->setQuoteStyle(ENT_NOQUOTES);
$this->assertEquals($result, $this->_filter->filter($input));
}
/**
* @group ZF-11344
*/
public function testCorrectsForEncodingMismatch()
{
$string = file_get_contents(dirname(__FILE__) . '/_files/latin-1-text.txt');
// restore_error_handler can emit an E_WARNING; let's ignore that, as
// we want to test the returned value
set_error_handler(array($this, 'errorHandler'), E_NOTICE | E_WARNING);
$result = $this->_filter->filter($string);
restore_error_handler();
$this->assertTrue(strlen($result) > 0);
}
/**
* @group ZF-11344
*/
public function testStripsUnknownCharactersWhenEncodingMismatchDetected()
{
$string = file_get_contents(dirname(__FILE__) . '/_files/latin-1-text.txt');
// restore_error_handler can emit an E_WARNING; let's ignore that, as
// we want to test the returned value
set_error_handler(array($this, 'errorHandler'), E_NOTICE | E_WARNING);
$result = $this->_filter->filter($string);
restore_error_handler();
$this->assertContains('""', $result);
}
/**
* @group ZF-11344
*/
public function testRaisesExceptionIfEncodingMismatchDetectedAndFinalStringIsEmpty()
{
$string = file_get_contents(dirname(__FILE__) . '/_files/latin-1-dash-only.txt');
// restore_error_handler can emit an E_WARNING; let's ignore that, as
// we want to test the returned value
// Also, explicit try, so that we don't mess up PHPUnit error handlers
set_error_handler(array($this, 'errorHandler'), E_NOTICE | E_WARNING);
try {
$result = $this->_filter->filter($string);
$this->fail('Expected exception from single non-utf-8 character');
} catch (Zend_Filter_Exception $e) {
$this->assertTrue($e instanceof Zend_Filter_Exception);
}
}
/**
* Null error handler; used when wanting to ignore specific error types
*/
public function errorHandler($errno, $errstr)
{
}
}
| {
"content_hash": "e311f2dcfaedd5000f1e29d2508a7ec1",
"timestamp": "",
"source": "github",
"line_count": 250,
"max_line_length": 116,
"avg_line_length": 28.304,
"alnum_prop": 0.5758903335217637,
"repo_name": "weierophinney/zf1",
"id": "7ffce0a1eb37c91338e9640ab06593803165b60f",
"size": "7793",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "tests/Zend/Filter/HtmlEntitiesTest.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "40638"
},
{
"name": "JavaScript",
"bytes": "30081"
},
{
"name": "PHP",
"bytes": "31409780"
},
{
"name": "PowerShell",
"bytes": "1028"
},
{
"name": "Puppet",
"bytes": "770"
},
{
"name": "Ruby",
"bytes": "10"
},
{
"name": "Shell",
"bytes": "10511"
},
{
"name": "TypeScript",
"bytes": "3445"
}
],
"symlink_target": ""
} |
package pl.touk.nussknacker.engine.api.component
import com.typesafe.config.{Config, ConfigFactory}
import com.vdurmont.semver4j.Semver
import net.ceedubs.ficus.readers.{ArbitraryTypeReader, ValueReader}
import pl.touk.nussknacker.engine.api.process.ProcessObjectDependencies
import pl.touk.nussknacker.engine.version.BuildInfo
/*
Service, SourceFactory, SinkFactory, CustomStreamTransformer
*/
trait Component
object ComponentProviderConfig {
/*
We use own reader, to insert additional config parameters to config field, so that ComponentProviderConfig has shape
{
providerType: "type1"
value1: "abc"
value2: "def"
}
instead of
{
providerType: "type1"
config {
value1: "abc"
value2: "def"
}
}
*/
implicit val reader: ValueReader[ComponentProviderConfig] = new ValueReader[ComponentProviderConfig] {
import net.ceedubs.ficus.Ficus._
private val normalReader = ArbitraryTypeReader.arbitraryTypeValueReader[ComponentProviderConfig]
override def read(config: Config, path: String): ComponentProviderConfig = {
normalReader.read(config, path).copy(config = config.getConfig(path))
}
}
}
case class ComponentProviderConfig( //if not present, we assume providerType is equal to component name
providerType: Option[String],
disabled: Boolean = false,
//TODO: more configurable/extensible way of name customization
componentPrefix: Option[String],
//if not present, we assume that components should be available in all categories
categories: Option[List[String]] = None,
config: Config = ConfigFactory.empty())
/**
* Implementations should be registered with ServiceLoader mechanism. Each provider can be configured multiple times
* (e.g. different DBs, different OpenAPI registrars and so on.
*/
trait ComponentProvider {
def providerName: String
//in some cases e.g. external model/service registry we don't want to resolve registry settings
//on engine/executor side (e.g. on Flink it can be in different network location, or have lower HA guarantees), @see ModelConfigLoader
def resolveConfigForExecution(config: Config): Config
def create(config: Config, dependencies: ProcessObjectDependencies): List[ComponentDefinition]
def isCompatible(version: NussknackerVersion): Boolean
def isAutoLoaded: Boolean = false
}
object NussknackerVersion {
val current: NussknackerVersion = NussknackerVersion(new Semver(BuildInfo.version))
}
case class NussknackerVersion(value: Semver)
case class ComponentDefinition(name: String, component: Component, icon: Option[String] = None, docsUrl: Option[String] = None)
| {
"content_hash": "e5fbff1a069922c25783158bfada7dcd",
"timestamp": "",
"source": "github",
"line_count": 86,
"max_line_length": 136,
"avg_line_length": 33.80232558139535,
"alnum_prop": 0.693842449260406,
"repo_name": "TouK/nussknacker",
"id": "e7a2eb171b80fa60416b60f5a2a05bcd66d198ae",
"size": "2907",
"binary": false,
"copies": "1",
"ref": "refs/heads/staging",
"path": "components-api/src/main/scala/pl/touk/nussknacker/engine/api/component/ComponentProvider.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "3757"
},
{
"name": "Dockerfile",
"bytes": "597"
},
{
"name": "HTML",
"bytes": "3573"
},
{
"name": "Java",
"bytes": "240995"
},
{
"name": "JavaScript",
"bytes": "189903"
},
{
"name": "PLSQL",
"bytes": "269"
},
{
"name": "Scala",
"bytes": "5323010"
},
{
"name": "Shell",
"bytes": "42521"
},
{
"name": "Stylus",
"bytes": "60452"
},
{
"name": "TypeScript",
"bytes": "991644"
}
],
"symlink_target": ""
} |
/*
Highcharts JS v8.0.0 (2019-12-10)
Highcharts 3D funnel module
(c) 2010-2019 Kacper Madej
License: www.highcharts.com/license
*/
(function(a){"object"===typeof module&&module.exports?(a["default"]=a,module.exports=a):"function"===typeof define&&define.amd?define("highcharts/modules/pyramid3d",["highcharts","highcharts/highcharts-3d","highcharts/modules/cylinder","highcharts/modules/funnel3d"],function(b){a(b);a.Highcharts=b;return a}):a("undefined"!==typeof Highcharts?Highcharts:void 0)})(function(a){function b(a,b,c,d){a.hasOwnProperty(b)||(a[b]=d.apply(null,c))}a=a?a._modules:{};b(a,"modules/pyramid3d.src.js",[a["parts/Globals.js"]],
function(a){a=a.seriesType;a("pyramid3d","funnel3d",{reversed:!0,neckHeight:0,neckWidth:0,dataLabels:{verticalAlign:"top"}});""});b(a,"masters/modules/pyramid3d.src.js",[],function(){})});
//# sourceMappingURL=pyramid3d.js.map | {
"content_hash": "4e93feb23e634e0364eb7b3a763a1b51",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 514,
"avg_line_length": 73.25,
"alnum_prop": 0.7246871444823664,
"repo_name": "cdnjs/cdnjs",
"id": "28bd85908bc4d503eb9b00665f69299346792429",
"size": "879",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "ajax/libs/highcharts/8.0.0/modules/pyramid3d.js",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
class _printfunc : public comid::function
{
public:
comid::ct_string id()
{
return "print";
}
int call(comid::parameters& param)
{
for(int i = 0; i < param.count(); i++){
if(param.get(i).id() == "int"){
comid::datatype_integer* s = (comid::datatype_integer*)(¶m.get(i));
std::cout << s->get_value();
}
if(param.get(i).id() == "string"){
comid::datatype_string* s = (comid::datatype_string*)(¶m.get(i));
std::cout << s->get_value();
}
}
}
}printfunc;
int main()
{
comid::binary binary;
comid::memory memory;
comid::vm vm;
// Register
vm.register_function(printfunc);
// Generate
comid::ct_bytecode bytecode;
if(comid::generate("[print] :\"Hello\", \" \", \"world\";", bytecode, vm))
std::cout << "oh no\n";
// Setup program
vm.load(bytecode, binary);
binary.copy_factory_memory(memory);
comid::program program(&binary);
while (!vm.tick(program, memory)){}
return 0;
} | {
"content_hash": "bdde723aba69be8ec77b86f0ad1f05a4",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 75,
"avg_line_length": 21.318181818181817,
"alnum_prop": 0.6087420042643923,
"repo_name": "clman94/comid-script",
"id": "1ba9f9758132a7cc90c81fa325d17fab11443153",
"size": "988",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/examples/print.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "718"
},
{
"name": "C++",
"bytes": "51740"
}
],
"symlink_target": ""
} |
package org.spongepowered.despector.ast.type;
import org.spongepowered.despector.Language;
import org.spongepowered.despector.ast.Annotation;
import org.spongepowered.despector.ast.AstVisitor;
import org.spongepowered.despector.ast.SourceSet;
import org.spongepowered.despector.util.serialization.AstSerializer;
import org.spongepowered.despector.util.serialization.MessagePacker;
import java.io.IOException;
/**
* Represents an interface type.
*/
public class InterfaceEntry extends TypeEntry {
public InterfaceEntry(SourceSet src, Language lang, String name) {
super(src, lang, name);
}
@Override
public String toString() {
return "Interface " + this.name;
}
@Override
public void writeTo(MessagePacker pack) throws IOException {
super.writeTo(pack, 0, AstSerializer.ENTRY_ID_INTERFACE);
pack.endMap();
}
@Override
public void accept(AstVisitor visitor) {
if (visitor instanceof TypeVisitor) {
((TypeVisitor) visitor).visitInterfaceEntry(this);
}
for (FieldEntry field : this.fields.values()) {
field.accept(visitor);
}
for (FieldEntry field : this.static_fields.values()) {
field.accept(visitor);
}
for (MethodEntry method : this.methods.values()) {
method.accept(visitor);
}
for (MethodEntry method : this.static_methods.values()) {
method.accept(visitor);
}
for (Annotation anno : this.annotations.values()) {
anno.accept(visitor);
}
if (visitor instanceof TypeVisitor) {
((TypeVisitor) visitor).visitTypeEnd();
}
}
}
| {
"content_hash": "cbdaae76e5a10af34624e7daac94a549",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 70,
"avg_line_length": 29.413793103448278,
"alnum_prop": 0.6512309495896834,
"repo_name": "Despector/Despector",
"id": "af7cbd58e0d0970c484f6036d8a9ec4ff024a27e",
"size": "2909",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/org/spongepowered/despector/ast/type/InterfaceEntry.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "2100971"
}
],
"symlink_target": ""
} |
using System;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using SampleWorkspacesApp.WorkSpaces;
using WeifenLuo.WinFormsUI.Docking;
namespace SampleWorkspacesApp
{
public partial class MainForm : Form
{
private readonly WorkspacesDock m_WorkspacesDock = new WorkspacesDock();
private readonly DummyTaskList m_MainTaskList = new DummyTaskList();
private readonly DummyToolbox m_MainToolBox = new DummyToolbox();
private readonly DockPanelExt.DeserializeDockContentDelegate m_DeserializeDockContent;
private const string AppConfigFile = "ApplicationDocks.config";
public MainForm()
{
InitializeComponent();
m_DeserializeDockContent = DeserializeDockContent;
//m_MainTaskList.Show(MainDockPanel);
//m_MainToolBox.Show(MainDockPanel);
//m_WorkspacesDock.Show(MainDockPanel);
}
private void MenuItem_NewTaskList_Click(object sender, EventArgs e)
{
WorkspacesDock.WorkSpaceManager().AddWorkItemToActiveWorkSpace(new WorkSpaceItemWindow());
}
private void MainForm_Load(object sender, EventArgs e)
{
RestoreAppConfiguration();
}
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
SaveAppConfiguration();
}
#region Save and Restore Configuration
private void SaveAppConfiguration()
{
var xmlWriter = new XmlTextWriter(AppConfigFile, Encoding.Unicode) { Formatting = Formatting.Indented };
try
{
xmlWriter.WriteStartDocument();
xmlWriter.WriteComment("!!! AUTOMATICALLY GENERATED FILE. DO NOT MODIFY !!!");
xmlWriter.WriteStartElement("ApplicationDocks");
xmlWriter.WriteAttributeString("FormatVersion", PersistorExt.AppConfigFileVersion);
MainDockPanel.Save(xmlWriter);
xmlWriter.WriteEndElement();
xmlWriter.WriteEndDocument();
}
finally
{
xmlWriter.Flush();
xmlWriter.Close();
}
}
private void RestoreAppConfiguration()
{
if (!File.Exists(AppConfigFile))
{
RestoreDefaultConfig();
return;
}
var fs = new FileStream(AppConfigFile, FileMode.Open, FileAccess.Read);
try
{
MainDockPanel.Restore(fs, m_DeserializeDockContent);
}
finally
{
fs.Close();
}
}
private void RestoreDefaultConfig()
{
using (var memoryStream = new MemoryStream(Encoding.Unicode.GetBytes(Properties.Resources.ApplicationDefaultDocks)))
{
MainDockPanel.Restore(memoryStream, m_DeserializeDockContent);
memoryStream.Close();
}
}
private IDockContent DeserializeDockContent(string persistString, XmlTextReader xmlTextReader)
{
if (persistString.Equals(typeof(DummyToolbox).Name))
return RestoreToolBox(xmlTextReader);
if (persistString.Equals(typeof(DummyTaskList).Name))
return RestoreTaskList(xmlTextReader);
if (persistString.Equals(typeof(WorkspacesDock).Name))
return RestoreWorkspacesDock(xmlTextReader);
return null;
}
private IDockContent RestoreWorkspacesDock(XmlTextReader xmlTextReader)
{
m_WorkspacesDock.Init(xmlTextReader);
return m_WorkspacesDock;
}
private IDockContent RestoreTaskList(XmlTextReader xmlTextReader)
{
return m_MainTaskList;
}
private IDockContent RestoreToolBox(XmlTextReader xmlTextReader)
{
return m_MainToolBox;
}
#endregion Save and Restore Configuration
}
}
| {
"content_hash": "0472c5c616442103e293793e3c38ff3d",
"timestamp": "",
"source": "github",
"line_count": 128,
"max_line_length": 128,
"avg_line_length": 32.0234375,
"alnum_prop": 0.6040497682361552,
"repo_name": "nakedboov/DockedWorkspaces",
"id": "f8f05a9fdfc1389fec68a9fcdff56d320094181b",
"size": "4101",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SampleWorkspacesApp/MainForm.cs",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
<?php
namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Util\Tokens;
class FunctionSpacingSniff implements Sniff
{
/**
* The number of blank lines between functions.
*
* @var integer
*/
public $spacing = 2;
/**
* The number of blank lines before the first function in a class.
*
* @var integer
*/
public $spacingBeforeFirst = 2;
/**
* The number of blank lines after the last function in a class.
*
* @var integer
*/
public $spacingAfterLast = 2;
/**
* Original properties as set in a custom ruleset (if any).
*
* @var array|null
*/
private $rulesetProperties = null;
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return [T_FUNCTION];
}//end register()
/**
* Processes this sniff when one of its tokens is encountered.
*
* @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void
*/
public function process(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$previousNonEmpty = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($stackPtr - 1), null, true);
if ($previousNonEmpty !== false
&& $tokens[$previousNonEmpty]['code'] === T_OPEN_TAG
&& $tokens[$previousNonEmpty]['line'] !== 1
) {
// Ignore functions at the start of an embedded PHP block.
return;
}
// If the ruleset has only overridden the spacing property, use
// that value for all spacing rules.
if ($this->rulesetProperties === null) {
$this->rulesetProperties = [];
if (isset($phpcsFile->ruleset->ruleset['Squiz.WhiteSpace.FunctionSpacing']) === true
&& isset($phpcsFile->ruleset->ruleset['Squiz.WhiteSpace.FunctionSpacing']['properties']) === true
) {
$this->rulesetProperties = $phpcsFile->ruleset->ruleset['Squiz.WhiteSpace.FunctionSpacing']['properties'];
if (isset($this->rulesetProperties['spacing']) === true) {
if (isset($this->rulesetProperties['spacingBeforeFirst']) === false) {
$this->spacingBeforeFirst = $this->spacing;
}
if (isset($this->rulesetProperties['spacingAfterLast']) === false) {
$this->spacingAfterLast = $this->spacing;
}
}
}
}
$this->spacing = (int) $this->spacing;
$this->spacingBeforeFirst = (int) $this->spacingBeforeFirst;
$this->spacingAfterLast = (int) $this->spacingAfterLast;
if (isset($tokens[$stackPtr]['scope_closer']) === false) {
// Must be an interface method, so the closer is the semicolon.
$closer = $phpcsFile->findNext(T_SEMICOLON, $stackPtr);
} else {
$closer = $tokens[$stackPtr]['scope_closer'];
}
$isFirst = false;
$isLast = false;
$ignore = ([T_WHITESPACE => T_WHITESPACE] + Tokens::$methodPrefixes);
$prev = $phpcsFile->findPrevious($ignore, ($stackPtr - 1), null, true);
while ($tokens[$prev]['code'] === T_ATTRIBUTE_END) {
// Skip past function attributes.
$prev = $phpcsFile->findPrevious($ignore, ($tokens[$prev]['attribute_opener'] - 1), null, true);
}
if ($tokens[$prev]['code'] === T_DOC_COMMENT_CLOSE_TAG) {
// Skip past function docblocks.
$prev = $phpcsFile->findPrevious($ignore, ($tokens[$prev]['comment_opener'] - 1), null, true);
}
if ($tokens[$prev]['code'] === T_OPEN_CURLY_BRACKET) {
$isFirst = true;
}
$next = $phpcsFile->findNext($ignore, ($closer + 1), null, true);
if (isset(Tokens::$emptyTokens[$tokens[$next]['code']]) === true
&& $tokens[$next]['line'] === $tokens[$closer]['line']
) {
// Skip past "end" comments.
$next = $phpcsFile->findNext($ignore, ($next + 1), null, true);
}
if ($tokens[$next]['code'] === T_CLOSE_CURLY_BRACKET) {
$isLast = true;
}
/*
Check the number of blank lines
after the function.
*/
// Allow for comments on the same line as the closer.
for ($nextLineToken = ($closer + 1); $nextLineToken < $phpcsFile->numTokens; $nextLineToken++) {
if ($tokens[$nextLineToken]['line'] !== $tokens[$closer]['line']) {
break;
}
}
$requiredSpacing = $this->spacing;
$errorCode = 'After';
if ($isLast === true) {
$requiredSpacing = $this->spacingAfterLast;
$errorCode = 'AfterLast';
}
$foundLines = 0;
if ($nextLineToken === ($phpcsFile->numTokens - 1)) {
// We are at the end of the file.
// Don't check spacing after the function because this
// should be done by an EOF sniff.
$foundLines = $requiredSpacing;
} else {
$nextContent = $phpcsFile->findNext(T_WHITESPACE, $nextLineToken, null, true);
if ($nextContent === false) {
// We are at the end of the file.
// Don't check spacing after the function because this
// should be done by an EOF sniff.
$foundLines = $requiredSpacing;
} else {
$foundLines = ($tokens[$nextContent]['line'] - $tokens[$nextLineToken]['line']);
}
}
if ($isLast === true) {
$phpcsFile->recordMetric($stackPtr, 'Function spacing after last', $foundLines);
} else {
$phpcsFile->recordMetric($stackPtr, 'Function spacing after', $foundLines);
}
if ($foundLines !== $requiredSpacing) {
$error = 'Expected %s blank line';
if ($requiredSpacing !== 1) {
$error .= 's';
}
$error .= ' after function; %s found';
$data = [
$requiredSpacing,
$foundLines,
];
$fix = $phpcsFile->addFixableError($error, $closer, $errorCode, $data);
if ($fix === true) {
$phpcsFile->fixer->beginChangeset();
for ($i = $nextLineToken; $i <= $nextContent; $i++) {
if ($tokens[$i]['line'] === $tokens[$nextContent]['line']) {
$phpcsFile->fixer->addContentBefore($i, str_repeat($phpcsFile->eolChar, $requiredSpacing));
break;
}
$phpcsFile->fixer->replaceToken($i, '');
}
$phpcsFile->fixer->endChangeset();
}//end if
}//end if
/*
Check the number of blank lines
before the function.
*/
$prevLineToken = null;
for ($i = $stackPtr; $i >= 0; $i--) {
if ($tokens[$i]['line'] === $tokens[$stackPtr]['line']) {
continue;
}
$prevLineToken = $i;
break;
}
if ($prevLineToken === null) {
// Never found the previous line, which means
// there are 0 blank lines before the function.
$foundLines = 0;
$prevContent = 0;
$prevLineToken = 0;
} else {
$currentLine = $tokens[$stackPtr]['line'];
$prevContent = $phpcsFile->findPrevious(T_WHITESPACE, $prevLineToken, null, true);
if ($tokens[$prevContent]['code'] === T_COMMENT
|| isset(Tokens::$phpcsCommentTokens[$tokens[$prevContent]['code']]) === true
) {
// Ignore comments as they can have different spacing rules, and this
// isn't a proper function comment anyway.
return;
}
while ($tokens[$prevContent]['code'] === T_ATTRIBUTE_END
&& $tokens[$prevContent]['line'] === ($currentLine - 1)
) {
// Account for function attributes.
$currentLine = $tokens[$tokens[$prevContent]['attribute_opener']]['line'];
$prevContent = $phpcsFile->findPrevious(T_WHITESPACE, ($tokens[$prevContent]['attribute_opener'] - 1), null, true);
}
if ($tokens[$prevContent]['code'] === T_DOC_COMMENT_CLOSE_TAG
&& $tokens[$prevContent]['line'] === ($currentLine - 1)
) {
// Account for function comments.
$prevContent = $phpcsFile->findPrevious(T_WHITESPACE, ($tokens[$prevContent]['comment_opener'] - 1), null, true);
}
$prevLineToken = $prevContent;
// Before we throw an error, check that we are not throwing an error
// for another function. We don't want to error for no blank lines after
// the previous function and no blank lines before this one as well.
$prevLine = ($tokens[$prevContent]['line'] - 1);
$i = ($stackPtr - 1);
$foundLines = 0;
$stopAt = 0;
if (isset($tokens[$stackPtr]['conditions']) === true) {
$conditions = $tokens[$stackPtr]['conditions'];
$conditions = array_keys($conditions);
$stopAt = array_pop($conditions);
}
while ($currentLine !== $prevLine && $currentLine > 1 && $i > $stopAt) {
if ($tokens[$i]['code'] === T_FUNCTION) {
// Found another interface or abstract function.
return;
}
if ($tokens[$i]['code'] === T_CLOSE_CURLY_BRACKET
&& $tokens[$tokens[$i]['scope_condition']]['code'] === T_FUNCTION
) {
// Found a previous function.
return;
}
$currentLine = $tokens[$i]['line'];
if ($currentLine === $prevLine) {
break;
}
if ($tokens[($i - 1)]['line'] < $currentLine && $tokens[($i + 1)]['line'] > $currentLine) {
// This token is on a line by itself. If it is whitespace, the line is empty.
if ($tokens[$i]['code'] === T_WHITESPACE) {
$foundLines++;
}
}
$i--;
}//end while
}//end if
$requiredSpacing = $this->spacing;
$errorCode = 'Before';
if ($isFirst === true) {
$requiredSpacing = $this->spacingBeforeFirst;
$errorCode = 'BeforeFirst';
$phpcsFile->recordMetric($stackPtr, 'Function spacing before first', $foundLines);
} else {
$phpcsFile->recordMetric($stackPtr, 'Function spacing before', $foundLines);
}
if ($foundLines !== $requiredSpacing) {
$error = 'Expected %s blank line';
if ($requiredSpacing !== 1) {
$error .= 's';
}
$error .= ' before function; %s found';
$data = [
$requiredSpacing,
$foundLines,
];
$fix = $phpcsFile->addFixableError($error, $stackPtr, $errorCode, $data);
if ($fix === true) {
$nextSpace = $phpcsFile->findNext(T_WHITESPACE, ($prevContent + 1), $stackPtr);
if ($nextSpace === false) {
$nextSpace = ($stackPtr - 1);
}
if ($foundLines < $requiredSpacing) {
$padding = str_repeat($phpcsFile->eolChar, ($requiredSpacing - $foundLines));
$phpcsFile->fixer->addContent($prevLineToken, $padding);
} else {
$nextContent = $phpcsFile->findNext(T_WHITESPACE, ($nextSpace + 1), null, true);
$phpcsFile->fixer->beginChangeset();
for ($i = $nextSpace; $i < $nextContent; $i++) {
if ($tokens[$i]['line'] === $tokens[$prevContent]['line']) {
continue;
}
if ($tokens[$i]['line'] === $tokens[$nextContent]['line']) {
$phpcsFile->fixer->addContentBefore($i, str_repeat($phpcsFile->eolChar, $requiredSpacing));
break;
}
$phpcsFile->fixer->replaceToken($i, '');
}
$phpcsFile->fixer->endChangeset();
}//end if
}//end if
}//end if
}//end process()
}//end class
| {
"content_hash": "5d6967552478ff1984e035852bfe0e7d",
"timestamp": "",
"source": "github",
"line_count": 361,
"max_line_length": 131,
"avg_line_length": 36.66759002770083,
"alnum_prop": 0.4909722746845962,
"repo_name": "jrfnl/PHP_CodeSniffer",
"id": "1f4704b91fd86576e34abbeb07ef1760250a47b5",
"size": "13507",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "src/Standards/Squiz/Sniffs/WhiteSpace/FunctionSpacingSniff.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "833"
},
{
"name": "CSS",
"bytes": "19040"
},
{
"name": "HTML",
"bytes": "658"
},
{
"name": "JavaScript",
"bytes": "58155"
},
{
"name": "PHP",
"bytes": "3959251"
}
],
"symlink_target": ""
} |
namespace osrm
{
namespace engine
{
namespace guidance
{
namespace detail
{
std::pair<short, short> getDepartBearings(const LegGeometry &leg_geometry,
const PhantomNode &source_node,
const bool traversed_in_reverse)
{
BOOST_ASSERT(leg_geometry.locations.size() >= 2);
const auto turn_coordinate = leg_geometry.locations.front();
const auto post_turn_coordinate = *(leg_geometry.locations.begin() + 1);
if (turn_coordinate == post_turn_coordinate)
{
return std::make_pair<short, short>(0, source_node.GetBearing(traversed_in_reverse));
}
return std::make_pair<short, short>(
0,
std::round(util::coordinate_calculation::bearing(turn_coordinate, post_turn_coordinate)));
}
std::pair<short, short> getArriveBearings(const LegGeometry &leg_geometry,
const PhantomNode &target_node,
const bool traversed_in_reverse)
{
BOOST_ASSERT(leg_geometry.locations.size() >= 2);
const auto turn_coordinate = leg_geometry.locations.back();
const auto pre_turn_coordinate = *(leg_geometry.locations.end() - 2);
if (turn_coordinate == pre_turn_coordinate)
{
return std::make_pair<short, short>(target_node.GetBearing(traversed_in_reverse), 0);
}
return std::make_pair<short, short>(
std::round(util::coordinate_calculation::bearing(pre_turn_coordinate, turn_coordinate)), 0);
}
} // ns detail
} // ns engine
} // ns guidance
} // ns detail
| {
"content_hash": "046c8de10db5efe24e99f896cb308ab7",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 100,
"avg_line_length": 36.06818181818182,
"alnum_prop": 0.6238185255198487,
"repo_name": "neilbu/osrm-backend",
"id": "3b0e601cf5e07cf5b6c8affdeb449b6b7a49b104",
"size": "1753",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/engine/guidance/assemble_steps.cpp",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Batchfile",
"bytes": "6637"
},
{
"name": "C++",
"bytes": "3351525"
},
{
"name": "CMake",
"bytes": "100275"
},
{
"name": "Gherkin",
"bytes": "1161970"
},
{
"name": "JavaScript",
"bytes": "203688"
},
{
"name": "Lua",
"bytes": "107115"
},
{
"name": "Makefile",
"bytes": "3170"
},
{
"name": "Python",
"bytes": "22159"
},
{
"name": "Shell",
"bytes": "15158"
}
],
"symlink_target": ""
} |
<?php namespace Phalcon\Mvc\Model\EagerLoading;
use Phalcon\Mvc\Model\Query\Builder;
final class QueryBuilder extends Builder
{
const E_NOT_ALLOWED_METHOD_CALL = 'When eager loading relations queries must return full entities';
public function distinct($distinct)
{
throw new \LogicException(static::E_NOT_ALLOWED_METHOD_CALL);
}
public function columns($columns)
{
throw new \LogicException(static::E_NOT_ALLOWED_METHOD_CALL);
}
public function where($conditions, $bindParams = null, $bindTypes = null)
{
$currentConditions = $this->_conditions;
/**
* Nest the condition to current ones or set as unique
*/
if ($currentConditions) {
$conditions = "(" . $currentConditions . ") AND (" . $conditions . ")";
}
return parent::where($conditions, $bindParams, $bindTypes);
}
}
| {
"content_hash": "05065a58acfd6050c5241664cbced0e9",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 103,
"avg_line_length": 28.40625,
"alnum_prop": 0.6325632563256326,
"repo_name": "twistersfury/incubator",
"id": "7984b785ce90e4b6e158acd5ff2ba1395b080e6c",
"size": "909",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "Library/Phalcon/Mvc/Model/EagerLoading/QueryBuilder.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "PHP",
"bytes": "998766"
},
{
"name": "Shell",
"bytes": "4252"
}
],
"symlink_target": ""
} |
id: 56bbb991ad1ed5201cd392d0
title: Build JavaScript Objects
challengeType: 1
videoUrl: ''
localeTitle: 构建JavaScript对象
---
## Description
<section id="description">您之前可能听说过<code>object</code>这个术语。对象类似于<code>arrays</code> ,除了不使用索引访问和修改数据,您可以通过所谓的<code>properties</code>访问对象中的数据。对象对于以结构化方式存储数据很有用,并且可以表示真实世界对象,如猫。这是一个示例cat对象: <blockquote> var cat = { <br> “名字”:“胡须”, <br> “腿”:4, <br> “尾巴”:1, <br> “敌人”:[“水”,“狗”] <br> }; </blockquote>在此示例中,所有属性都存储为字符串,例如 - <code>"name"</code> , <code>"legs"</code>和<code>"tails"</code> 。但是,您也可以使用数字作为属性。您甚至可以省略单字符串属性的引号,如下所示: <blockquote> var anotherObject = { <br>制作:“福特”, <br> 5:“五”, <br> “模特”:“焦点” <br> }; </blockquote>但是,如果您的对象具有任何非字符串属性,JavaScript将自动将它们作为字符串进行类型转换。 </section>
## Instructions
<section id="instructions">创建一个代表名为<code>myDog</code>的狗的对象,其中包含属性<code>"name"</code> (字符串), <code>"legs"</code> , <code>"tails"</code>和<code>"friends"</code> 。您可以将这些对象属性设置为您想要的任何值,因为<code>"name"</code>是一个字符串, <code>"legs"</code>和<code>"tails"</code>是数字, <code>"friends"</code>是一个数组。 </section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>myDog</code>应该包含属性<code>name</code> ,它应该是一个<code>string</code> 。
testString: 'assert((function(z){if(z.hasOwnProperty("name") && z.name !== undefined && typeof z.name === "string"){return true;}else{return false;}})(myDog), "<code>myDog</code> should contain the property <code>name</code> and it should be a <code>string</code>.");'
- text: <code>myDog</code>应该包含属性<code>legs</code> ,它应该是一个<code>number</code> 。
testString: 'assert((function(z){if(z.hasOwnProperty("legs") && z.legs !== undefined && typeof z.legs === "number"){return true;}else{return false;}})(myDog), "<code>myDog</code> should contain the property <code>legs</code> and it should be a <code>number</code>.");'
- text: <code>myDog</code>应该包含属性<code>tails</code> ,它应该是一个<code>number</code> 。
testString: 'assert((function(z){if(z.hasOwnProperty("tails") && z.tails !== undefined && typeof z.tails === "number"){return true;}else{return false;}})(myDog), "<code>myDog</code> should contain the property <code>tails</code> and it should be a <code>number</code>.");'
- text: <code>myDog</code>应该包含属性<code>friends</code> ,它应该是一个<code>array</code> 。
testString: 'assert((function(z){if(z.hasOwnProperty("friends") && z.friends !== undefined && Array.isArray(z.friends)){return true;}else{return false;}})(myDog), "<code>myDog</code> should contain the property <code>friends</code> and it should be an <code>array</code>.");'
- text: <code>myDog</code>应该只包含所有给定的属性。
testString: 'assert((function(z){return Object.keys(z).length === 4;})(myDog), "<code>myDog</code> should only contain all the given properties.");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
// Example
var ourDog = {
"name": "Camper",
"legs": 4,
"tails": 1,
"friends": ["everything!"]
};
// Only change code below this line.
var myDog = {
};
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>
| {
"content_hash": "a1afa1a3a01b76da8859d91df4d3301d",
"timestamp": "",
"source": "github",
"line_count": 79,
"max_line_length": 604,
"avg_line_length": 41.25316455696203,
"alnum_prop": 0.6775084381712182,
"repo_name": "BhaveshSGupta/FreeCodeCamp",
"id": "9159f9ed1aed0cf812e286c2499b928cde0d1907",
"size": "4045",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/build-javascript-objects.chinese.md",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "71786"
},
{
"name": "HTML",
"bytes": "17627"
},
{
"name": "JavaScript",
"bytes": "1003613"
},
{
"name": "Shell",
"bytes": "340"
}
],
"symlink_target": ""
} |
//////////////////////////////////////////////////////////////////////////////
// INCLUDES
//////////////////////////////////////////////////////////////////////////////
#include <assert.h>
#include <malloc.h>
#include <string.h>
#include <stdio.h>
#include "apx/client_connection.h"
#include "apx/numheader.h"
#include "apx/file.h"
#include "apx/remotefile.h"
#include "apx/client.h"
#include "apx/client_internal.h"
#ifdef MEM_LEAK_CHECK
#include "CMemLeak.h"
#else
#define vfree free
#endif
//////////////////////////////////////////////////////////////////////////////
// PRIVATE CONSTANTS AND DATA TYPES
//////////////////////////////////////////////////////////////////////////////
#define MAX_HEADER_LEN 128
//////////////////////////////////////////////////////////////////////////////
// PRIVATE FUNCTION PROTOTYPES
//////////////////////////////////////////////////////////////////////////////
static void send_greeting_header(apx_clientConnection_t* self);
static apx_error_t remote_file_published_notification(apx_clientConnection_t* self, apx_file_t* file);
static apx_error_t process_new_require_port_data_file(apx_clientConnection_t* self, apx_file_t* file);
static apx_error_t remote_file_write_notification(apx_clientConnection_t* self, apx_file_t* file, uint32_t offset, uint8_t const* data, apx_size_t size);
static uint8_t const* parse_message(apx_clientConnection_t* self, uint8_t const* begin, uint8_t const* end, apx_error_t* error_code);
static bool is_greeting_accepted(uint8_t const* msg_data, apx_size_t msg_size, apx_error_t* error_code);
//////////////////////////////////////////////////////////////////////////////
// PRIVATE VARIABLES
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
// PUBLIC FUNCTIONS
//////////////////////////////////////////////////////////////////////////////
apx_error_t apx_clientConnection_create(apx_clientConnection_t* self, apx_connectionBaseVTable_t* base_connection_vtable, apx_connectionInterface_t* connection_interface)
{
if (self != 0)
{
apx_error_t error_code;
//init non-overridable virtual functions
base_connection_vtable->node_created_notification = NULL; //Only used in server mode
base_connection_vtable->require_port_write_notification = apx_clientConnection_vrequire_port_write_notification;
connection_interface->remote_file_published_notification = apx_clientConnection_vremote_file_published_notification;
connection_interface->remote_file_write_notification = apx_clientConnection_vremote_file_write_notification;
error_code = apx_connectionBase_create(&self->base, APX_CLIENT_MODE, base_connection_vtable, connection_interface);
self->is_greeting_accepted = false;
self->client = NULL;
self->last_error = APX_NO_ERROR;
//apx_connectionBase_setEventHandler(&self->base, apx_clientConnection_defaultEventHandler, (void*) self);
return error_code;
}
return APX_INVALID_ARGUMENT_ERROR;
}
void apx_clientConnection_destroy(apx_clientConnection_t *self)
{
if (self != 0)
{
apx_connectionBase_destroy(&self->base);
}
}
apx_fileManager_t* apx_clientConnection_get_file_manager(apx_clientConnection_t* self)
{
if (self != 0)
{
return apx_connectionBase_get_file_manager(&self->base);
}
return NULL;
}
void apx_clientConnection_start(apx_clientConnection_t* self)
{
(void)self;
}
void apx_clientConnection_close(apx_clientConnection_t* self)
{
(void)self;
}
uint32_t apx_clientConnection_get_total_bytes_received(apx_clientConnection_t* self)
{
(void)self;
return 0u;
}
uint32_t apx_clientConnection_get_total_bytes_sent(apx_clientConnection_t* self)
{
(void)self;
return 0u;
}
/*
void apx_clientConnection_default_event_handler(void* arg, apx_event_t* event)
{
(void)arg;
(void)event;
}
void* apx_clientConnection_register_event_listener(apx_clientConnection_t* self, apx_connectionEventListener_t* listener)
{
(void)self;
(void)listener;
return NULL;
}
void apx_clientConnection_unregister_event_listener(apx_clientConnection_t* self, void* handle)
{
(void)self;
(void)handle;
}
*/
void apx_clientConnection_greeting_header_accepted_notification(apx_clientConnection_t* self)
{
if (self != NULL)
{
self->is_greeting_accepted = true;
apx_fileManager_connected(&self->base.file_manager);
}
}
void apx_clientConnection_connected_notification(apx_clientConnection_t* self)
{
if (self != NULL)
{
self->is_greeting_accepted = false;
send_greeting_header(self);
if (self->client != NULL)
{
apx_clientInternal_connect_notification(self->client, self);
}
}
}
void apx_clientConnection_disconnected_notification(apx_clientConnection_t* self)
{
if (self != NULL)
{
if (self->client != NULL)
{
apx_clientInternal_disconnect_notification(self->client, self);
}
}
}
void apx_clientConnection_attach_node_manager(apx_clientConnection_t* self, apx_nodeManager_t* node_manager)
{
if (self != NULL)
{
apx_connectionBase_attach_node_manager(&self->base, node_manager);
}
}
apx_nodeManager_t* apx_clientConnection_get_node_manager(apx_clientConnection_t* self)
{
if (self != NULL)
{
return apx_connectionBase_get_node_manager(&self->base);
}
return NULL;
}
void apx_clientConnection_set_client(apx_clientConnection_t* self, struct apx_client_tag* client)
{
if (self != NULL)
{
self->client = client;
}
}
int apx_clientConnection_on_data_received(apx_clientConnection_t* self, uint8_t const* data, apx_size_t data_size, apx_size_t* parse_len)
{
if ( (self != NULL) && (data != NULL) && (data_size > 0u) && (parse_len != NULL))
{
apx_size_t total_parse_len = 0u;
uint8_t const* next = data;
uint8_t const* end = data + data_size;
while (next < end)
{
uint8_t const* result;
apx_error_t error_code = APX_NO_ERROR;
result = parse_message(self, next, end, &error_code);
if (error_code == APX_NO_ERROR)
{
assert((result >= next) && (result <= end));
if (result == next)
{
// No more complete messages can be parsed. There may be a partial
// message left in buffer, but we leave it in the buffer until
// more data has arrived.
break;
}
next = result;
total_parse_len = (apx_size_t) (next - data);
assert(total_parse_len <= data_size);
}
else
{
self->last_error = error_code;
return -1;
}
}
*parse_len = total_parse_len;
return 0;
}
return -1;
}
apx_error_t apx_clientConnection_attach_node_instance(apx_clientConnection_t* self, apx_nodeInstance_t* node_instance)
{
if ((self != NULL) && (node_instance != NULL))
{
apx_fileManager_t* file_manager = apx_connectionBase_get_file_manager(&self->base);
assert(file_manager != NULL);
return apx_nodeInstance_attach_to_file_manager(node_instance, file_manager);
}
return APX_INVALID_ARGUMENT_ERROR;
}
void apx_clientConnection_vrequire_port_write_notification(void* arg, apx_portInstance_t* port_instance, uint8_t const* data, apx_size_t size)
{
apx_clientConnection_t* self = (apx_clientConnection_t*)arg;
if ( (self != NULL) && (port_instance != NULL) && (self->client != NULL))
{
apx_clientInternal_require_port_write_notification(self->client, self, port_instance, data, size);
}
}
//ConnectionInterface API
apx_error_t apx_clientConnection_vremote_file_published_notification(void* arg, apx_file_t* file)
{
return remote_file_published_notification((apx_clientConnection_t*)arg, file);
}
apx_error_t apx_clientConnection_vremote_file_write_notification(void* arg, apx_file_t* file, uint32_t offset, uint8_t const* data, apx_size_t size)
{
return remote_file_write_notification((apx_clientConnection_t*)arg, file, offset, data, size);
}
#ifdef UNIT_TEST
void apx_clientConnection_run(apx_clientConnection_t* self)
{
if (self != 0)
{
//apx_connectionBase_runAll(&self->base);
apx_fileManager_run(&self->base.file_manager);
}
}
#endif
//////////////////////////////////////////////////////////////////////////////
// PRIVATE FUNCTIONS
//////////////////////////////////////////////////////////////////////////////
static void send_greeting_header(apx_clientConnection_t* self)
{
int32_t greeting_size;
apx_connectionInterface_t const* connection;
int num_header_format = 32;
char greeting[RMF_GREETING_MAX_LEN];
char* p = &greeting[0];
strcpy(greeting, RMF_GREETING_START);
p += strlen(greeting);
p += sprintf(p, "%s%d\n\n", RMF_NUMHEADER_FORMAT_HDR, num_header_format);
greeting_size = (int32_t)(p - greeting);
connection = apx_connectionBase_get_connection(&self->base);
if (connection != NULL)
{
int32_t bytes_available = 0;
assert((connection->transmit_begin != NULL) && (connection->transmit_end != NULL) && (connection->transmit_direct_message != NULL));
connection->transmit_begin(connection->arg);
connection->transmit_direct_message(connection->arg, (uint8_t const*)greeting, greeting_size, &bytes_available);
connection->transmit_end(connection->arg);
}
}
static apx_error_t remote_file_published_notification(apx_clientConnection_t* self, apx_file_t* file)
{
if ((self != NULL) && (file != NULL))
{
#if APX_DEBUG_ENABLE
printf("[CLIENT-CONNECTION] remote_file_published_notification: \"%s\"(%d)\n", apx_file_get_name(file), apx_file_get_apx_file_type(file));
#endif
if (apx_file_get_apx_file_type(file) == APX_REQUIRE_PORT_DATA_FILE_TYPE)
{
return process_new_require_port_data_file(self, file);
}
//TODO: Add generic handling of new file types
return APX_NO_ERROR;
}
return APX_INVALID_ARGUMENT_ERROR;
}
static apx_error_t process_new_require_port_data_file(apx_clientConnection_t* self, apx_file_t* file)
{
assert((self != NULL) && (file != NULL));
char* base_name = rmf_fileInfo_base_name(apx_file_get_file_info(file));
if (base_name != NULL)
{
assert(self->base.node_manager != NULL);
apx_nodeInstance_t* node_instance = apx_nodeManager_find(self->base.node_manager, base_name);
if (node_instance != NULL)
{
free(base_name);
return apx_nodeInstance_remote_file_published_notification(node_instance, file);
}
else
{
#if APX_DEBUG_ENABLE
printf("Node not found: \"%s\"\n", base_name);
#endif
free(base_name);
}
}
else
{
return APX_MEM_ERROR;
}
return APX_NO_ERROR;
}
static apx_error_t remote_file_write_notification(apx_clientConnection_t* self, apx_file_t* file, uint32_t offset, uint8_t const* data, apx_size_t size)
{
if ( (self != NULL) && (file != NULL) )
{
return apx_file_write_notify(file, offset, data, (uint32_t)size);
}
return APX_INVALID_ARGUMENT_ERROR;
}
static uint8_t const* parse_message(apx_clientConnection_t* self, uint8_t const* begin, uint8_t const* end, apx_error_t* error_code)
{
uint8_t const* msg_end = NULL;
*error_code = APX_NO_ERROR;
if (begin < end)
{
uint32_t msg_size = 0u;
uint8_t const* result = numheader_decode32(begin, end, &msg_size);
if (result == NULL)
{
*error_code = APX_PARSE_ERROR;
return NULL;
}
else if (result == begin)
{
//Not enough bytes in buffer, try later when more data has been received
return begin;
}
else
{
uint8_t const* msg_data = result;
msg_end = msg_data + msg_size;
#if APX_DEBUG_ENABLE
apx_size_t const header_size = (apx_size_t)(msg_data - begin);
printf("[CLIENT-CONNECTION]: Received message: (%d+%d) bytes\n", (int)header_size, (int)msg_size);
#endif
if (msg_end <= end)
{
if (self->is_greeting_accepted)
{
*error_code = apx_connectionBase_message_received(&self->base, msg_data, msg_size);
}
else
{
if (is_greeting_accepted(msg_data, msg_size, error_code))
{
apx_clientConnection_greeting_header_accepted_notification(self);
}
else
{
return NULL;
}
}
}
else
{
//Message not complete, try again later
return begin;
}
}
}
else
{
*error_code = APX_PARSE_ERROR;
return NULL;
}
return msg_end;
}
static bool is_greeting_accepted(uint8_t const* msg_data, apx_size_t msg_size, apx_error_t* error_code)
{
uint32_t address;
bool more_bit = false;
uint8_t const* const msg_end = msg_data + msg_size;
apx_size_t header_size = rmf_address_decode(msg_data, msg_data + msg_size, &address, &more_bit);
if (address == RMF_CMD_AREA_START_ADDRESS)
{
uint32_t cmd_type = 0u;
apx_size_t decode_size = rmf_decode_cmd_type(msg_data + header_size, msg_end, &cmd_type);
if ((decode_size == RMF_CMD_TYPE_SIZE) && (cmd_type ==RMF_CMD_ACK_MSG))
{
return true;
}
}
else
{
*error_code = APX_INVALID_MSG_ERROR;
}
return false;
}
| {
"content_hash": "7e690f936ceac1b8944c669c86bbdf3c",
"timestamp": "",
"source": "github",
"line_count": 426,
"max_line_length": 170,
"avg_line_length": 32.744131455399064,
"alnum_prop": 0.5819772026668578,
"repo_name": "cogu/c-apx",
"id": "b4479e8ee3aab51ea742a06306d4febbc5525ebf",
"size": "15368",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "apx/src/client_connection.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "2372914"
},
{
"name": "C++",
"bytes": "14856"
},
{
"name": "CMake",
"bytes": "16027"
},
{
"name": "Python",
"bytes": "2137"
}
],
"symlink_target": ""
} |
package systems.comodal.hash.gen;
import systems.comodal.hash.api.Hash;
import systems.comodal.hash.Skein1024_512;
import systems.comodal.hash.api.HashFactory;
import systems.comodal.hash.base.ReverseHash;
public final class ReverseSkein1024_512 extends ReverseHash implements Skein1024_512 {
public ReverseSkein1024_512(final byte[] data, final int offset) {
super(data, offset);
}
@Override
public HashFactory<Skein1024_512> getHashFactory() {
return FACTORY;
}
@Override
public boolean equals(final Object other) {
return this == other || other != null && other instanceof Skein1024_512
&& ((Hash) other).digestEqualsReverse(data, offset);
}
} | {
"content_hash": "a354e6f9b38a4a2bc3257c028f6026ee",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 86,
"avg_line_length": 28.625,
"alnum_prop": 0.74235807860262,
"repo_name": "comodal/hash-overlay",
"id": "0fb190ca55ca2bf138b6b588021f49ff74954d05",
"size": "687",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/systems.comodal.hash_overlay/systems/comodal/hash/gen/ReverseSkein1024_512.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "13425"
},
{
"name": "Java",
"bytes": "388892"
}
],
"symlink_target": ""
} |
package edu.vandy.common;
import android.content.Context;
import android.util.Log;
/**
* This Activity provides a framework for mediating access to a object
* residing in the Presenter layer in the Model-View-Presenter (MVP)
* pattern. It automatically handles runtime configuration changes in
* conjunction with an instance of PresenterType, which must implement
* the PresenterOps interface. It extends LifecycleLoggingActivity so
* that all lifecycle hook method calls are automatically logged. It
* also implements the ContextView interface that provides access to
* the Activity and Application contexts in the View layer.
*
* The three types used by a GenericActivity are the following:
* <ol>
* <li><code>RequiredViewOps</code>, the class or interface that
* defines the methods available to the Presenter object from the
* View layer.</li>
* <li><code>ProvidedPresenterOps</code>, the class or interface
* that defines the methods available to the View layer from the
* Presenter object.</li>
* <li><code>PresenterType</code>, the class created/used by the
* GenericActivity framework to implement an Presenter object.</li>
* </ol>
*/
public abstract class GenericActivity<RequiredViewOps,
ProvidedPresenterOps,
PresenterType extends PresenterOps<RequiredViewOps>>
extends LifecycleLoggingActivity
implements ContextView {
/**
* Used to retain the ProvidedPresenterOps state between runtime
* configuration changes.
*/
private final RetainedFragmentManager mRetainedFragmentManager
= new RetainedFragmentManager(this.getFragmentManager(),
TAG);
/**
* Instance of the Presenter type.
*/
private PresenterType mPresenterInstance;
/**
* Initialize or reinitialize the Presenter layer. This must be
* called *after* the onCreate(Bundle saveInstanceState) method.
*
* @param opsType
* Class object that's used to create a Presenter object.
* @param view
* Reference to the RequiredViewOps object in the View layer.
*/
public void onCreate(Class<PresenterType> opsType,
RequiredViewOps view) {
// Handle configuration-related events, including the initial
// creation of an Activity and any subsequent runtime
// configuration changes.
try {
// If this method returns true it's the first time the
// Activity has been created.
if (mRetainedFragmentManager.firstTimeIn()) {
Log.d(TAG,
"First time calling onCreate()");
// Initialize the GenericActivity fields.
initialize(opsType,
view);
} else {
Log.d(TAG,
"Second (or subsequent) time calling onCreate()");
// The RetainedFragmentManager was previously
// initialized, which means that a runtime
// configuration change occurred.
reinitialize(opsType,
view);
}
} catch (InstantiationException
| IllegalAccessException e) {
Log.d(TAG,
"onCreate() "
+ e);
// Propagate this as a runtime exception.
throw new RuntimeException(e);
}
}
/**
* Return the initialized ProvidedPresenterOps instance for use by
* application logic in the View layer.
*/
@SuppressWarnings("unchecked")
public ProvidedPresenterOps getPresenter() {
return (ProvidedPresenterOps) mPresenterInstance;
}
/**
* Return the RetainedFragmentManager.
*/
public RetainedFragmentManager getRetainedFragmentManager() {
return mRetainedFragmentManager;
}
/**
* Initialize the GenericActivity fields.
* @throws IllegalAccessException
* @throws InstantiationException
*/
private void initialize(Class<PresenterType> opsType,
RequiredViewOps view)
throws InstantiationException, IllegalAccessException {
// Create the PresenterType object.
mPresenterInstance = opsType.newInstance();
// Put the PresenterInstance into the RetainedFragmentManager under
// the simple name.
mRetainedFragmentManager.put(opsType.getSimpleName(),
mPresenterInstance);
// Perform the first initialization.
mPresenterInstance.onCreate(view);
}
/**
* Reinitialize the GenericActivity fields after a runtime
* configuration change.
* @throws IllegalAccessException
* @throws InstantiationException
*/
private void reinitialize(Class<PresenterType> opsType,
RequiredViewOps view)
throws InstantiationException, IllegalAccessException {
// Try to obtain the PresenterType instance from the
// RetainedFragmentManager.
mPresenterInstance =
mRetainedFragmentManager.get(opsType.getSimpleName());
// This check shouldn't be necessary under normal
// circumstances, but it's better to lose state than to
// crash!
if (mPresenterInstance == null)
// Initialize the GenericActivity fields.
initialize(opsType,
view);
else
// Inform it that the runtime configuration change has
// completed.
mPresenterInstance.onConfigurationChange(view);
}
/**
* Return the Activity context.
*/
@Override
public Context getActivityContext() {
return this;
}
/**
* Return the Application context.
*/
@Override
public Context getApplicationContext() {
return super.getApplicationContext();
}
}
| {
"content_hash": "0a4b94388239cdb57b4fa4d862a4d134",
"timestamp": "",
"source": "github",
"line_count": 168,
"max_line_length": 90,
"avg_line_length": 36.18452380952381,
"alnum_prop": 0.6201677907550583,
"repo_name": "TingxinLi/Android-Concurrency",
"id": "41083d70ac3817f0e671bf44cf5e1f2aca89882d",
"size": "6079",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "assignment1/app/src/main/java/edu/vandy/common/GenericActivity.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "6879"
},
{
"name": "Java",
"bytes": "296850"
}
],
"symlink_target": ""
} |
package mod.smb.easygunpowder.helper;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraftforge.oredict.OreDictionary;
import cpw.mods.fml.common.registry.GameRegistry;
public class RegisterHelper
{
// Use to register blocks for this mod.
public static void registerBlock (Block block)
{
// Register said block using Forge's Block Registry
GameRegistry.registerBlock(block, Reference.MODID + "_" + block.getUnlocalizedName().substring(5));
}
// Use to register Items from this mod.
public static void registerItem (Item item)
{
GameRegistry.registerItem(item, Reference.MODID + "_" + item.getUnlocalizedName().substring(5));
}
// Integrate our RegisterOreDictEG Class into this class.
public static void addBlockIntoOreDict(Block block, String myName)
{
OreDictionary.registerOre(myName, block);
}
public static void addItemIntoOreDict(Item item, String myName)
{
OreDictionary.registerOre(myName, item);
}
}
| {
"content_hash": "3227df406a17220de82adf69d98ad5df",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 101,
"avg_line_length": 30.606060606060606,
"alnum_prop": 0.7405940594059406,
"repo_name": "LanceShield/EasyGunpowder2",
"id": "bf24a121f90f8c847ad6f8f7af35fd1d3b01b359",
"size": "1010",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "java/mod/smb/easygunpowder/helper/RegisterHelper.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "11008"
}
],
"symlink_target": ""
} |
@implementation AVAsset (NIMKit)
- (AVMutableVideoComposition *)nim_videoComposition {
AVAssetTrack *videoTrack = [[self tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0];
AVMutableComposition *composition = [AVMutableComposition composition];
AVMutableVideoComposition *videoComposition = [AVMutableVideoComposition videoComposition];
CGSize videoSize = videoTrack.naturalSize;
BOOL isPortrait_ = [self nim_isVideoPortrait];
if(isPortrait_) {
videoSize = CGSizeMake(videoSize.height, videoSize.width);
}
composition.naturalSize = videoSize;
videoComposition.renderSize = videoSize;
videoComposition.frameDuration = CMTimeMakeWithSeconds( 1 / videoTrack.nominalFrameRate, 600);
AVMutableCompositionTrack *compositionVideoTrack;
compositionVideoTrack = [composition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
[compositionVideoTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, self.duration) ofTrack:videoTrack atTime:kCMTimeZero error:nil];
AVMutableVideoCompositionLayerInstruction *layerInst;
layerInst = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstructionWithAssetTrack:videoTrack];
[layerInst setTransform:videoTrack.preferredTransform atTime:kCMTimeZero];
AVMutableVideoCompositionInstruction *inst = [AVMutableVideoCompositionInstruction videoCompositionInstruction];
inst.timeRange = CMTimeRangeMake(kCMTimeZero, self.duration);
inst.layerInstructions = [NSArray arrayWithObject:layerInst];
videoComposition.instructions = [NSArray arrayWithObject:inst];
return videoComposition;
}
- (BOOL)nim_isVideoPortrait
{
BOOL isPortrait = NO;
NSArray *tracks = [self tracksWithMediaType:AVMediaTypeVideo];
if([tracks count] > 0) {
AVAssetTrack *videoTrack = [tracks objectAtIndex:0];
CGAffineTransform t = videoTrack.preferredTransform;
// Portrait
if(t.a == 0 && t.b == 1.0 && t.c == -1.0 && t.d == 0)
{
isPortrait = YES;
}
// PortraitUpsideDown
if(t.a == 0 && t.b == -1.0 && t.c == 1.0 && t.d == 0) {
isPortrait = YES;
}
// LandscapeRight
if(t.a == 1.0 && t.b == 0 && t.c == 0 && t.d == 1.0)
{
isPortrait = NO;
}
// LandscapeLeft
if(t.a == -1.0 && t.b == 0 && t.c == 0 && t.d == -1.0)
{
isPortrait = NO;
}
}
return isPortrait;
}
@end
| {
"content_hash": "250bdf6c2e19c2c054669fafab1ec754",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 136,
"avg_line_length": 41.77049180327869,
"alnum_prop": 0.6793563579277865,
"repo_name": "netease-im/NIM_iOS_UIKit",
"id": "021f1eecb875fa6c04d4a489bcb261161afa6325",
"size": "2707",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "NIMKit/NIMKit/Classes/Category/AVAsset+NIMKit.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "529"
},
{
"name": "Objective-C",
"bytes": "850479"
},
{
"name": "Ruby",
"bytes": "2108"
}
],
"symlink_target": ""
} |
//
// Copyright 2015 DreamWorks Animation LLC.
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef OPENSUBDIV3_FAR_PRIMVAR_REFINER_H
#define OPENSUBDIV3_FAR_PRIMVAR_REFINER_H
#include "../version.h"
#include "../sdc/types.h"
#include "../sdc/options.h"
#include "../sdc/bilinearScheme.h"
#include "../sdc/catmarkScheme.h"
#include "../sdc/loopScheme.h"
#include "../vtr/level.h"
#include "../vtr/fvarLevel.h"
#include "../vtr/refinement.h"
#include "../vtr/fvarRefinement.h"
#include "../vtr/stackBuffer.h"
#include "../vtr/componentInterfaces.h"
#include "../far/types.h"
#include "../far/error.h"
#include "../far/topologyLevel.h"
#include "../far/topologyRefiner.h"
#include <cassert>
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
namespace Far {
///
/// \brief Applies refinement operations to generic primvar data.
///
class PrimvarRefiner {
public:
PrimvarRefiner(TopologyRefiner const & refiner) : _refiner(refiner) { }
~PrimvarRefiner() { }
TopologyRefiner const & GetTopologyRefiner() const { return _refiner; }
//@{
/// @name Primvar data interpolation
///
/// \anchor templating
///
/// \note Interpolation methods template both the source and destination
/// data buffer classes. Client-code is expected to provide interfaces
/// that implement the functions specific to its primitive variable
/// data layout. Template APIs must implement the following:
/// <br><br> \code{.cpp}
///
/// class MySource {
/// MySource & operator[](int index);
/// };
///
/// class MyDestination {
/// void Clear();
/// void AddWithWeight(MySource const & value, float weight);
/// void AddWithWeight(MyDestination const & value, float weight);
/// };
///
/// \endcode
/// <br>
/// It is possible to implement a single interface only and use it as
/// both source and destination.
/// <br><br>
/// Primitive variable buffers are expected to be arrays of instances,
/// passed either as direct pointers or with a container
/// (ex. std::vector<MyVertex>).
/// Some interpolation methods however allow passing the buffers by
/// reference: this allows to work transparently with arrays and
/// containers (or other scheme that overload the '[]' operator)
/// <br><br>
/// See the <a href=http://graphics.pixar.com/opensubdiv/docs/tutorials.html>
/// Far tutorials</a> for code examples.
///
/// \brief Apply vertex interpolation weights to a primvar buffer for a single
/// level level of refinement.
///
/// The destination buffer must allocate an array of data for all the
/// refined vertices, i.e. at least refiner.GetLevel(level).GetNumVertices()
///
/// @param level The refinement level
///
/// @param src Source primvar buffer (\ref templating control vertex data)
///
/// @param dst Destination primvar buffer (\ref templating refined vertex data)
///
template <class T, class U> void Interpolate(int level, T const & src, U & dst) const;
/// \brief Apply only varying interpolation weights to a primvar buffer
/// for a single level level of refinement.
///
/// This method can useful if the varying primvar data does not need to be
/// re-computed over time.
///
/// The destination buffer must allocate an array of data for all the
/// refined vertices, i.e. at least refiner.GetLevel(level).GetNumVertices()
///
/// @param level The refinement level
///
/// @param src Source primvar buffer (\ref templating control vertex data)
///
/// @param dst Destination primvar buffer (\ref templating refined vertex data)
///
template <class T, class U> void InterpolateVarying(int level, T const & src, U & dst) const;
/// \brief Refine uniform (per-face) primvar data between levels.
///
/// Data is simply copied from a parent face to its child faces and does not involve
/// any weighting. Setting the source primvar data for the base level to be the index
/// of each face allows the propagation of the base face to primvar data for child
/// faces in all levels.
///
/// The destination buffer must allocate an array of data for all the refined faces,
/// i.e. at least refiner.GetLevel(level).GetNumFaces()
///
/// @param level The refinement level
///
/// @param src Source primvar buffer
///
/// @param dst Destination primvar buffer
///
template <class T, class U> void InterpolateFaceUniform(int level, T const & src, U & dst) const;
/// \brief Apply face-varying interpolation weights to a primvar buffer
/// associated with a particular face-varying channel.
///
/// Unlike vertex and varying primvar buffers, there is not a 1-to-1 correspondence
/// between vertices and face-varying values -- typically there are more face-varying
/// values than vertices. Each face-varying channel is also independent in how its
/// values relate to the vertices.
///
/// The destination buffer must allocate an array of data for all the refined values,
/// i.e. at least refiner.GetLevel(level).GetNumFVarValues(channel).
///
template <class T, class U> void InterpolateFaceVarying(int level, T const & src, U & dst, int channel = 0) const;
/// \brief Apply limit weights to a primvar buffer
///
/// The source buffer must refer to an array of previously interpolated
/// vertex data for the last refinement level. The destination buffer
/// must allocate an array for all vertices at the last refinement level,
/// i.e. at least refiner.GetLevel(refiner.GetMaxLevel()).GetNumVertices()
///
/// @param src Source primvar buffer (refined data) for last level
///
/// @param dstPos Destination primvar buffer (data at the limit)
///
template <class T, class U> void Limit(T const & src, U & dstPos) const;
template <class T, class U, class U1, class U2>
void Limit(T const & src, U & dstPos, U1 & dstTan1, U2 & dstTan2) const;
template <class T, class U> void LimitFaceVarying(T const & src, U & dst, int channel = 0) const;
//@}
private:
// Non-copyable:
PrimvarRefiner(PrimvarRefiner const & src) : _refiner(src._refiner) { }
PrimvarRefiner & operator=(PrimvarRefiner const &) { return *this; }
template <Sdc::SchemeType SCHEME, class T, class U> void interpFromFaces(int, T const &, U &) const;
template <Sdc::SchemeType SCHEME, class T, class U> void interpFromEdges(int, T const &, U &) const;
template <Sdc::SchemeType SCHEME, class T, class U> void interpFromVerts(int, T const &, U &) const;
template <Sdc::SchemeType SCHEME, class T, class U> void interpFVarFromFaces(int, T const &, U &, int) const;
template <Sdc::SchemeType SCHEME, class T, class U> void interpFVarFromEdges(int, T const &, U &, int) const;
template <Sdc::SchemeType SCHEME, class T, class U> void interpFVarFromVerts(int, T const &, U &, int) const;
template <Sdc::SchemeType SCHEME, class T, class U, class U1, class U2>
void limit(T const & src, U & pos, U1 * tan1, U2 * tan2) const;
template <Sdc::SchemeType SCHEME, class T, class U>
void limitFVar(T const & src, U * dst, int channel) const;
private:
TopologyRefiner const & _refiner;
private:
//
// Local class to fulfil interface for <typename MASK> in the Scheme mask queries:
//
class Mask {
public:
typedef float Weight; // Also part of the expected interface
public:
Mask(Weight* v, Weight* e, Weight* f) :
_vertWeights(v), _edgeWeights(e), _faceWeights(f),
_vertCount(0), _edgeCount(0), _faceCount(0),
_faceWeightsForFaceCenters(false)
{ }
~Mask() { }
public: // Generic interface expected of <typename MASK>:
int GetNumVertexWeights() const { return _vertCount; }
int GetNumEdgeWeights() const { return _edgeCount; }
int GetNumFaceWeights() const { return _faceCount; }
void SetNumVertexWeights(int count) { _vertCount = count; }
void SetNumEdgeWeights( int count) { _edgeCount = count; }
void SetNumFaceWeights( int count) { _faceCount = count; }
Weight const& VertexWeight(int index) const { return _vertWeights[index]; }
Weight const& EdgeWeight( int index) const { return _edgeWeights[index]; }
Weight const& FaceWeight( int index) const { return _faceWeights[index]; }
Weight& VertexWeight(int index) { return _vertWeights[index]; }
Weight& EdgeWeight( int index) { return _edgeWeights[index]; }
Weight& FaceWeight( int index) { return _faceWeights[index]; }
bool AreFaceWeightsForFaceCenters() const { return _faceWeightsForFaceCenters; }
void SetFaceWeightsForFaceCenters(bool on) { _faceWeightsForFaceCenters = on; }
private:
Weight* _vertWeights;
Weight* _edgeWeights;
Weight* _faceWeights;
int _vertCount;
int _edgeCount;
int _faceCount;
bool _faceWeightsForFaceCenters;
};
};
//
// Public entry points to the methods. Queries of the scheme type and its
// use as a template parameter in subsequent implementation will be factored
// out of a later release:
//
template <class T, class U>
inline void
PrimvarRefiner::Interpolate(int level, T const & src, U & dst) const {
assert(level>0 and level<=(int)_refiner._refinements.size());
switch (_refiner._subdivType) {
case Sdc::SCHEME_CATMARK:
interpFromFaces<Sdc::SCHEME_CATMARK>(level, src, dst);
interpFromEdges<Sdc::SCHEME_CATMARK>(level, src, dst);
interpFromVerts<Sdc::SCHEME_CATMARK>(level, src, dst);
break;
case Sdc::SCHEME_LOOP:
interpFromFaces<Sdc::SCHEME_LOOP>(level, src, dst);
interpFromEdges<Sdc::SCHEME_LOOP>(level, src, dst);
interpFromVerts<Sdc::SCHEME_LOOP>(level, src, dst);
break;
case Sdc::SCHEME_BILINEAR:
interpFromFaces<Sdc::SCHEME_BILINEAR>(level, src, dst);
interpFromEdges<Sdc::SCHEME_BILINEAR>(level, src, dst);
interpFromVerts<Sdc::SCHEME_BILINEAR>(level, src, dst);
break;
}
}
template <class T, class U>
inline void
PrimvarRefiner::InterpolateFaceVarying(int level, T const & src, U & dst, int channel) const {
assert(level>0 and level<=(int)_refiner._refinements.size());
switch (_refiner._subdivType) {
case Sdc::SCHEME_CATMARK:
interpFVarFromFaces<Sdc::SCHEME_CATMARK>(level, src, dst, channel);
interpFVarFromEdges<Sdc::SCHEME_CATMARK>(level, src, dst, channel);
interpFVarFromVerts<Sdc::SCHEME_CATMARK>(level, src, dst, channel);
break;
case Sdc::SCHEME_LOOP:
interpFVarFromFaces<Sdc::SCHEME_LOOP>(level, src, dst, channel);
interpFVarFromEdges<Sdc::SCHEME_LOOP>(level, src, dst, channel);
interpFVarFromVerts<Sdc::SCHEME_LOOP>(level, src, dst, channel);
break;
case Sdc::SCHEME_BILINEAR:
interpFVarFromFaces<Sdc::SCHEME_BILINEAR>(level, src, dst, channel);
interpFVarFromEdges<Sdc::SCHEME_BILINEAR>(level, src, dst, channel);
interpFVarFromVerts<Sdc::SCHEME_BILINEAR>(level, src, dst, channel);
break;
}
}
template <class T, class U>
inline void
PrimvarRefiner::Limit(T const & src, U & dst) const {
if (_refiner.getLevel(_refiner.GetMaxLevel()).getNumVertexEdgesTotal() == 0) {
Error(FAR_RUNTIME_ERROR,
"Failure in PrimvarRefiner::Limit() -- "
"last level of refinement does not include full topology.");
return;
}
switch (_refiner._subdivType) {
case Sdc::SCHEME_CATMARK:
limit<Sdc::SCHEME_CATMARK>(src, dst, (U*)0, (U*)0);
break;
case Sdc::SCHEME_LOOP:
limit<Sdc::SCHEME_LOOP>(src, dst, (U*)0, (U*)0);
break;
case Sdc::SCHEME_BILINEAR:
limit<Sdc::SCHEME_BILINEAR>(src, dst, (U*)0, (U*)0);
break;
}
}
template <class T, class U, class U1, class U2>
inline void
PrimvarRefiner::Limit(T const & src, U & dstPos, U1 & dstTan1, U2 & dstTan2) const {
if (_refiner.getLevel(_refiner.GetMaxLevel()).getNumVertexEdgesTotal() == 0) {
Error(FAR_RUNTIME_ERROR,
"Failure in PrimvarRefiner::Limit() -- "
"last level of refinement does not include full topology.");
return;
}
switch (_refiner._subdivType) {
case Sdc::SCHEME_CATMARK:
limit<Sdc::SCHEME_CATMARK>(src, dstPos, &dstTan1, &dstTan2);
break;
case Sdc::SCHEME_LOOP:
limit<Sdc::SCHEME_LOOP>(src, dstPos, &dstTan1, &dstTan2);
break;
case Sdc::SCHEME_BILINEAR:
limit<Sdc::SCHEME_BILINEAR>(src, dstPos, &dstTan1, &dstTan2);
break;
}
}
template <class T, class U>
inline void
PrimvarRefiner::LimitFaceVarying(T const & src, U & dst, int channel) const {
if (_refiner.getLevel(_refiner.GetMaxLevel()).getNumVertexEdgesTotal() == 0) {
Error(FAR_RUNTIME_ERROR,
"Failure in PrimvarRefiner::LimitFaceVarying() -- "
"last level of refinement does not include full topology.");
return;
}
switch (_refiner._subdivType) {
case Sdc::SCHEME_CATMARK:
limitFVar<Sdc::SCHEME_CATMARK>(src, dst, channel);
break;
case Sdc::SCHEME_LOOP:
limitFVar<Sdc::SCHEME_LOOP>(src, dst, channel);
break;
case Sdc::SCHEME_BILINEAR:
limitFVar<Sdc::SCHEME_BILINEAR>(src, dst, channel);
break;
}
}
template <class T, class U>
inline void
PrimvarRefiner::InterpolateFaceUniform(int level, T const & src, U & dst) const {
assert(level>0 and level<=(int)_refiner._refinements.size());
Vtr::internal::Refinement const & refinement = _refiner.getRefinement(level-1);
Vtr::internal::Level const & child = refinement.child();
for (int cFace = 0; cFace < child.getNumFaces(); ++cFace) {
Vtr::Index pFace = refinement.getChildFaceParentFace(cFace);
dst[cFace] = src[pFace];
}
}
template <class T, class U>
inline void
PrimvarRefiner::InterpolateVarying(int level, T const & src, U & dst) const {
assert(level>0 and level<=(int)_refiner._refinements.size());
Vtr::internal::Refinement const & refinement = _refiner.getRefinement(level-1);
Vtr::internal::Level const & parent = refinement.parent();
//
// Group values to interolate based on origin -- note that there may
// be none originating from faces:
//
if (refinement.getNumChildVerticesFromFaces() > 0) {
for (int face = 0; face < parent.getNumFaces(); ++face) {
Vtr::Index cVert = refinement.getFaceChildVertex(face);
if (Vtr::IndexIsValid(cVert)) {
// Apply the weights to the parent face's vertices:
ConstIndexArray fVerts = parent.getFaceVertices(face);
float fVaryingWeight = 1.0f / (float) fVerts.size();
dst[cVert].Clear();
for (int i = 0; i < fVerts.size(); ++i) {
dst[cVert].AddWithWeight(src[fVerts[i]], fVaryingWeight);
}
}
}
}
for (int edge = 0; edge < parent.getNumEdges(); ++edge) {
Vtr::Index cVert = refinement.getEdgeChildVertex(edge);
if (Vtr::IndexIsValid(cVert)) {
// Apply the weights to the parent edges's vertices
ConstIndexArray eVerts = parent.getEdgeVertices(edge);
dst[cVert].Clear();
dst[cVert].AddWithWeight(src[eVerts[0]], 0.5f);
dst[cVert].AddWithWeight(src[eVerts[1]], 0.5f);
}
}
for (int vert = 0; vert < parent.getNumVertices(); ++vert) {
Vtr::Index cVert = refinement.getVertexChildVertex(vert);
if (Vtr::IndexIsValid(cVert)) {
// Essentially copy the parent vertex:
dst[cVert].Clear();
dst[cVert].AddWithWeight(src[vert], 1.0f);
}
}
}
//
// Internal implementation methods -- grouping vertices to be interpolated
// based on the type of parent component from which they originated:
//
template <Sdc::SchemeType SCHEME, class T, class U>
inline void
PrimvarRefiner::interpFromFaces(int level, T const & src, U & dst) const {
Vtr::internal::Refinement const & refinement = _refiner.getRefinement(level-1);
Vtr::internal::Level const & parent = refinement.parent();
if (refinement.getNumChildVerticesFromFaces() == 0) return;
Sdc::Scheme<SCHEME> scheme(_refiner._subdivOptions);
Vtr::internal::StackBuffer<float,16> fVertWeights(parent.getMaxValence());
for (int face = 0; face < parent.getNumFaces(); ++face) {
Vtr::Index cVert = refinement.getFaceChildVertex(face);
if (!Vtr::IndexIsValid(cVert))
continue;
// Declare and compute mask weights for this vertex relative to its parent face:
ConstIndexArray fVerts = parent.getFaceVertices(face);
Mask fMask(fVertWeights, 0, 0);
Vtr::internal::FaceInterface fHood(fVerts.size());
scheme.ComputeFaceVertexMask(fHood, fMask);
// Apply the weights to the parent face's vertices:
dst[cVert].Clear();
for (int i = 0; i < fVerts.size(); ++i) {
dst[cVert].AddWithWeight(src[fVerts[i]], fVertWeights[i]);
}
}
}
template <Sdc::SchemeType SCHEME, class T, class U>
inline void
PrimvarRefiner::interpFromEdges(int level, T const & src, U & dst) const {
Vtr::internal::Refinement const & refinement = _refiner.getRefinement(level-1);
Vtr::internal::Level const & parent = refinement.parent();
Vtr::internal::Level const & child = refinement.child();
Sdc::Scheme<SCHEME> scheme(_refiner._subdivOptions);
Vtr::internal::EdgeInterface eHood(parent);
float eVertWeights[2];
Vtr::internal::StackBuffer<float,8> eFaceWeights(parent.getMaxEdgeFaces());
for (int edge = 0; edge < parent.getNumEdges(); ++edge) {
Vtr::Index cVert = refinement.getEdgeChildVertex(edge);
if (!Vtr::IndexIsValid(cVert))
continue;
// Declare and compute mask weights for this vertex relative to its parent edge:
ConstIndexArray eVerts = parent.getEdgeVertices(edge),
eFaces = parent.getEdgeFaces(edge);
Mask eMask(eVertWeights, 0, eFaceWeights);
eHood.SetIndex(edge);
Sdc::Crease::Rule pRule = (parent.getEdgeSharpness(edge) > 0.0f) ? Sdc::Crease::RULE_CREASE : Sdc::Crease::RULE_SMOOTH;
Sdc::Crease::Rule cRule = child.getVertexRule(cVert);
scheme.ComputeEdgeVertexMask(eHood, eMask, pRule, cRule);
// Apply the weights to the parent edges's vertices and (if applicable) to
// the child vertices of its incident faces:
dst[cVert].Clear();
dst[cVert].AddWithWeight(src[eVerts[0]], eVertWeights[0]);
dst[cVert].AddWithWeight(src[eVerts[1]], eVertWeights[1]);
if (eMask.GetNumFaceWeights() > 0) {
for (int i = 0; i < eFaces.size(); ++i) {
if (eMask.AreFaceWeightsForFaceCenters()) {
assert(refinement.getNumChildVerticesFromFaces() > 0);
Vtr::Index cVertOfFace = refinement.getFaceChildVertex(eFaces[i]);
assert(Vtr::IndexIsValid(cVertOfFace));
dst[cVert].AddWithWeight(dst[cVertOfFace], eFaceWeights[i]);
} else {
Vtr::Index pFace = eFaces[i];
ConstIndexArray pFaceEdges = parent.getFaceEdges(pFace),
pFaceVerts = parent.getFaceVertices(pFace);
int eInFace = 0;
for ( ; pFaceEdges[eInFace] != edge; ++eInFace ) ;
int vInFace = eInFace + 2;
if (vInFace >= pFaceVerts.size()) vInFace -= pFaceVerts.size();
Vtr::Index pVertNext = pFaceVerts[vInFace];
dst[cVert].AddWithWeight(src[pVertNext], eFaceWeights[i]);
}
}
}
}
}
template <Sdc::SchemeType SCHEME, class T, class U>
inline void
PrimvarRefiner::interpFromVerts(int level, T const & src, U & dst) const {
Vtr::internal::Refinement const & refinement = _refiner.getRefinement(level-1);
Vtr::internal::Level const & parent = refinement.parent();
Vtr::internal::Level const & child = refinement.child();
Sdc::Scheme<SCHEME> scheme(_refiner._subdivOptions);
Vtr::internal::VertexInterface vHood(parent, child);
Vtr::internal::StackBuffer<float,32> weightBuffer(2*parent.getMaxValence());
for (int vert = 0; vert < parent.getNumVertices(); ++vert) {
Vtr::Index cVert = refinement.getVertexChildVertex(vert);
if (!Vtr::IndexIsValid(cVert))
continue;
// Declare and compute mask weights for this vertex relative to its parent edge:
ConstIndexArray vEdges = parent.getVertexEdges(vert),
vFaces = parent.getVertexFaces(vert);
float vVertWeight,
* vEdgeWeights = weightBuffer,
* vFaceWeights = vEdgeWeights + vEdges.size();
Mask vMask(&vVertWeight, vEdgeWeights, vFaceWeights);
vHood.SetIndex(vert, cVert);
Sdc::Crease::Rule pRule = parent.getVertexRule(vert);
Sdc::Crease::Rule cRule = child.getVertexRule(cVert);
scheme.ComputeVertexVertexMask(vHood, vMask, pRule, cRule);
// Apply the weights to the parent vertex, the vertices opposite its incident
// edges, and the child vertices of its incident faces:
//
// In order to improve numerical precision, its better to apply smaller weights
// first, so begin with the face-weights followed by the edge-weights and the
// vertex weight last.
dst[cVert].Clear();
if (vMask.GetNumFaceWeights() > 0) {
assert(vMask.AreFaceWeightsForFaceCenters());
for (int i = 0; i < vFaces.size(); ++i) {
Vtr::Index cVertOfFace = refinement.getFaceChildVertex(vFaces[i]);
assert(Vtr::IndexIsValid(cVertOfFace));
dst[cVert].AddWithWeight(dst[cVertOfFace], vFaceWeights[i]);
}
}
if (vMask.GetNumEdgeWeights() > 0) {
for (int i = 0; i < vEdges.size(); ++i) {
ConstIndexArray eVerts = parent.getEdgeVertices(vEdges[i]);
Vtr::Index pVertOppositeEdge = (eVerts[0] == vert) ? eVerts[1] : eVerts[0];
dst[cVert].AddWithWeight(src[pVertOppositeEdge], vEdgeWeights[i]);
}
}
dst[cVert].AddWithWeight(src[vert], vVertWeight);
}
}
//
// Internal face-varying implementation details:
//
template <Sdc::SchemeType SCHEME, class T, class U>
inline void
PrimvarRefiner::interpFVarFromFaces(int level, T const & src, U & dst, int channel) const {
Vtr::internal::Refinement const & refinement = _refiner.getRefinement(level-1);
if (refinement.getNumChildVerticesFromFaces() == 0) return;
Sdc::Scheme<SCHEME> scheme(_refiner._subdivOptions);
Vtr::internal::Level const & parentLevel = refinement.parent();
Vtr::internal::Level const & childLevel = refinement.child();
Vtr::internal::FVarLevel const & parentFVar = parentLevel.getFVarLevel(channel);
Vtr::internal::FVarLevel const & childFVar = childLevel.getFVarLevel(channel);
Vtr::internal::StackBuffer<float,16> fValueWeights(parentLevel.getMaxValence());
for (int face = 0; face < parentLevel.getNumFaces(); ++face) {
Vtr::Index cVert = refinement.getFaceChildVertex(face);
if (!Vtr::IndexIsValid(cVert))
continue;
Vtr::Index cVertValue = childFVar.getVertexValueOffset(cVert);
// The only difference for face-varying here is that we get the values associated
// with each face-vertex directly from the FVarLevel, rather than using the parent
// face-vertices directly. If any face-vertex has any sibling values, then we may
// get the wrong one using the face-vertex index directly.
// Declare and compute mask weights for this vertex relative to its parent face:
ConstIndexArray fValues = parentFVar.getFaceValues(face);
Mask fMask(fValueWeights, 0, 0);
Vtr::internal::FaceInterface fHood(fValues.size());
scheme.ComputeFaceVertexMask(fHood, fMask);
// Apply the weights to the parent face's vertices:
dst[cVertValue].Clear();
for (int i = 0; i < fValues.size(); ++i) {
dst[cVertValue].AddWithWeight(src[fValues[i]], fValueWeights[i]);
}
}
}
template <Sdc::SchemeType SCHEME, class T, class U>
inline void
PrimvarRefiner::interpFVarFromEdges(int level, T const & src, U & dst, int channel) const {
Vtr::internal::Refinement const & refinement = _refiner.getRefinement(level-1);
Sdc::Scheme<SCHEME> scheme(_refiner._subdivOptions);
Vtr::internal::Level const & parentLevel = refinement.parent();
Vtr::internal::Level const & childLevel = refinement.child();
Vtr::internal::FVarRefinement const & refineFVar = refinement.getFVarRefinement(channel);
Vtr::internal::FVarLevel const & parentFVar = parentLevel.getFVarLevel(channel);
Vtr::internal::FVarLevel const & childFVar = childLevel.getFVarLevel(channel);
//
// Allocate and intialize (if linearly interpolated) interpolation weights for
// the edge mask:
//
float eVertWeights[2];
Vtr::internal::StackBuffer<float,8> eFaceWeights(parentLevel.getMaxEdgeFaces());
Mask eMask(eVertWeights, 0, eFaceWeights);
bool isLinearFVar = parentFVar.isLinear();
if (isLinearFVar) {
eMask.SetNumVertexWeights(2);
eMask.SetNumEdgeWeights(0);
eMask.SetNumFaceWeights(0);
eVertWeights[0] = 0.5f;
eVertWeights[1] = 0.5f;
}
Vtr::internal::EdgeInterface eHood(parentLevel);
for (int edge = 0; edge < parentLevel.getNumEdges(); ++edge) {
Vtr::Index cVert = refinement.getEdgeChildVertex(edge);
if (!Vtr::IndexIsValid(cVert))
continue;
ConstIndexArray cVertValues = childFVar.getVertexValues(cVert);
bool fvarEdgeVertMatchesVertex = childFVar.valueTopologyMatches(cVertValues[0]);
if (fvarEdgeVertMatchesVertex) {
//
// If smoothly interpolated, compute new weights for the edge mask:
//
if (!isLinearFVar) {
eHood.SetIndex(edge);
Sdc::Crease::Rule pRule = (parentLevel.getEdgeSharpness(edge) > 0.0f)
? Sdc::Crease::RULE_CREASE : Sdc::Crease::RULE_SMOOTH;
Sdc::Crease::Rule cRule = childLevel.getVertexRule(cVert);
scheme.ComputeEdgeVertexMask(eHood, eMask, pRule, cRule);
}
// Apply the weights to the parent edges's vertices and (if applicable) to
// the child vertices of its incident faces:
//
// Even though the face-varying topology matches the vertex topology, we need
// to be careful here when getting values corresponding to the two end-vertices.
// While the edge may be continuous, the vertices at their ends may have
// discontinuities elsewhere in their neighborhood (i.e. on the "other side"
// of the end-vertex) and so have sibling values associated with them. In most
// cases the topology for an end-vertex will match and we can use it directly,
// but we must still check and retrieve as needed.
//
// Indices for values corresponding to face-vertices are guaranteed to match,
// so we can use the child-vertex indices directly.
//
// And by "directly", we always use getVertexValue(vertexIndex) to reference
// values in the "src" to account for the possible indirection that may exist at
// level 0 -- where there may be fewer values than vertices and an additional
// indirection is necessary. We can use a vertex index directly for "dst" when
// it matches.
//
Vtr::Index eVertValues[2];
parentFVar.getEdgeFaceValues(edge, 0, eVertValues);
Index cVertValue = cVertValues[0];
dst[cVertValue].Clear();
dst[cVertValue].AddWithWeight(src[eVertValues[0]], eVertWeights[0]);
dst[cVertValue].AddWithWeight(src[eVertValues[1]], eVertWeights[1]);
if (eMask.GetNumFaceWeights() > 0) {
ConstIndexArray eFaces = parentLevel.getEdgeFaces(edge);
for (int i = 0; i < eFaces.size(); ++i) {
if (eMask.AreFaceWeightsForFaceCenters()) {
Vtr::Index cVertOfFace = refinement.getFaceChildVertex(eFaces[i]);
assert(Vtr::IndexIsValid(cVertOfFace));
Vtr::Index cValueOfFace = childFVar.getVertexValueOffset(cVertOfFace);
dst[cVertValue].AddWithWeight(dst[cValueOfFace], eFaceWeights[i]);
} else {
Vtr::Index pFace = eFaces[i];
ConstIndexArray pFaceEdges = parentLevel.getFaceEdges(pFace),
pFaceVerts = parentLevel.getFaceVertices(pFace);
int eInFace = 0;
for ( ; pFaceEdges[eInFace] != edge; ++eInFace ) ;
// Edge "i" spans vertices [i,i+1] so we want i+2...
int vInFace = eInFace + 2;
if (vInFace >= pFaceVerts.size()) vInFace -= pFaceVerts.size();
Vtr::Index pValueNext = parentFVar.getFaceValues(pFace)[vInFace];
dst[cVertValue].AddWithWeight(src[pValueNext], eFaceWeights[i]);
}
}
}
} else {
//
// Mismatched edge-verts should just be linearly interpolated between the pairs of
// values for each sibling of the child edge-vertex -- the question is: which face
// holds that pair of values for a given sibling?
//
// In the manifold case, the sibling and edge-face indices will correspond. We
// will eventually need to update this to account for > 3 incident faces.
//
for (int i = 0; i < cVertValues.size(); ++i) {
Vtr::Index eVertValues[2];
int eFaceIndex = refineFVar.getChildValueParentSource(cVert, i);
assert(eFaceIndex == i);
parentFVar.getEdgeFaceValues(edge, eFaceIndex, eVertValues);
Index cVertValue = cVertValues[i];
dst[cVertValue].Clear();
dst[cVertValue].AddWithWeight(src[eVertValues[0]], 0.5);
dst[cVertValue].AddWithWeight(src[eVertValues[1]], 0.5);
}
}
}
}
template <Sdc::SchemeType SCHEME, class T, class U>
inline void
PrimvarRefiner::interpFVarFromVerts(int level, T const & src, U & dst, int channel) const {
Vtr::internal::Refinement const & refinement = _refiner.getRefinement(level-1);
Sdc::Scheme<SCHEME> scheme(_refiner._subdivOptions);
Vtr::internal::Level const & parentLevel = refinement.parent();
Vtr::internal::Level const & childLevel = refinement.child();
Vtr::internal::FVarRefinement const & refineFVar = refinement.getFVarRefinement(channel);
Vtr::internal::FVarLevel const & parentFVar = parentLevel.getFVarLevel(channel);
Vtr::internal::FVarLevel const & childFVar = childLevel.getFVarLevel(channel);
bool isLinearFVar = parentFVar.isLinear();
Vtr::internal::StackBuffer<float,32> weightBuffer(2*parentLevel.getMaxValence());
Vtr::internal::StackBuffer<Vtr::Index,16> vEdgeValues(parentLevel.getMaxValence());
Vtr::internal::VertexInterface vHood(parentLevel, childLevel);
for (int vert = 0; vert < parentLevel.getNumVertices(); ++vert) {
Vtr::Index cVert = refinement.getVertexChildVertex(vert);
if (!Vtr::IndexIsValid(cVert))
continue;
ConstIndexArray pVertValues = parentFVar.getVertexValues(vert),
cVertValues = childFVar.getVertexValues(cVert);
bool fvarVertVertMatchesVertex = childFVar.valueTopologyMatches(cVertValues[0]);
if (isLinearFVar && fvarVertVertMatchesVertex) {
dst[cVertValues[0]].Clear();
dst[cVertValues[0]].AddWithWeight(src[pVertValues[0]], 1.0f);
continue;
}
if (fvarVertVertMatchesVertex) {
//
// Declare and compute mask weights for this vertex relative to its parent edge:
//
// (We really need to encapsulate this somewhere else for use here and in the
// general case)
//
ConstIndexArray vEdges = parentLevel.getVertexEdges(vert);
float vVertWeight;
float * vEdgeWeights = weightBuffer;
float * vFaceWeights = vEdgeWeights + vEdges.size();
Mask vMask(&vVertWeight, vEdgeWeights, vFaceWeights);
vHood.SetIndex(vert, cVert);
Sdc::Crease::Rule pRule = parentLevel.getVertexRule(vert);
Sdc::Crease::Rule cRule = childLevel.getVertexRule(cVert);
scheme.ComputeVertexVertexMask(vHood, vMask, pRule, cRule);
// Apply the weights to the parent vertex, the vertices opposite its incident
// edges, and the child vertices of its incident faces:
//
// Even though the face-varying topology matches the vertex topology, we need
// to be careful here when getting values corresponding to vertices at the
// ends of edges. While the edge may be continuous, the end vertex may have
// discontinuities elsewhere in their neighborhood (i.e. on the "other side"
// of the end-vertex) and so have sibling values associated with them. In most
// cases the topology for an end-vertex will match and we can use it directly,
// but we must still check and retrieve as needed.
//
// Indices for values corresponding to face-vertices are guaranteed to match,
// so we can use the child-vertex indices directly.
//
// And by "directly", we always use getVertexValue(vertexIndex) to reference
// values in the "src" to account for the possible indirection that may exist at
// level 0 -- where there may be fewer values than vertices and an additional
// indirection is necessary. We can use a vertex index directly for "dst" when
// it matches.
//
// As with applying the mask to vertex data, in order to improve numerical
// precision, its better to apply smaller weights first, so begin with the
// face-weights followed by the edge-weights and the vertex weight last.
//
Vtr::Index pVertValue = pVertValues[0];
Vtr::Index cVertValue = cVertValues[0];
dst[cVertValue].Clear();
if (vMask.GetNumFaceWeights() > 0) {
assert(vMask.AreFaceWeightsForFaceCenters());
ConstIndexArray vFaces = parentLevel.getVertexFaces(vert);
for (int i = 0; i < vFaces.size(); ++i) {
Vtr::Index cVertOfFace = refinement.getFaceChildVertex(vFaces[i]);
assert(Vtr::IndexIsValid(cVertOfFace));
Vtr::Index cValueOfFace = childFVar.getVertexValueOffset(cVertOfFace);
dst[cVertValue].AddWithWeight(dst[cValueOfFace], vFaceWeights[i]);
}
}
if (vMask.GetNumEdgeWeights() > 0) {
parentFVar.getVertexEdgeValues(vert, vEdgeValues);
for (int i = 0; i < vEdges.size(); ++i) {
dst[cVertValue].AddWithWeight(src[vEdgeValues[i]], vEdgeWeights[i]);
}
}
dst[cVertValue].AddWithWeight(src[pVertValue], vVertWeight);
} else {
//
// Each FVar value associated with a vertex will be either a corner or a crease,
// or potentially in transition from corner to crease:
// - if the CHILD is a corner, there can be no transition so we have a corner
// - otherwise if the PARENT is a crease, both will be creases (no transition)
// - otherwise the parent must be a corner and the child a crease (transition)
//
Vtr::internal::FVarLevel::ConstValueTagArray pValueTags = parentFVar.getVertexValueTags(vert);
Vtr::internal::FVarLevel::ConstValueTagArray cValueTags = childFVar.getVertexValueTags(cVert);
for (int cSibling = 0; cSibling < cVertValues.size(); ++cSibling) {
int pSibling = refineFVar.getChildValueParentSource(cVert, cSibling);
assert(pSibling == cSibling);
Vtr::Index pVertValue = pVertValues[pSibling];
Vtr::Index cVertValue = cVertValues[cSibling];
dst[cVertValue].Clear();
if (cValueTags[cSibling].isCorner()) {
dst[cVertValue].AddWithWeight(src[pVertValue], 1.0f);
} else {
//
// We have either a crease or a transition from corner to crease -- in
// either case, we need the end values for the full/fractional crease:
//
Index pEndValues[2];
parentFVar.getVertexCreaseEndValues(vert, pSibling, pEndValues);
float vWeight = 0.75f;
float eWeight = 0.125f;
//
// If semisharp we need to apply fractional weighting -- if made sharp because
// of the other sibling (dependent-sharp) use the fractional weight from that
// other sibling (should only occur when there are 2):
//
if (pValueTags[pSibling].isSemiSharp()) {
float wCorner = pValueTags[pSibling].isDepSharp()
? refineFVar.getFractionalWeight(vert, !pSibling, cVert, !cSibling)
: refineFVar.getFractionalWeight(vert, pSibling, cVert, cSibling);
float wCrease = 1.0f - wCorner;
vWeight = wCrease * 0.75f + wCorner;
eWeight = wCrease * 0.125f;
}
dst[cVertValue].AddWithWeight(src[pEndValues[0]], eWeight);
dst[cVertValue].AddWithWeight(src[pEndValues[1]], eWeight);
dst[cVertValue].AddWithWeight(src[pVertValue], vWeight);
}
}
}
}
}
template <Sdc::SchemeType SCHEME, class T, class U, class U1, class U2>
inline void
PrimvarRefiner::limit(T const & src, U & dstPos, U1 * dstTan1Ptr, U2 * dstTan2Ptr) const {
Sdc::Scheme<SCHEME> scheme(_refiner._subdivOptions);
Vtr::internal::Level const & level = _refiner.getLevel(_refiner.GetMaxLevel());
int maxWeightsPerMask = 1 + 2 * level.getMaxValence();
bool hasTangents = (dstTan1Ptr && dstTan2Ptr);
int numMasks = 1 + (hasTangents ? 2 : 0);
Vtr::internal::StackBuffer<Index,33> indexBuffer(maxWeightsPerMask);
Vtr::internal::StackBuffer<float,99> weightBuffer(numMasks * maxWeightsPerMask);
float * vPosWeights = weightBuffer,
* ePosWeights = vPosWeights + 1,
* fPosWeights = ePosWeights + level.getMaxValence();
float * vTan1Weights = vPosWeights + maxWeightsPerMask,
* eTan1Weights = ePosWeights + maxWeightsPerMask,
* fTan1Weights = fPosWeights + maxWeightsPerMask;
float * vTan2Weights = vTan1Weights + maxWeightsPerMask,
* eTan2Weights = eTan1Weights + maxWeightsPerMask,
* fTan2Weights = fTan1Weights + maxWeightsPerMask;
Mask posMask( vPosWeights, ePosWeights, fPosWeights);
Mask tan1Mask(vTan1Weights, eTan1Weights, fTan1Weights);
Mask tan2Mask(vTan2Weights, eTan2Weights, fTan2Weights);
// This is a bit obscure -- assigning both parent and child as last level -- but
// this mask type was intended for another purpose. Consider one for the limit:
Vtr::internal::VertexInterface vHood(level, level);
for (int vert = 0; vert < level.getNumVertices(); ++vert) {
ConstIndexArray vEdges = level.getVertexEdges(vert);
// Incomplete vertices (present in sparse refinement) do not have their full
// topological neighborhood to determine a proper limit -- just leave the
// vertex at the refined location and continue to the next:
if (level.getVertexTag(vert)._incomplete || (vEdges.size() == 0)) {
dstPos[vert].Clear();
dstPos[vert].AddWithWeight(src[vert], 1.0);
if (hasTangents) {
(*dstTan1Ptr)[vert].Clear();
(*dstTan2Ptr)[vert].Clear();
}
continue;
}
//
// Limit masks require the subdivision Rule for the vertex in order to deal
// with infinitely sharp features correctly -- including boundaries and corners.
// The vertex neighborhood is minimally defined with vertex and edge counts.
//
Sdc::Crease::Rule vRule = level.getVertexRule(vert);
// This is a bit obscure -- child vertex index will be ignored here
vHood.SetIndex(vert, vert);
if (hasTangents) {
scheme.ComputeVertexLimitMask(vHood, posMask, tan1Mask, tan2Mask, vRule);
} else {
scheme.ComputeVertexLimitMask(vHood, posMask, vRule);
}
//
// Gather the neighboring vertices of this vertex -- the vertices opposite its
// incident edges, and the opposite vertices of its incident faces:
//
Index * eIndices = indexBuffer;
Index * fIndices = indexBuffer + vEdges.size();
for (int i = 0; i < vEdges.size(); ++i) {
ConstIndexArray eVerts = level.getEdgeVertices(vEdges[i]);
eIndices[i] = (eVerts[0] == vert) ? eVerts[1] : eVerts[0];
}
if (posMask.GetNumFaceWeights() || (hasTangents && tan1Mask.GetNumFaceWeights())) {
ConstIndexArray vFaces = level.getVertexFaces(vert);
ConstLocalIndexArray vInFace = level.getVertexFaceLocalIndices(vert);
for (int i = 0; i < vFaces.size(); ++i) {
ConstIndexArray fVerts = level.getFaceVertices(vFaces[i]);
LocalIndex vOppInFace = (vInFace[i] + 2);
if (vOppInFace >= fVerts.size()) vOppInFace -= (LocalIndex)fVerts.size();
fIndices[i] = level.getFaceVertices(vFaces[i])[vOppInFace];
}
}
//
// Combine the weights and indices for position and tangents. As with applying
// refinment masks to vertex data, in order to improve numerical precision, its
// better to apply smaller weights first, so begin with the face-weights followed
// by the edge-weights and the vertex weight last.
//
dstPos[vert].Clear();
for (int i = 0; i < posMask.GetNumFaceWeights(); ++i) {
dstPos[vert].AddWithWeight(src[fIndices[i]], fPosWeights[i]);
}
for (int i = 0; i < posMask.GetNumEdgeWeights(); ++i) {
dstPos[vert].AddWithWeight(src[eIndices[i]], ePosWeights[i]);
}
dstPos[vert].AddWithWeight(src[vert], vPosWeights[0]);
//
// Apply the tangent masks -- both will have the same number of weights and
// indices (one tangent may be "padded" to accomodate the other), but these
// may differ from those of the position:
//
if (hasTangents) {
assert(tan1Mask.GetNumFaceWeights() == tan2Mask.GetNumFaceWeights());
assert(tan1Mask.GetNumEdgeWeights() == tan2Mask.GetNumEdgeWeights());
U1 & dstTan1 = *dstTan1Ptr;
U2 & dstTan2 = *dstTan2Ptr;
dstTan1[vert].Clear();
dstTan2[vert].Clear();
for (int i = 0; i < tan1Mask.GetNumFaceWeights(); ++i) {
dstTan1[vert].AddWithWeight(src[fIndices[i]], fTan1Weights[i]);
dstTan2[vert].AddWithWeight(src[fIndices[i]], fTan2Weights[i]);
}
for (int i = 0; i < tan1Mask.GetNumEdgeWeights(); ++i) {
dstTan1[vert].AddWithWeight(src[eIndices[i]], eTan1Weights[i]);
dstTan2[vert].AddWithWeight(src[eIndices[i]], eTan2Weights[i]);
}
dstTan1[vert].AddWithWeight(src[vert], vTan1Weights[0]);
dstTan2[vert].AddWithWeight(src[vert], vTan2Weights[0]);
}
}
}
template <Sdc::SchemeType SCHEME, class T, class U>
inline void
PrimvarRefiner::limitFVar(T const & src, U * dst, int channel) const {
Sdc::Scheme<SCHEME> scheme(_refiner._subdivOptions);
Vtr::internal::Level const & level = _refiner.getLevel(_refiner.GetMaxLevel());
Vtr::internal::FVarLevel const & fvarChannel = level.getFVarLevel(channel);
int maxWeightsPerMask = 1 + 2 * level.getMaxValence();
Vtr::internal::StackBuffer<float,33> weightBuffer(maxWeightsPerMask);
Vtr::internal::StackBuffer<Index,16> vEdgeBuffer(level.getMaxValence());
// This is a bit obscure -- assign both parent and child as last level
Vtr::internal::VertexInterface vHood(level, level);
for (int vert = 0; vert < level.getNumVertices(); ++vert) {
ConstIndexArray vEdges = level.getVertexEdges(vert);
ConstIndexArray vValues = fvarChannel.getVertexValues(vert);
// Incomplete vertices (present in sparse refinement) do not have their full
// topological neighborhood to determine a proper limit -- just leave the
// values (perhaps more than one per vertex) at the refined location.
//
// The same can be done if the face-varying channel is purely linear.
//
bool isIncomplete = (level.getVertexTag(vert)._incomplete || (vEdges.size() == 0));
if (isIncomplete || fvarChannel.isLinear()) {
for (int i = 0; i < vValues.size(); ++i) {
Vtr::Index vValue = vValues[i];
dst[vValue].Clear();
dst[vValue].AddWithWeight(src[vValue], 1.0f);
}
continue;
}
bool fvarVertMatchesVertex = fvarChannel.valueTopologyMatches(vValues[0]);
if (fvarVertMatchesVertex) {
// Assign the mask weights to the common buffer and compute the mask:
//
float * vWeights = weightBuffer,
* eWeights = vWeights + 1,
* fWeights = eWeights + vEdges.size();
Mask vMask(vWeights, eWeights, fWeights);
vHood.SetIndex(vert, vert);
scheme.ComputeVertexLimitMask(vHood, vMask, level.getVertexRule(vert));
//
// Apply mask to corresponding FVar values for neighboring vertices:
//
Vtr::Index vValue = vValues[0];
dst[vValue].Clear();
if (vMask.GetNumFaceWeights() > 0) {
assert(!vMask.AreFaceWeightsForFaceCenters());
ConstIndexArray vFaces = level.getVertexFaces(vert);
ConstLocalIndexArray vInFace = level.getVertexFaceLocalIndices(vert);
for (int i = 0; i < vFaces.size(); ++i) {
ConstIndexArray faceValues = fvarChannel.getFaceValues(vFaces[i]);
LocalIndex vOppInFace = vInFace[i] + 2;
if (vOppInFace >= faceValues.size()) vOppInFace -= faceValues.size();
Index vValueOppositeFace = faceValues[vOppInFace];
dst[vValue].AddWithWeight(src[vValueOppositeFace], fWeights[i]);
}
}
if (vMask.GetNumEdgeWeights() > 0) {
Index * vEdgeValues = vEdgeBuffer;
fvarChannel.getVertexEdgeValues(vert, vEdgeValues);
for (int i = 0; i < vEdges.size(); ++i) {
dst[vValue].AddWithWeight(src[vEdgeValues[i]], eWeights[i]);
}
}
dst[vValue].AddWithWeight(src[vValue], vWeights[0]);
} else {
//
// Sibling FVar values associated with a vertex will be either a corner or a crease:
//
for (int i = 0; i < vValues.size(); ++i) {
Vtr::Index vValue = vValues[i];
dst[vValue].Clear();
if (fvarChannel.getValueTag(vValue).isCorner()) {
dst[vValue].AddWithWeight(src[vValue], 1.0f);
} else {
Index vEndValues[2];
fvarChannel.getVertexCreaseEndValues(vert, i, vEndValues);
dst[vValue].AddWithWeight(src[vEndValues[0]], 1.0f/6.0f);
dst[vValue].AddWithWeight(src[vEndValues[1]], 1.0f/6.0f);
dst[vValue].AddWithWeight(src[vValue], 2.0f/3.0f);
}
}
}
}
}
} // end namespace Far
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif /* OPENSUBDIV3_FAR_PRIMVAR_REFINER_H */
| {
"content_hash": "d640c2e93a28b2638b5b7697a810d6ec",
"timestamp": "",
"source": "github",
"line_count": 1251,
"max_line_length": 127,
"avg_line_length": 41.00959232613909,
"alnum_prop": 0.6124788024092158,
"repo_name": "virtuallynaked/virtually-naked",
"id": "e692cd3208524fc2e3cfda0e0fac08ee3aef016a",
"size": "51303",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "third-party/OpenSubdiv/include/opensubdiv/far/primvarrefiner.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "918589"
},
{
"name": "C++",
"bytes": "18883"
},
{
"name": "HLSL",
"bytes": "72308"
}
],
"symlink_target": ""
} |
blurb: |
Word embeddings for recommender systems
title: Factorization meets the item embedding
venue: Recommender Systems
year: 2016
author: Dawen Liang, Jaan Altosaar, Laurent Charlin, and David Blei
link: https://dl.acm.org/citation.cfm?id=2959182
pdf: 2016_Liang-Altosaar-Charlin-Blei_CoFactor.pdf
code: https://github.com/dawenl/cofactor
talk: https://www.youtube.com/watch?v=jE-IwDxFhAA
thumb: like-thumb.png
bibtex: |
@inproceedings{Liang:2016:FMI:2959100.2959182,
author = {Liang, Dawen and Altosaar, Jaan and Charlin, Laurent and Blei, David M.},
title = {Factorization Meets the Item Embedding: Regularizing Matrix Factorization with Item Co-occurrence},
booktitle = {Proceedings of the 10th ACM Conference on Recommender Systems},
series = {RecSys '16},
year = {2016},
isbn = {978-1-4503-4035-9},
location = {Boston, Massachusetts, USA},
pages = {59--66},
numpages = {8},
url = {http://doi.acm.org/10.1145/2959100.2959182},
doi = {10.1145/2959100.2959182},
acmid = {2959182},
publisher = {ACM},
address = {New York, NY, USA},
keywords = {collaborative filtering, implicit feedback, item embedding, matrix factorization},
}
--- | {
"content_hash": "7c358a34a8d3f98331852cfa41a19ad7",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 113,
"avg_line_length": 39.516129032258064,
"alnum_prop": 0.6979591836734694,
"repo_name": "altosaar/jaan.io",
"id": "1ad2733dabf91044e8bae052ab0af9cab5ebe6e4",
"size": "1229",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_papers/2016-08-05-factorization-item-embedding.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "59899"
},
{
"name": "HTML",
"bytes": "22365313"
},
{
"name": "JavaScript",
"bytes": "11793"
},
{
"name": "Jupyter Notebook",
"bytes": "3395"
},
{
"name": "Ruby",
"bytes": "4903"
},
{
"name": "SCSS",
"bytes": "35321"
}
],
"symlink_target": ""
} |
/*================ FUNCTIONS =================*/
/*================ MIXINS =================*/
/*================ CLASSES =================*/
.popover {
background: white;
border: 1px solid #DD3416;
border-radius: 3px;
box-shadow: 0px 1px 2px 0px rgba(0, 0, 0, 0.25);
z-index: 100;
transition: all, 300ms; }
.has-shadow {
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15); }
.cf {
/* For modern browsers */
/* For IE 6/7 (trigger hasLayout) */
*zoom: 1; }
.cf:before, .cf:after {
content: "";
display: table; }
.cf:after {
clear: both; }
/*================ FLEXBOX =================*/
form.form-block, .accounts-dialog.form-block {
background: #e7eff2;
border-radius: 3px;
margin-bottom: 10px;
padding: 10px; }
form > div, .accounts-dialog > div {
/* For modern browsers */
/* For IE 6/7 (trigger hasLayout) */
*zoom: 1; }
form > div:before, form > div:after, .accounts-dialog > div:before, .accounts-dialog > div:after {
content: "";
display: table; }
form > div:after, .accounts-dialog > div:after {
clear: both; }
form .control-group, form .form-group, form .at-input, .accounts-dialog .control-group, .accounts-dialog .form-group, .accounts-dialog .at-input {
/* For modern browsers */
/* For IE 6/7 (trigger hasLayout) */
*zoom: 1;
margin-bottom: 15px; }
form .control-group:before, form .control-group:after, form .form-group:before, form .form-group:after, form .at-input:before, form .at-input:after, .accounts-dialog .control-group:before, .accounts-dialog .control-group:after, .accounts-dialog .form-group:before, .accounts-dialog .form-group:after, .accounts-dialog .at-input:before, .accounts-dialog .at-input:after {
content: "";
display: table; }
form .control-group:after, form .form-group:after, form .at-input:after, .accounts-dialog .control-group:after, .accounts-dialog .form-group:after, .accounts-dialog .at-input:after {
clear: both; }
form .control-group > label, form .form-group > label, form .at-input > label, .accounts-dialog .control-group > label, .accounts-dialog .form-group > label, .accounts-dialog .at-input > label {
font-weight: bold;
display: block; }
@media screen and (max-width: 600px) {
form .control-group > label, form .form-group > label, form .at-input > label, .accounts-dialog .control-group > label, .accounts-dialog .form-group > label, .accounts-dialog .at-input > label {
margin-bottom: 5px; } }
@media screen and (min-width: 600px) {
form .control-group > label, form .form-group > label, form .at-input > label, .accounts-dialog .control-group > label, .accounts-dialog .form-group > label, .accounts-dialog .at-input > label {
float: left;
margin-right: 10px; } }
form .control-group.hide-label label, form .form-group.hide-label label, form .at-input.hide-label label, .accounts-dialog .control-group.hide-label label, .accounts-dialog .form-group.hide-label label, .accounts-dialog .at-input.hide-label label {
display: none; }
form .control-group.hide-label .controls, form .form-group.hide-label .controls, form .at-input.hide-label .controls, .accounts-dialog .control-group.hide-label .controls, .accounts-dialog .form-group.hide-label .controls, .accounts-dialog .at-input.hide-label .controls {
margin-left: 0; }
form .control-group .controls, form .form-group .controls, form .at-input .controls, .accounts-dialog .control-group .controls, .accounts-dialog .form-group .controls, .accounts-dialog .at-input .controls {
position: relative; }
@media screen and (min-width: 600px) {
form .control-group .controls, form .form-group .controls, form .at-input .controls, .accounts-dialog .control-group .controls, .accounts-dialog .form-group .controls, .accounts-dialog .at-input .controls {
margin-left: 200px; } }
form .control-group .controls .inline-link, form .form-group .controls .inline-link, form .at-input .controls .inline-link, .accounts-dialog .control-group .controls .inline-link, .accounts-dialog .form-group .controls .inline-link, .accounts-dialog .at-input .controls .inline-link {
position: absolute;
display: block;
top: 2px;
right: 8px; }
form .control-group .controls .inline-link.loading, form .form-group .controls .inline-link.loading, form .at-input .controls .inline-link.loading, .accounts-dialog .control-group .controls .inline-link.loading, .accounts-dialog .form-group .controls .inline-link.loading, .accounts-dialog .at-input .controls .inline-link.loading {
background: url("/packages/telescope_core/public/img/loading.svg") center center no-repeat;
height: 22px;
width: 18px;
font: 0/0 a;
text-shadow: none;
color: transparent; }
form .control-group .controls label, form .form-group .controls label, form .at-input .controls label, .accounts-dialog .control-group .controls label, .accounts-dialog .form-group .controls label, .accounts-dialog .at-input .controls label {
display: block; }
form .control-group .controls label.inline, form .form-group .controls label.inline, form .at-input .controls label.inline, .accounts-dialog .control-group .controls label.inline, .accounts-dialog .form-group .controls label.inline, .accounts-dialog .at-input .controls label.inline {
display: inline-block;
margin-bottom: 0; }
form .control-group.inline, form .form-group.inline, form .at-input.inline, .accounts-dialog .control-group.inline, .accounts-dialog .form-group.inline, .accounts-dialog .at-input.inline {
margin-bottom: 10px; }
form .control-group.inline .controls, form .form-group.inline .controls, form .at-input.inline .controls, .accounts-dialog .control-group.inline .controls, .accounts-dialog .form-group.inline .controls, .accounts-dialog .at-input.inline .controls {
margin-left: 0px;
width: 80%;
float: left; }
form .control-group.inline .submit, form .form-group.inline .submit, form .at-input.inline .submit, .accounts-dialog .control-group.inline .submit, .accounts-dialog .form-group.inline .submit, .accounts-dialog .at-input.inline .submit {
float: right; }
form .form-actions, form .form-group, .accounts-dialog .form-actions, .accounts-dialog .form-group {
/* For modern browsers */
/* For IE 6/7 (trigger hasLayout) */
*zoom: 1; }
form .form-actions:before, form .form-actions:after, form .form-group:before, form .form-group:after, .accounts-dialog .form-actions:before, .accounts-dialog .form-actions:after, .accounts-dialog .form-group:before, .accounts-dialog .form-group:after {
content: "";
display: table; }
form .form-actions:after, form .form-group:after, .accounts-dialog .form-actions:after, .accounts-dialog .form-group:after {
clear: both; }
form .form-actions a, form .form-group a, .accounts-dialog .form-actions a, .accounts-dialog .form-group a {
float: left;
display: block; }
form .form-actions .button, form .form-actions .btn, form .form-group .button, form .form-group .btn, .accounts-dialog .form-actions .button, .accounts-dialog .form-actions .btn, .accounts-dialog .form-group .button, .accounts-dialog .form-group .btn {
float: right; }
form input[type="text"], form input[type="password"], form input[type="number"], form input[type="email"], form textarea, form .login-form input, .accounts-dialog input[type="text"], .accounts-dialog input[type="password"], .accounts-dialog input[type="number"], .accounts-dialog input[type="email"], .accounts-dialog textarea, .accounts-dialog .login-form input {
display: block;
padding: 5px 6px;
width: 100%;
font-size: 14px;
-webkit-box-sizing: border-box;
/* Safari/Chrome, other WebKit */
-moz-box-sizing: border-box;
/* Firefox, other Gecko */
box-sizing: border-box;
/* Opera/IE 8+ */
border: 1px solid #b5b0b0;
transition: #b5b0b0, 500ms; }
form input[type="text"]:focus, form input[type="password"]:focus, form input[type="number"]:focus, form input[type="email"]:focus, form textarea:focus, form .login-form input:focus, .accounts-dialog input[type="text"]:focus, .accounts-dialog input[type="password"]:focus, .accounts-dialog input[type="number"]:focus, .accounts-dialog input[type="email"]:focus, .accounts-dialog textarea:focus, .accounts-dialog .login-form input:focus {
outline: none;
border-color: #DD3416;
box-shadow: 0px 0px 5px 0px rgba(221, 52, 22, 0.3); }
form input[type="text"][type="number"], form input[type="password"][type="number"], form input[type="number"][type="number"], form input[type="email"][type="number"], form textarea[type="number"], form .login-form input[type="number"], .accounts-dialog input[type="text"][type="number"], .accounts-dialog input[type="password"][type="number"], .accounts-dialog input[type="number"][type="number"], .accounts-dialog input[type="email"][type="number"], .accounts-dialog textarea[type="number"], .accounts-dialog .login-form input[type="number"] {
width: 30%; }
form input[type="text"]:disabled, form input[type="password"]:disabled, form input[type="number"]:disabled, form input[type="email"]:disabled, form textarea:disabled, form .login-form input:disabled, .accounts-dialog input[type="text"]:disabled, .accounts-dialog input[type="password"]:disabled, .accounts-dialog input[type="number"]:disabled, .accounts-dialog input[type="email"]:disabled, .accounts-dialog textarea:disabled, .accounts-dialog .login-form input:disabled {
background: #eee;
color: #b3c1c6; }
form input[type="text"], form input[type="password"], form input[type="number"], form .login-form input, .accounts-dialog input[type="text"], .accounts-dialog input[type="password"], .accounts-dialog input[type="number"], .accounts-dialog .login-form input {
height: 30px;
line-height: 20px; }
form input[disabled='disabled'], .accounts-dialog input[disabled='disabled'] {
color: #b3c1c6;
background: #e7eff2; }
form textarea, .accounts-dialog textarea {
min-height: 100px;
line-height: 1.4; }
form .note, .accounts-dialog .note {
padding: 5px 0;
color: #b3c1c6;
font-size: 80%; }
input[type="submit"], button, .button, .btn {
-webkit-appearance: none;
border-radius: 3px;
text-align: center;
display: block;
max-width: 300px;
padding: 10px 12px;
line-height: 1;
border: none;
font-size: 15px;
cursor: pointer;
margin: 0;
color: white;
font-weight: bold;
white-space: nowrap; }
input[type="submit"].disabled, input[type="submit"].loading, button.disabled, button.loading, .button.disabled, .button.loading, .btn.disabled, .btn.loading {
background: #dfdbdb !important;
pointer-events: none;
color: #a4a9ab; }
input[type="submit"].inline, button.inline, .button.inline, .btn.inline {
display: inline-block; }
input[type="submit"].loading, button.loading, .button.loading, .btn.loading {
position: relative;
color: #dfdbdb !important; }
input[type="submit"].loading:after, button.loading:after, .button.loading:after, .btn.loading:after {
position: absolute;
top: 50%;
left: 50%;
margin: -10px 0 0 -10px;
content: " ";
display: block;
background: url("/packages/telescope_core/public/img/loading.svg");
height: 20px;
width: 20px;
background-size: 20px 20px; }
.btn-primary {
background: #DD3416; }
.btn-primary:link, .btn-primary:hover, .btn-primary:active, .btn-primary:visited {
color: white; }
input[type="search"] {
font-size: 14px; }
.twitter-signup {
margin-bottom: 20px;
padding-bottom: 20px;
border-bottom: 1px solid #dfdbdb; }
.twitter-signup .twitter-button {
background: #00aced; }
.category-slug {
font-size: 12px;
float: left;
width: 80%;
display: block; }
.ui-autocomplete {
background: white;
width: 200px !important;
padding: 10px;
font-size: 14px;
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15); }
.help-block {
color: #b3c1c6;
margin-bottom: 15px; }
#editor > iframe {
border: 1px solid #B5B0B0; }
.comment-field {
margin-bottom: 10px; }
.af-fieldgroup-heading, .af-fieldGroup-heading {
display: block;
width: 100%;
padding-bottom: 5px;
margin-bottom: 15px;
border-bottom: 1px solid #B5B0B0;
color: #b3c1c6;
font-size: 20px; }
fieldset {
margin-bottom: 30px; }
.instructions-block {
margin-top: 5px;
display: block;
font-size: 80%;
color: #b3c1c6; }
.private-field {
color: #DD3416; }
.finish-signup-message {
text-align: center;
margin-bottom: 10px;
font-size: 16px; }
.form-well {
background: #fffcea;
padding: 20px;
margin-bottom: 40px; }
.form-module {
border-bottom: 1px solid #B5B0B0;
padding-bottom: 40px;
margin: 0 auto 40px auto; }
a {
text-decoration: none; }
a, a:link, a:visited, a:active {
color: currentColor;
font-weight: bold; }
a:hover {
color: #DD3416; }
.icon-circle {
border-radius: 100%;
border: 1px solid currentColor; }
.fa-fw {
width: 1.5em; }
.app-loading {
height: 100vh; }
.loader {
min-height: 70px;
height: 100%;
display: flex;
align-items: center;
justify-content: center; }
.loader div {
background: url("/packages/telescope_core/public/img/loading.svg") center center no-repeat;
font: 0/0 a;
text-shadow: none;
color: transparent;
width: 24px;
height: 30px;
margin: 10px 0; }
.hidden {
display: none; }
.visible {
display: block; }
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
border: 0; }
.sr-only-focusable:active,
.sr-only-focusable:focus {
position: static;
width: auto;
height: auto;
margin: 0;
overflow: visible;
clip: auto; }
.overlay {
position: fixed;
top: 0;
left: 0;
height: 100%;
width: 100%;
z-index: 50; }
#spinner {
margin: 100px 0; }
.debug {
display: none; }
.footer {
text-align: center;
padding: 10px 0 70px 0;
font-size: 14px; }
.footer.absolute {
position: absolute; }
#login-buttons .loading {
display: none; }
#loading, .loading-page {
height: 300px; }
.notifications-toggle {
background: white;
margin-bottom: 10px;
padding: 15px; }
.search-date-header {
background: #e7eff2; }
.search-date-header th {
/* For modern browsers */
/* For IE 6/7 (trigger hasLayout) */
*zoom: 1; }
.search-date-header th:before, .search-date-header th:after {
content: "";
display: table; }
.search-date-header th:after {
clear: both; }
.search-date-header .search-date {
display: block;
float: left;
font-weight: bold; }
.search-date-header .search-count {
font-size: 13px;
display: block;
float: right; }
.no-rights {
text-align: center; }
.markdown img {
max-width: 100%; }
.markdown ul, .markdown ol, .markdown p, .markdown pre, .markdown blockquote, .markdown h1, .markdown h2, .markdown h3, .markdown h4, .markdown h5 {
margin-bottom: 1em;
line-height: 1.7; }
.markdown ul:last-child, .markdown ol:last-child, .markdown p:last-child, .markdown pre:last-child, .markdown blockquote:last-child, .markdown h1:last-child, .markdown h2:last-child, .markdown h3:last-child, .markdown h4:last-child, .markdown h5:last-child {
margin-bottom: 0; }
.markdown strong {
font-weight: bold; }
.markdown em {
font-style: italic; }
.markdown ul, .markdown ol {
padding-left: 18px; }
.markdown ul {
list-style-type: disc; }
.markdown ol {
list-style-type: decimal; }
.markdown a:link, .markdown a:visited, .markdown a:active {
color: #7ac0e4; }
.markdown a:hover {
color: #DD3416; }
.markdown h1, .markdown h2, .markdown h3, .markdown h4, .markdown h5 {
font-weight: bold; }
.markdown h1 {
font-size: 36px; }
.markdown h2 {
font-size: 24px; }
.markdown h3 {
font-size: 18px; }
.markdown h4 {
font-size: 16px; }
.markdown h5 {
font-size: 14px; }
.markdown code {
font-family: monospace;
margin: 0 2px;
padding: 0px 5px;
border: 1px solid #ddd;
background-color: #f8f8f8;
border-radius: 3px; }
.markdown pre {
padding: 20px;
border: 1px solid #ddd;
background-color: #f8f8f8;
overflow-x: scroll; }
.markdown pre code {
border: none;
background: none; }
.markdown blockquote {
border-left: 3px solid #eee;
padding-left: 20px; }
table {
width: 100%; }
table tr {
border-bottom: 1px solid #eee; }
table tr td, table tr th {
padding: 4px;
vertical-align: middle; }
table thead tr td, table thead tr th {
font-weight: bold; }
html, body, input, button {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; }
h1, h2, h3, h4, h5, ul, ol, li, p, pre, div {
line-height: 1.5; }
h1 {
font-size: 40px; }
h2 {
font-size: 30px; }
h3 {
font-size: 20px; }
h4 {
font-size: 16px; }
li {
margin: 0 0 10px 0; }
.important {
color: #DD3416; }
.admin-wrapper {
padding: 0;
margin-bottom: 10px; }
@media screen and (min-width: 600px) {
.admin-wrapper {
display: flex; } }
.admin-menu {
background: rgba(255, 255, 255, 0.8);
padding: 20px; }
@media screen and (min-width: 600px) {
.admin-menu {
width: 200px; } }
.admin-contents {
background: white;
padding: 20px; }
@media screen and (min-width: 600px) {
.admin-contents {
border-left: 1px solid #ccc;
width: 100%; } }
.avatar-xsmall .avatar-initials {
font-size: 12px;
line-height: 20px; }
.avatar-small {
height: 24px;
width: 24px;
min-width: 0px; }
.avatar-small .avatar-initials {
font-size: 13px;
line-height: 24px; }
.avatar-medium {
height: 30px;
width: 30px; }
.avatar-medium .avatar-initials {
font-size: 14px;
line-height: 30px; }
.avatar-initials {
font-weight: normal;
overflow: hidden; }
.banner.banner {
background: rgba(255, 255, 255, 0.7);
margin-bottom: 10px;
position: relative;
overflow: hidden; }
@media screen and (max-width: 600px) {
.banner.banner {
padding: 20px; } }
@media screen and (min-width: 600px) {
.banner.banner {
padding: 20px 60px; } }
.banner-heading {
border-bottom: 1px solid #b5b0b0;
font-weight: bold;
color: #a4a9ab;
padding-bottom: 10px;
margin-bottom: 10px; }
.banner-dismiss, .banner-dismiss:link, .banner-dismiss:visited {
display: block;
position: absolute;
height: 30px;
width: 30px;
border-radius: 100%;
background: rgba(0, 0, 0, 0.15);
color: white;
top: 50%;
margin-top: -15px;
right: 15px;
font-size: 16px;
text-align: center;
vertical-align: middle;
line-height: 30px; }
@media screen and (max-width: 600px) {
.banner-dismiss, .banner-dismiss:link, .banner-dismiss:visited {
top: 10px;
right: 10px;
margin-top: 0px; } }
.banner-dismiss:hover {
color: inherit; }
.error, .at-error {
background: #DD3416;
margin-bottom: 10px;
text-align: center;
color: white;
padding: 20px; }
.error a:link, .error a:hover, .at-error a:link, .at-error a:hover {
color: white; }
.menu-dropdown .menu-items {
color: #333; }
.header {
background: #444444;
margin-bottom: 10px;
padding: 15px;
color: white; }
@media screen and (max-width: 600px) {
.header {
height: 50px;
padding: 5px 10px;
position: fixed;
width: 100%; } }
.header a, .header a:link, .header a:visited {
color: inherit; }
.header .nav {
list-style-type: none; }
.header .nav > li {
margin-bottom: 0; }
.header .nav > li:last-child .header-submodule {
margin-right: 0px; }
@media screen and (max-width: 600px) {
.logo {
font-size: 24px;
overflow: hidden;
height: 100%; }
.logo a {
margin: 0 auto; } }
@media screen and (max-width: 300px) {
.logo {
font-size: 18px; } }
@media screen and (max-width: 600px) {
.header .logo {
padding: 0 50px; } }
.mobile-nav .logo {
padding: 20px;
font-size: 30px; }
.mobile-nav .logo, .mobile-nav .logo a {
color: white; }
@media screen and (max-width: 600px) {
.mobile-nav .logo {
display: none; } }
.logo-text {
white-space: nowrap; }
@media screen and (max-width: 600px) {
.logo-image {
height: 100%; } }
.logo-image a {
display: block;
height: 100%; }
.logo-image img {
display: block;
max-height: 100%;
max-width: 100%; }
.account-link {
display: inline-block; }
*, *:before, *:after {
box-sizing: border-box;
line-height: 1.5; }
html, body, .outer-wrapper {
height: 100%; }
body {
background: #eee;
font-size: 14px; }
@media screen and (max-width: 600px) {
body {
overflow-x: hidden; } }
.outer-wrapper {
position: relative; }
.content-wrapper {
padding: 0 10px;
max-width: 1200px;
margin: 0 auto; }
@media screen and (max-width: 600px) {
.content-wrapper {
overflow-x: hidden;
overflow-y: hidden;
padding-top: 70px; } }
.grid-module, .at-form {
background: white;
padding: 15px;
margin-bottom: 10px; }
.loading-module {
height: 70px;
position: relative; }
@media screen and (min-width: 600px) {
.mobile-only {
display: none !important; } }
@media screen and (max-width: 600px) {
.desktop-only {
display: none !important; } }
.mobile-nav {
position: fixed;
overflow: auto;
height: 100%;
top: 0px;
bottom: 0px;
background: #444;
color: white;
box-shadow: inset -3px 0px 7px rgba(0, 0, 0, 0.5);
z-index: 100;
left: -200px;
left: calc((100% - 60px) * -1);
width: 200px;
width: calc(100% - 60px); }
.mobile-nav .mobile-menu-item.menu {
display: block; }
.mobile-nav .menu-contents li {
margin: 0; }
.mobile-nav .button, .mobile-nav .btn {
max-width: none; }
.mobile-nav, .inner-wrapper {
transition: all, 300ms, ease-out, 0ms; }
.inner-wrapper {
position: relative;
left: 0px; }
.mobile-nav-open {
overflow: hidden; }
.mobile-nav-open .mobile-nav {
left: 0px; }
.mobile-nav-open .outer-wrapper {
overflow: hidden; }
.mobile-nav-open .outer-wrapper .inner-wrapper {
left: 200px;
left: calc(100% - 60px); }
@media screen and (max-width: 600px) {
.desktop-nav {
display: none; } }
.mobile-menu .header-module, .mobile-menu .mobile-menu-item {
display: block;
margin-right: 0px; }
.mobile-menu .mobile-menu-item {
margin-bottom: 0;
border-bottom: 1px rgba(255, 255, 255, 0.2) solid; }
.mobile-menu .mobile-menu-item:last-child {
border: none; }
.mobile-menu .mobile-menu-item .menu-expanded {
background: rgba(255, 255, 255, 0.1); }
.mobile-menu .menu-description {
display: none; }
.mobile-menu .sign-up {
border-bottom: 1px rgba(255, 255, 255, 0.2) solid;
margin-right: 0px; }
.mobile-menu a {
display: block;
height: auto;
line-height: inherit;
font-size: 15px; }
.mobile-menu a, .mobile-menu a:link, .mobile-menu a:visited {
color: white; }
.mobile-menu .mobile-menu-item > a, .mobile-menu .menu-top-level, .mobile-menu .sign-in, .mobile-menu .sign-up {
padding: 10px; }
.mobile-menu .menu-menu {
display: none;
background: #333; }
.mobile-menu .menu-item {
margin-bottom: 0;
border-top: 1px rgba(255, 255, 255, 0.2) solid;
padding: 0; }
.mobile-menu .menu-label, .mobile-menu .menu-item-label-wrapper {
padding: 10px; }
.mobile-menu .menu-items, .mobile-menu .menu-child-items {
margin: 0;
border-left: 15px solid rgba(255, 255, 255, 0.1);
padding-left: 0; }
.mobile-menu .submit-button {
padding: 10px;
border-bottom: 1px rgba(255, 255, 255, 0.2) solid; }
.mobile-menu .btn, .mobile-menu .button {
display: block;
width: 100%;
max-width: none; }
.mobile-menu-button {
position: absolute;
left: 10px;
display: inline-block;
padding: 4px;
top: 50%;
margin-top: -17px;
text-align: center;
width: 30px;
z-index: 100; }
.notification-item {
margin-bottom: 10px; }
.side-nav .mark-as-read {
display: block;
width: 100%; }
.mark-as-read {
width: 100%; }
.posts-wrapper {
background: none; }
.more-button {
display: block; }
.users-dashboard-heading {
margin-bottom: -50px; }
.users-dashboard a {
color: #5e5e5e;
transition: color .5s; }
.users-dashboard a:hover {
color: #DD3416; }
.users-dashboard .reactive-table-filter {
margin: 5px 7px 25px 0; }
.users-dashboard .reactive-table-filter span {
font-size: 1.15em;
color: #444444;
font-weight: bold; }
.users-dashboard .reactive-table-filter input {
width: 170px;
height: 30px;
font-size: 1em;
padding: .7em;
margin-left: .3em;
transition: width .7s ease-in-out; }
.users-dashboard .reactive-table-filter input:focus {
width: 220px;
outline: none; }
.users-dashboard td {
text-align: center; }
.users-dashboard td .time-ago {
font-size: .9em;
color: #6a6a6a; }
.users-dashboard td.actions li {
margin-bottom: .25em; }
.users-dashboard td.actions li:last-child {
margin-bottom: .15em; }
.users-dashboard .reactive-table-navigation {
margin-top: 30px; }
.user-profile-avatar {
margin-bottom: 20px; }
.edit-profile-button {
margin-top: 20px; }
.user-info {
max-width: 400px; }
.user-info tr:last-child {
border: none; }
/*# sourceMappingURL=.screen.scss.map */ | {
"content_hash": "12e22885c27b1a29b8399b13f982e8a8",
"timestamp": "",
"source": "github",
"line_count": 861,
"max_line_length": 546,
"avg_line_length": 29.33101045296167,
"alnum_prop": 0.6549853488556269,
"repo_name": "benobab/Telescope---Test-",
"id": "12b22bcfdfcb37946ad1c653a29c0743eee6d5f3",
"size": "25254",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": ".demeteorized/bundle/programs/web.browser/packages/telescope_theme-base/lib/client/scss/screen.scss.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "137794"
},
{
"name": "HTML",
"bytes": "59667"
},
{
"name": "JavaScript",
"bytes": "11226596"
},
{
"name": "Shell",
"bytes": "121"
}
],
"symlink_target": ""
} |
@implementation AutoSizeCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
self.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
self.textLabel.numberOfLines = 0;
self.textLabel.translatesAutoresizingMaskIntoConstraints = NO;
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-6-[bodyLabel]-6-|" options:0 metrics:nil views:@{ @"bodyLabel": self.textLabel }]];
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-6-[bodyLabel]-6-|" options:0 metrics:nil views:@{ @"bodyLabel": self.textLabel }]];
}
return self;
}
- (void)layoutSubviews
{
[super layoutSubviews];
// Make sure the contentView does a layout pass here so that its subviews have their frames set, which we
// need to use to set the preferredMaxLayoutWidth below.
[self.contentView setNeedsLayout];
[self.contentView layoutIfNeeded];
// Set the preferredMaxLayoutWidth of the mutli-line bodyLabel based on the evaluated width of the label's frame,
// as this will allow the text to wrap correctly, and as a result allow the label to take on the correct height.
self.textLabel.preferredMaxLayoutWidth = CGRectGetWidth(self.textLabel.frame);
}
@end
| {
"content_hash": "67fe33313c8440c8bdc132d038b86161",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 178,
"avg_line_length": 43.515151515151516,
"alnum_prop": 0.7277158774373259,
"repo_name": "nightfade/iOSExamples-AutoSizingTableCells",
"id": "8f0c599a111696369d931010c9bbb67aa0bdb983",
"size": "1610",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "AutoSizingTableCells/AutoSizeCell.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "6179"
}
],
"symlink_target": ""
} |
create table Attachment (
id bigint generated by default as identity (start with 1),
accessType integer,
attachedAt timestamp,
attachmentContentId bigint not null,
contentType varchar(255),
name varchar(255),
attachment_size integer,
attachedBy_id varchar(255),
TaskData_Attachments_Id bigint,
primary key (id)
);
create table AuditTaskImpl (
id bigint generated by default as identity (start with 1),
activationTime timestamp,
actualOwner varchar(255),
createdBy varchar(255),
createdOn timestamp,
deploymentId varchar(255),
description varchar(255),
dueDate timestamp,
name varchar(255),
parentId bigint not null,
priority integer not null,
processId varchar(255),
processInstanceId bigint not null,
processSessionId bigint not null,
status varchar(255),
taskId bigint,
workItemId bigint,
lastModificationDate timestamp,
primary key (id)
);
create table BAMTaskSummary (
pk bigint generated by default as identity (start with 1),
createdDate timestamp,
duration bigint,
endDate timestamp,
processInstanceId bigint not null,
startDate timestamp,
status varchar(255),
taskId bigint not null,
taskName varchar(255),
userId varchar(255),
OPTLOCK integer,
primary key (pk)
);
create table BooleanExpression (
id bigint generated by default as identity (start with 1),
expression longvarchar,
type varchar(255),
Escalation_Constraints_Id bigint,
primary key (id)
);
create table CaseIdInfo (
id bigint generated by default as identity (start with 1),
caseIdPrefix varchar(255),
currentValue bigint,
primary key (id)
);
create table CaseFileDataLog (
id bigint generated by default as identity (start with 1),
caseDefId varchar(255),
caseId varchar(255),
itemName varchar(255),
itemType varchar(255),
itemValue varchar(255),
lastModified timestamp,
lastModifiedBy varchar(255),
primary key (id)
);
create table CaseRoleAssignmentLog (
id bigint generated by default as identity (start with 1),
caseId varchar(255),
entityId varchar(255),
processInstanceId bigint not null,
roleName varchar(255),
type integer not null,
primary key (id)
);
create table Content (
id bigint generated by default as identity (start with 1),
content longvarbinary,
primary key (id)
);
create table ContextMappingInfo (
mappingId bigint generated by default as identity (start with 1),
CONTEXT_ID varchar(255) not null,
KSESSION_ID bigint not null,
OWNER_ID varchar(255),
OPTLOCK integer,
primary key (mappingId)
);
create table CorrelationKeyInfo (
keyId bigint generated by default as identity (start with 1),
name varchar(255),
processInstanceId bigint not null,
OPTLOCK integer,
primary key (keyId)
);
create table CorrelationPropertyInfo (
propertyId bigint generated by default as identity (start with 1),
name varchar(255),
value varchar(255),
OPTLOCK integer,
correlationKey_keyId bigint,
primary key (propertyId)
);
create table Deadline (
id bigint generated by default as identity (start with 1),
deadline_date timestamp,
escalated smallint,
Deadlines_StartDeadLine_Id bigint,
Deadlines_EndDeadLine_Id bigint,
primary key (id)
);
create table Delegation_delegates (
task_id bigint not null,
entity_id varchar(255) not null
);
create table DeploymentStore (
id bigint generated by default as identity (start with 1),
attributes varchar(255),
DEPLOYMENT_ID varchar(255),
deploymentUnit longvarchar,
state integer,
updateDate timestamp,
primary key (id)
);
create table ErrorInfo (
id bigint generated by default as identity (start with 1),
message varchar(255),
stacktrace varchar(5000),
timestamp timestamp,
REQUEST_ID bigint not null,
primary key (id)
);
create table Escalation (
id bigint generated by default as identity (start with 1),
name varchar(255),
Deadline_Escalation_Id bigint,
primary key (id)
);
create table EventTypes (
InstanceId bigint not null,
element varchar(255)
);
create table ExecutionErrorInfo (
id bigint generated by default as identity (start with 1),
ERROR_ACK smallint,
ERROR_ACK_AT timestamp,
ERROR_ACK_BY varchar(255),
ACTIVITY_ID bigint,
ACTIVITY_NAME varchar(255),
DEPLOYMENT_ID varchar(255),
ERROR_INFO longvarchar,
ERROR_DATE timestamp,
ERROR_ID varchar(255),
ERROR_MSG varchar(255),
INIT_ACTIVITY_ID bigint,
JOB_ID bigint,
PROCESS_ID varchar(255),
PROCESS_INST_ID bigint,
ERROR_TYPE varchar(255),
primary key (id)
);
create table I18NText (
id bigint generated by default as identity (start with 1),
language varchar(255),
shortText varchar(255),
text longvarchar,
Task_Subjects_Id bigint,
Task_Names_Id bigint,
Task_Descriptions_Id bigint,
Reassignment_Documentation_Id bigint,
Notification_Subjects_Id bigint,
Notification_Names_Id bigint,
Notification_Documentation_Id bigint,
Notification_Descriptions_Id bigint,
Deadline_Documentation_Id bigint,
primary key (id)
);
create table NodeInstanceLog (
id bigint generated by default as identity (start with 1),
connection varchar(255),
log_date timestamp,
externalId varchar(255),
nodeId varchar(255),
nodeInstanceId varchar(255),
nodeName varchar(255),
nodeType varchar(255),
processId varchar(255),
processInstanceId bigint not null,
type integer not null,
workItemId bigint,
nodeContainerId varchar(255),
referenceId bigint,
primary key (id)
);
create table Notification (
DTYPE varchar(31) not null,
id bigint generated by default as identity (start with 1),
priority integer not null,
Escalation_Notifications_Id bigint,
primary key (id)
);
create table Notification_BAs (
task_id bigint not null,
entity_id varchar(255) not null
);
create table Notification_Recipients (
task_id bigint not null,
entity_id varchar(255) not null
);
create table Notification_email_header (
Notification_id bigint not null,
emailHeaders_id bigint not null,
mapkey varchar(255) not null,
primary key (Notification_id, mapkey)
);
create table OrganizationalEntity (
DTYPE varchar(31) not null,
id varchar(255) not null,
primary key (id)
);
create table PeopleAssignments_BAs (
task_id bigint not null,
entity_id varchar(255) not null
);
create table PeopleAssignments_ExclOwners (
task_id bigint not null,
entity_id varchar(255) not null
);
create table PeopleAssignments_PotOwners (
task_id bigint not null,
entity_id varchar(255) not null
);
create table PeopleAssignments_Recipients (
task_id bigint not null,
entity_id varchar(255) not null
);
create table PeopleAssignments_Stakeholders (
task_id bigint not null,
entity_id varchar(255) not null
);
create table ProcessInstanceInfo (
InstanceId bigint generated by default as identity (start with 1),
lastModificationDate timestamp,
lastReadDate timestamp,
processId varchar(255),
processInstanceByteArray longvarbinary,
startDate timestamp,
state integer not null,
OPTLOCK integer,
primary key (InstanceId)
);
create table ProcessInstanceLog (
id bigint generated by default as identity (start with 1),
correlationKey varchar(255),
duration bigint,
end_date timestamp,
externalId varchar(255),
user_identity varchar(255),
outcome varchar(255),
parentProcessInstanceId bigint,
processId varchar(255),
processInstanceDescription varchar(255),
processInstanceId bigint not null,
processName varchar(255),
processType integer,
processVersion varchar(255),
start_date timestamp,
status integer,
primary key (id)
);
create table QueryDefinitionStore (
id bigint generated by default as identity (start with 1),
qExpression longvarchar,
qName varchar(255),
qSource varchar(255),
qTarget varchar(255),
primary key (id)
);
create table Reassignment (
id bigint generated by default as identity (start with 1),
Escalation_Reassignments_Id bigint,
primary key (id)
);
create table Reassignment_potentialOwners (
task_id bigint not null,
entity_id varchar(255) not null
);
create table RequestInfo (
id bigint generated by default as identity (start with 1),
commandName varchar(255),
deploymentId varchar(255),
executions integer not null,
businessKey varchar(255),
message varchar(255),
owner varchar(255),
priority integer not null,
processInstanceId bigint,
requestData longvarbinary,
responseData longvarbinary,
retries integer not null,
status varchar(255),
timestamp timestamp,
primary key (id)
);
create table SessionInfo (
id bigint generated by default as identity (start with 1),
lastModificationDate timestamp,
rulesByteArray longvarbinary,
startDate timestamp,
OPTLOCK integer,
primary key (id)
);
create table Task (
id bigint generated by default as identity (start with 1),
archived smallint,
allowedToDelegate varchar(255),
description varchar(255),
formName varchar(255),
name varchar(255),
priority integer not null,
subTaskStrategy varchar(255),
subject varchar(255),
activationTime timestamp,
createdOn timestamp,
deploymentId varchar(255),
documentAccessType integer,
documentContentId bigint not null,
documentType varchar(255),
expirationTime timestamp,
faultAccessType integer,
faultContentId bigint not null,
faultName varchar(255),
faultType varchar(255),
outputAccessType integer,
outputContentId bigint not null,
outputType varchar(255),
parentId bigint not null,
previousStatus integer,
processId varchar(255),
processInstanceId bigint not null,
processSessionId bigint not null,
skipable boolean not null,
status varchar(255),
workItemId bigint not null,
taskType varchar(255),
OPTLOCK integer,
taskInitiator_id varchar(255),
actualOwner_id varchar(255),
createdBy_id varchar(255),
primary key (id)
);
create table TaskDef (
id bigint generated by default as identity (start with 1),
name varchar(255),
priority integer not null,
primary key (id)
);
create table TaskEvent (
id bigint generated by default as identity (start with 1),
logTime timestamp,
message varchar(255),
processInstanceId bigint,
taskId bigint,
type varchar(255),
userId varchar(255),
OPTLOCK integer,
workItemId bigint,
primary key (id)
);
create table TaskVariableImpl (
id bigint generated by default as identity (start with 1),
modificationDate timestamp,
name varchar(255),
processId varchar(255),
processInstanceId bigint,
taskId bigint,
type integer,
value varchar(4000),
primary key (id)
);
create table VariableInstanceLog (
id bigint generated by default as identity (start with 1),
log_date timestamp,
externalId varchar(255),
oldValue varchar(255),
processId varchar(255),
processInstanceId bigint not null,
value varchar(255),
variableId varchar(255),
variableInstanceId varchar(255),
primary key (id)
);
create table WorkItemInfo (
workItemId bigint generated by default as identity (start with 1),
creationDate timestamp,
name varchar(255),
processInstanceId bigint not null,
state bigint not null,
OPTLOCK integer,
workItemByteArray longvarbinary,
primary key (workItemId)
);
create table email_header (
id bigint generated by default as identity (start with 1),
body longvarchar,
fromAddress varchar(255),
language varchar(255),
replyToAddress varchar(255),
subject varchar(255),
primary key (id)
);
create table task_comment (
id bigint generated by default as identity (start with 1),
addedAt timestamp,
text longvarchar,
addedBy_id varchar(255),
TaskData_Comments_Id bigint,
primary key (id)
);
alter table DeploymentStore
add constraint UK_85rgskt09thd8mkkfl3tb0y81 unique (DEPLOYMENT_ID);
alter table Notification_email_header
add constraint UK_ptaka5kost68h7l3wflv7w6y8 unique (emailHeaders_id);
alter table QueryDefinitionStore
add constraint UK_4ry5gt77jvq0orfttsoghta2j unique (qName);
alter table Attachment
add constraint FK_7ndpfa311i50bq7hy18q05va3
foreign key (attachedBy_id)
references OrganizationalEntity;
alter table Attachment
add constraint FK_hqupx569krp0f0sgu9kh87513
foreign key (TaskData_Attachments_Id)
references Task;
alter table BooleanExpression
add constraint FK_394nf2qoc0k9ok6omgd6jtpso
foreign key (Escalation_Constraints_Id)
references Escalation;
alter table CaseIdInfo
add constraint UK_CaseIdInfo_1 unique (caseIdPrefix);
alter table CorrelationPropertyInfo
add constraint FK_hrmx1m882cejwj9c04ixh50i4
foreign key (correlationKey_keyId)
references CorrelationKeyInfo;
alter table Deadline
add constraint FK_68w742sge00vco2cq3jhbvmgx
foreign key (Deadlines_StartDeadLine_Id)
references Task;
alter table Deadline
add constraint FK_euoohoelbqvv94d8a8rcg8s5n
foreign key (Deadlines_EndDeadLine_Id)
references Task;
alter table Delegation_delegates
add constraint FK_gn7ula51sk55wj1o1m57guqxb
foreign key (entity_id)
references OrganizationalEntity;
alter table Delegation_delegates
add constraint FK_fajq6kossbsqwr3opkrctxei3
foreign key (task_id)
references Task;
alter table ErrorInfo
add constraint FK_cms0met37ggfw5p5gci3otaq0
foreign key (REQUEST_ID)
references RequestInfo;
alter table Escalation
add constraint FK_ay2gd4fvl9yaapviyxudwuvfg
foreign key (Deadline_Escalation_Id)
references Deadline;
alter table EventTypes
add constraint FK_nrecj4617iwxlc65ij6m7lsl1
foreign key (InstanceId)
references ProcessInstanceInfo;
alter table I18NText
add constraint FK_k16jpgrh67ti9uedf6konsu1p
foreign key (Task_Subjects_Id)
references Task;
alter table I18NText
add constraint FK_fd9uk6hemv2dx1ojovo7ms3vp
foreign key (Task_Names_Id)
references Task;
alter table I18NText
add constraint FK_4eyfp69ucrron2hr7qx4np2fp
foreign key (Task_Descriptions_Id)
references Task;
alter table I18NText
add constraint FK_pqarjvvnwfjpeyb87yd7m0bfi
foreign key (Reassignment_Documentation_Id)
references Reassignment;
alter table I18NText
add constraint FK_o84rkh69r47ti8uv4eyj7bmo2
foreign key (Notification_Subjects_Id)
references Notification;
alter table I18NText
add constraint FK_g1trxri8w64enudw2t1qahhk5
foreign key (Notification_Names_Id)
references Notification;
alter table I18NText
add constraint FK_qoce92c70adem3ccb3i7lec8x
foreign key (Notification_Documentation_Id)
references Notification;
alter table I18NText
add constraint FK_bw8vmpekejxt1ei2ge26gdsry
foreign key (Notification_Descriptions_Id)
references Notification;
alter table I18NText
add constraint FK_21qvifarxsvuxeaw5sxwh473w
foreign key (Deadline_Documentation_Id)
references Deadline;
alter table Notification
add constraint FK_bdbeml3768go5im41cgfpyso9
foreign key (Escalation_Notifications_Id)
references Escalation;
alter table Notification_BAs
add constraint FK_mfbsnbrhth4rjhqc2ud338s4i
foreign key (entity_id)
references OrganizationalEntity;
alter table Notification_BAs
add constraint FK_fc0uuy76t2bvxaxqysoo8xts7
foreign key (task_id)
references Notification;
alter table Notification_Recipients
add constraint FK_blf9jsrumtrthdaqnpwxt25eu
foreign key (entity_id)
references OrganizationalEntity;
alter table Notification_Recipients
add constraint FK_3l244pj8sh78vtn9imaymrg47
foreign key (task_id)
references Notification;
alter table Notification_email_header
add constraint FK_ptaka5kost68h7l3wflv7w6y8
foreign key (emailHeaders_id)
references email_header;
alter table Notification_email_header
add constraint FK_eth4nvxn21fk1vnju85vkjrai
foreign key (Notification_id)
references Notification;
alter table PeopleAssignments_BAs
add constraint FK_t38xbkrq6cppifnxequhvjsl2
foreign key (entity_id)
references OrganizationalEntity;
alter table PeopleAssignments_BAs
add constraint FK_omjg5qh7uv8e9bolbaq7hv6oh
foreign key (task_id)
references Task;
alter table PeopleAssignments_ExclOwners
add constraint FK_pth28a73rj6bxtlfc69kmqo0a
foreign key (entity_id)
references OrganizationalEntity;
alter table PeopleAssignments_ExclOwners
add constraint FK_b8owuxfrdng050ugpk0pdowa7
foreign key (task_id)
references Task;
alter table PeopleAssignments_PotOwners
add constraint FK_tee3ftir7xs6eo3fdvi3xw026
foreign key (entity_id)
references OrganizationalEntity;
alter table PeopleAssignments_PotOwners
add constraint FK_4dv2oji7pr35ru0w45trix02x
foreign key (task_id)
references Task;
alter table PeopleAssignments_Recipients
add constraint FK_4g7y3wx6gnokf6vycgpxs83d6
foreign key (entity_id)
references OrganizationalEntity;
alter table PeopleAssignments_Recipients
add constraint FK_enhk831fghf6akjilfn58okl4
foreign key (task_id)
references Task;
alter table PeopleAssignments_Stakeholders
add constraint FK_met63inaep6cq4ofb3nnxi4tm
foreign key (entity_id)
references OrganizationalEntity;
alter table PeopleAssignments_Stakeholders
add constraint FK_4bh3ay74x6ql9usunubttfdf1
foreign key (task_id)
references Task;
alter table Reassignment
add constraint FK_pnpeue9hs6kx2ep0sp16b6kfd
foreign key (Escalation_Reassignments_Id)
references Escalation;
alter table Reassignment_potentialOwners
add constraint FK_8frl6la7tgparlnukhp8xmody
foreign key (entity_id)
references OrganizationalEntity;
alter table Reassignment_potentialOwners
add constraint FK_qbega5ncu6b9yigwlw55aeijn
foreign key (task_id)
references Reassignment;
alter table Task
add constraint FK_dpk0f9ucm14c78bsxthh7h8yh
foreign key (taskInitiator_id)
references OrganizationalEntity;
alter table Task
add constraint FK_nh9nnt47f3l61qjlyedqt05rf
foreign key (actualOwner_id)
references OrganizationalEntity;
alter table Task
add constraint FK_k02og0u71obf1uxgcdjx9rcjc
foreign key (createdBy_id)
references OrganizationalEntity;
alter table task_comment
add constraint FK_aax378yjnsmw9kb9vsu994jjv
foreign key (addedBy_id)
references OrganizationalEntity;
alter table task_comment
add constraint FK_1ws9jdmhtey6mxu7jb0r0ufvs
foreign key (TaskData_Comments_Id)
references Task;
create index IDX_Attachment_Id ON Attachment(attachedBy_id);
create index IDX_Attachment_DataId ON Attachment(TaskData_Attachments_Id);
create index IDX_BoolExpr_Id ON BooleanExpression(Escalation_Constraints_Id);
create index IDX_CorrPropInfo_Id ON CorrelationPropertyInfo(correlationKey_keyId);
create index IDX_Deadline_StartId ON Deadline(Deadlines_StartDeadLine_Id);
create index IDX_Deadline_EndId ON Deadline(Deadlines_EndDeadLine_Id);
create index IDX_Delegation_EntityId ON Delegation_delegates(entity_id);
create index IDX_Delegation_TaskId ON Delegation_delegates(task_id);
create index IDX_ErrorInfo_Id ON ErrorInfo(REQUEST_ID);
create index IDX_Escalation_Id ON Escalation(Deadline_Escalation_Id);
create index IDX_EventTypes_Id ON EventTypes(InstanceId);
create index IDX_I18NText_SubjId ON I18NText(Task_Subjects_Id);
create index IDX_I18NText_NameId ON I18NText(Task_Names_Id);
create index IDX_I18NText_DescrId ON I18NText(Task_Descriptions_Id);
create index IDX_I18NText_ReassignId ON I18NText(Reassignment_Documentation_Id);
create index IDX_I18NText_NotSubjId ON I18NText(Notification_Subjects_Id);
create index IDX_I18NText_NotNamId ON I18NText(Notification_Names_Id);
create index IDX_I18NText_NotDocId ON I18NText(Notification_Documentation_Id);
create index IDX_I18NText_NotDescrId ON I18NText(Notification_Descriptions_Id);
create index IDX_I18NText_DeadDocId ON I18NText(Deadline_Documentation_Id);
create index IDX_Not_EscId ON Notification(Escalation_Notifications_Id);
create index IDX_NotBAs_Entity ON Notification_BAs(entity_id);
create index IDX_NotBAs_Task ON Notification_BAs(task_id);
create index IDX_NotRec_Entity ON Notification_Recipients(entity_id);
create index IDX_NotRec_Task ON Notification_Recipients(task_id);
create index IDX_NotEmail_Header ON Notification_email_header(emailHeaders_id);
create index IDX_NotEmail_Not ON Notification_email_header(Notification_id);
create index IDX_PAsBAs_Entity ON PeopleAssignments_BAs(entity_id);
create index IDX_PAsBAs_Task ON PeopleAssignments_BAs(task_id);
create index IDX_PAsExcl_Entity ON PeopleAssignments_ExclOwners(entity_id);
create index IDX_PAsExcl_Task ON PeopleAssignments_ExclOwners(task_id);
create index IDX_PAsPot_Entity ON PeopleAssignments_PotOwners(entity_id);
create index IDX_PAsPot_Task ON PeopleAssignments_PotOwners(task_id);
create index IDX_PAsRecip_Entity ON PeopleAssignments_Recipients(entity_id);
create index IDX_PAsRecip_Task ON PeopleAssignments_Recipients(task_id);
create index IDX_PAsStake_Entity ON PeopleAssignments_Stakeholders(entity_id);
create index IDX_PAsStake_Task ON PeopleAssignments_Stakeholders(task_id);
create index IDX_Reassign_Esc ON Reassignment(Escalation_Reassignments_Id);
create index IDX_ReassignPO_Entity ON Reassignment_potentialOwners(entity_id);
create index IDX_ReassignPO_Task ON Reassignment_potentialOwners(task_id);
create index IDX_Task_Initiator ON Task(taskInitiator_id);
create index IDX_Task_ActualOwner ON Task(actualOwner_id);
create index IDX_Task_CreatedBy ON Task(createdBy_id);
create index IDX_TaskComments_CreatedBy ON task_comment(addedBy_id);
create index IDX_TaskComments_Id ON task_comment(TaskData_Comments_Id);
create index IDX_Task_processInstanceId on Task(processInstanceId);
create index IDX_Task_processId on Task(processId);
create index IDX_Task_status on Task(status);
create index IDX_Task_archived on Task(archived);
create index IDX_Task_workItemId on Task(workItemId);
create index IDX_EventTypes_element ON EventTypes(element);
create index IDX_CMI_Context ON ContextMappingInfo(CONTEXT_ID);
create index IDX_CMI_KSession ON ContextMappingInfo(KSESSION_ID);
create index IDX_CMI_Owner ON ContextMappingInfo(OWNER_ID);
create index IDX_RequestInfo_status ON RequestInfo(status);
create index IDX_RequestInfo_timestamp ON RequestInfo(timestamp);
create index IDX_RequestInfo_owner ON RequestInfo(owner);
create index IDX_BAMTaskSumm_createdDate on BAMTaskSummary(createdDate);
create index IDX_BAMTaskSumm_duration on BAMTaskSummary(duration);
create index IDX_BAMTaskSumm_endDate on BAMTaskSummary(endDate);
create index IDX_BAMTaskSumm_pInstId on BAMTaskSummary(processInstanceId);
create index IDX_BAMTaskSumm_startDate on BAMTaskSummary(startDate);
create index IDX_BAMTaskSumm_status on BAMTaskSummary(status);
create index IDX_BAMTaskSumm_taskId on BAMTaskSummary(taskId);
create index IDX_BAMTaskSumm_taskName on BAMTaskSummary(taskName);
create index IDX_BAMTaskSumm_userId on BAMTaskSummary(userId);
create index IDX_PInstLog_duration on ProcessInstanceLog(duration);
create index IDX_PInstLog_end_date on ProcessInstanceLog(end_date);
create index IDX_PInstLog_extId on ProcessInstanceLog(externalId);
create index IDX_PInstLog_user_identity on ProcessInstanceLog(user_identity);
create index IDX_PInstLog_outcome on ProcessInstanceLog(outcome);
create index IDX_PInstLog_parentPInstId on ProcessInstanceLog(parentProcessInstanceId);
create index IDX_PInstLog_pId on ProcessInstanceLog(processId);
create index IDX_PInstLog_pInsteDescr on ProcessInstanceLog(processInstanceDescription);
create index IDX_PInstLog_pInstId on ProcessInstanceLog(processInstanceId);
create index IDX_PInstLog_pName on ProcessInstanceLog(processName);
create index IDX_PInstLog_pVersion on ProcessInstanceLog(processVersion);
create index IDX_PInstLog_start_date on ProcessInstanceLog(start_date);
create index IDX_PInstLog_status on ProcessInstanceLog(status);
create index IDX_PInstLog_correlation on ProcessInstanceLog(correlationKey);
create index IDX_VInstLog_pInstId on VariableInstanceLog(processInstanceId);
create index IDX_VInstLog_varId on VariableInstanceLog(variableId);
create index IDX_VInstLog_pId on VariableInstanceLog(processId);
create index IDX_NInstLog_pInstId on NodeInstanceLog(processInstanceId);
create index IDX_NInstLog_nodeType on NodeInstanceLog(nodeType);
create index IDX_NInstLog_pId on NodeInstanceLog(processId);
create index IDX_ErrorInfo_pInstId on ExecutionErrorInfo(PROCESS_INST_ID);
create index IDX_ErrorInfo_errorAck on ExecutionErrorInfo(ERROR_ACK); | {
"content_hash": "08147bdc3e682f072ef68a99a7c38ee3",
"timestamp": "",
"source": "github",
"line_count": 804,
"max_line_length": 92,
"avg_line_length": 34.993781094527364,
"alnum_prop": 0.6799715656655412,
"repo_name": "domhanak/jbpm",
"id": "98b813980f154610c9fce66a2baf432e4215baca",
"size": "28135",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "jbpm-installer/src/main/resources/db/ddl-scripts/hsqldb/hsqldb-jbpm-schema.sql",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "FreeMarker",
"bytes": "24447"
},
{
"name": "HTML",
"bytes": "271"
},
{
"name": "Java",
"bytes": "14344879"
},
{
"name": "PLSQL",
"bytes": "34719"
},
{
"name": "PLpgSQL",
"bytes": "11997"
},
{
"name": "Protocol Buffer",
"bytes": "6518"
},
{
"name": "Shell",
"bytes": "98"
},
{
"name": "Visual Basic",
"bytes": "2545"
}
],
"symlink_target": ""
} |
namespace IRunesWebApp.Controllers
{
using IRunesWebApp.Models;
using IRunesWebApp.Services;
using IRunesWebApp.Services.Contracts;
using SIS.HTTP.Requests.Contracts;
using SIS.HTTP.Response.Contracts;
using SIS.WebServer.Results;
using System;
using System.Linq;
public class UserController : BaseController
{
private IHashService hashService;
public UserController()
{
hashService = new HashService();
}
public IHttpResponse Register()
{
return GetView();
}
public IHttpResponse Register(IHttpRequest request)
{
var username = this.GetFormData(request, "username").Trim();
var password = this.GetFormData(request, "password");
var confirmPassword = this.GetFormData(request, "confirm-password");
var email = this.GetFormData(request, "email").Trim();
var httpResponse = ValdiateUserDetails(username, password, confirmPassword, email);
if (httpResponse != null)
{
return httpResponse;
}
SaveUser(username, password, email);
IHttpResponse response = new RedirectResult(HomeRoot);
response = this.SignInUser(request, response, username);
return response;
}
public IHttpResponse Login()
{
return GetView();
}
public IHttpResponse Login(IHttpRequest request)
{
if (!this.IsAuthenticated(request))
{
var usernameOrEmail = this.GetFormData(request, "usernameOrEmail").Trim();
var password = this.GetFormData(request, "password");
var hashedPassword = this.hashService.Hash(password);
var user = this.db.Users.FirstOrDefault(u => u.Username == usernameOrEmail && hashedPassword == u.Password ||
u.Email == usernameOrEmail && hashedPassword == u.Password);
if (user == null)
{
return new RedirectResult(LoginRoot);
}
IHttpResponse response = new RedirectResult(HomeRoot);
response = this.SignInUser(request, response, user.Username);
return response;
}
return new RedirectResult(LoginRoot);
}
private void SaveUser(string username, string password, string email)
{
string hashedPassword = this.hashService.Hash(password);
var user = new User
{
Id = Guid.NewGuid().ToString(),
Username = username,
Password = hashedPassword,
Email = email
};
db.Users.Add(user);
db.SaveChanges();
}
private IHttpResponse ValdiateUserDetails(string username, string password, string confirmPassword, string email)
{
IHttpResponse httpResponse = null;
if (string.IsNullOrWhiteSpace(username) ||
string.IsNullOrWhiteSpace(password) ||
string.IsNullOrWhiteSpace(confirmPassword) ||
string.IsNullOrWhiteSpace(email) ||
db.Users.Any(u => u.Username == username) ||
password != confirmPassword)
{
return new RedirectResult(RegisterRoot);
}
return httpResponse;
}
public IHttpResponse Logout(IHttpRequest request)
{
if (!request.Session.ContainsParameter(Username))
{
return null;
}
request.Session.ClearParameters();
var cookie = request.CookieCollection.GetCookie(AuthCookie);
if (cookie != null)
{
cookie.Delete();
}
this.Authenticated = false;
var response = new RedirectResult(HomeRoot);
return response;
}
}
}
| {
"content_hash": "b39ce8bc13bce08d2171b771ed2f010b",
"timestamp": "",
"source": "github",
"line_count": 135,
"max_line_length": 125,
"avg_line_length": 30.31111111111111,
"alnum_prop": 0.5505865102639296,
"repo_name": "MihailDobrev/SoftUni",
"id": "d288fffdfdaaf73cb8163e00a592f72f089782cf",
"size": "4094",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "C# Web/C# Web Development Basics/09. Introduction To MVC - Lab/IRunesWebApp/Controllers/UserController.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "921"
},
{
"name": "Batchfile",
"bytes": "1673"
},
{
"name": "C#",
"bytes": "3102431"
},
{
"name": "CSS",
"bytes": "1301866"
},
{
"name": "HTML",
"bytes": "449336"
},
{
"name": "Java",
"bytes": "43616"
},
{
"name": "JavaScript",
"bytes": "739855"
},
{
"name": "PHP",
"bytes": "244170"
},
{
"name": "PLpgSQL",
"bytes": "17609"
}
],
"symlink_target": ""
} |
from ansible import errors
try:
import netaddr
except Exception, e:
raise errors.AnsibleFilterError('python-netaddr package is not installed')
# ---- IP address and network filters ----
def ipaddr(value, query = '', version = False, alias = 'ipaddr'):
''' Check if string is an IP address or network and filter it '''
query_types = [ 'type', 'bool', 'int', 'version', 'size', 'address', 'ip', 'host', \
'network', 'subnet', 'prefix', 'broadcast', 'netmask', 'hostmask', \
'unicast', 'multicast', 'private', 'public', 'loopback', 'lo', \
'revdns', 'wrap', 'ipv6', 'v6', 'ipv4', 'v4', 'cidr', 'net', \
'hostnet', 'router', 'gateway', 'gw', 'host/prefix', 'address/prefix' ]
if not value:
return False
elif value == True:
return False
# Check if value is a list and parse each element
elif isinstance(value, (list, tuple)):
_ret = []
for element in value:
if ipaddr(element, str(query), version):
_ret.append(ipaddr(element, str(query), version))
if _ret:
return _ret
else:
return list()
# Check if value is a number and convert it to an IP address
elif str(value).isdigit():
# We don't know what IP version to assume, so let's check IPv4 first,
# then IPv6
try:
if ((not version) or (version and version == 4)):
v = netaddr.IPNetwork('0.0.0.0/0')
v.value = int(value)
v.prefixlen = 32
elif version and version == 6:
v = netaddr.IPNetwork('::/0')
v.value = int(value)
v.prefixlen = 128
# IPv4 didn't work the first time, so it definitely has to be IPv6
except:
try:
v = netaddr.IPNetwork('::/0')
v.value = int(value)
v.prefixlen = 128
# The value is too big for IPv6. Are you a nanobot?
except:
return False
# We got an IP address, let's mark it as such
value = str(v)
vtype = 'address'
# value has not been recognized, check if it's a valid IP string
else:
try:
v = netaddr.IPNetwork(value)
# value is a valid IP string, check if user specified
# CIDR prefix or just an IP address, this will indicate default
# output format
try:
address, prefix = value.split('/')
vtype = 'network'
except:
vtype = 'address'
# value hasn't been recognized, maybe it's a numerical CIDR?
except:
try:
address, prefix = value.split('/')
address.isdigit()
address = int(address)
prefix.isdigit()
prefix = int(prefix)
# It's not numerical CIDR, give up
except:
return False
# It is something, so let's try and build a CIDR from the parts
try:
v = netaddr.IPNetwork('0.0.0.0/0')
v.value = address
v.prefixlen = prefix
# It's not a valid IPv4 CIDR
except:
try:
v = netaddr.IPNetwork('::/0')
v.value = address
v.prefixlen = prefix
# It's not a valid IPv6 CIDR. Give up.
except:
return False
# We have a valid CIDR, so let's write it in correct format
value = str(v)
vtype = 'network'
v_ip = netaddr.IPAddress(str(v.ip))
# We have a query string but it's not in the known query types. Check if
# that string is a valid subnet, if so, we can check later if given IP
# address/network is inside that specific subnet
try:
if query and query not in query_types and ipaddr(query, 'network'):
iplist = netaddr.IPSet([netaddr.IPNetwork(query)])
query = 'cidr_lookup'
except:
None
# This code checks if value maches the IP version the user wants, ie. if
# it's any version ("ipaddr()"), IPv4 ("ipv4()") or IPv6 ("ipv6()")
# If version does not match, return False
if version and v.version != version:
return False
# We don't have any query to process, so just check what type the user
# expects, and return the IP address in a correct format
if not query:
if v:
if vtype == 'address':
return str(v.ip)
elif vtype == 'network':
return str(v)
elif query == 'type':
if v.size == 1:
return 'address'
if v.size > 1:
if v.ip != v.network:
return 'address'
else:
return 'network'
elif query == 'bool':
if v:
return True
elif query == 'int':
if vtype == 'address':
return int(v.ip)
elif vtype == 'network':
return str(int(v.ip)) + '/' + str(int(v.prefixlen))
elif query == 'version':
return v.version
elif query == 'size':
return v.size
elif query in [ 'address', 'ip' ]:
if v.size == 1:
return str(v.ip)
if v.size > 1:
if v.ip != v.network:
return str(v.ip)
elif query == 'host':
if v.size == 1:
return str(v)
elif v.size > 1:
if v.ip != v.network:
return str(v.ip) + '/' + str(v.prefixlen)
elif query == 'net':
if v.size > 1:
if v.ip == v.network:
return str(v.network) + '/' + str(v.prefixlen)
elif query in [ 'hostnet', 'router', 'gateway', 'gw', 'host/prefix', 'address/prefix' ]:
if v.size > 1:
if v.ip != v.network:
return str(v.ip) + '/' + str(v.prefixlen)
elif query == 'network':
if v.size > 1:
return str(v.network)
elif query == 'subnet':
return str(v.cidr)
elif query == 'cidr':
return str(v)
elif query == 'prefix':
return int(v.prefixlen)
elif query == 'broadcast':
if v.size > 1:
return str(v.broadcast)
elif query == 'netmask':
if v.size > 1:
return str(v.netmask)
elif query == 'hostmask':
return str(v.hostmask)
elif query == 'unicast':
if v.is_unicast():
return value
elif query == 'multicast':
if v.is_multicast():
return value
elif query == 'link-local':
if v.version == 4:
if ipaddr(str(v_ip), '169.254.0.0/24'):
return value
elif v.version == 6:
if ipaddr(str(v_ip), 'fe80::/10'):
return value
elif query == 'private':
if v.is_private():
return value
elif query == 'public':
if v_ip.is_unicast() and not v_ip.is_private() and \
not v_ip.is_loopback() and not v_ip.is_netmask() and \
not v_ip.is_hostmask():
return value
elif query in [ 'loopback', 'lo' ]:
if v_ip.is_loopback():
return value
elif query == 'revdns':
return v_ip.reverse_dns
elif query == 'wrap':
if v.version == 6:
if vtype == 'address':
return '[' + str(v.ip) + ']'
elif vtype == 'network':
return '[' + str(v.ip) + ']/' + str(v.prefixlen)
else:
return value
elif query in [ 'ipv6', 'v6' ]:
if v.version == 4:
return str(v.ipv6())
else:
return value
elif query in [ 'ipv4', 'v4' ]:
if v.version == 6:
try:
return str(v.ipv4())
except:
return False
else:
return value
elif query == '6to4':
if v.version == 4:
if v.size == 1:
ipconv = str(v.ip)
elif v.size > 1:
if v.ip != v.network:
ipconv = str(v.ip)
else:
ipconv = False
if ipaddr(ipconv, 'public'):
numbers = list(map(int, ipconv.split('.')))
try:
return '2002:{:02x}{:02x}:{:02x}{:02x}::1/48'.format(*numbers)
except:
return False
elif v.version == 6:
if vtype == 'address':
if ipaddr(str(v), '2002::/16'):
return value
elif vtype == 'network':
if v.ip != v.network:
if ipaddr(str(v.ip), '2002::/16'):
return value
else:
return False
elif query == 'cidr_lookup':
try:
if v in iplist:
return value
except:
return False
else:
try:
float(query)
if v.size == 1:
if vtype == 'address':
return str(v.ip)
elif vtype == 'network':
return str(v)
elif v.size > 1:
try:
return str(v[query]) + '/' + str(v.prefixlen)
except:
return False
else:
return value
except:
raise errors.AnsibleFilterError(alias + ': unknown filter type: %s' % query)
return False
def ipwrap(value, query = ''):
try:
if isinstance(value, (list, tuple)):
_ret = []
for element in value:
if ipaddr(element, query, version = False, alias = 'ipwrap'):
_ret.append(ipaddr(element, 'wrap'))
else:
_ret.append(element)
return _ret
else:
_ret = ipaddr(value, query, version = False, alias = 'ipwrap')
if _ret:
return ipaddr(_ret, 'wrap')
else:
return value
except:
return value
def ipv4(value, query = ''):
return ipaddr(value, query, version = 4, alias = 'ipv4')
def ipv6(value, query = ''):
return ipaddr(value, query, version = 6, alias = 'ipv6')
# Split given subnet into smaller subnets or find out the biggest subnet of
# a given IP address with given CIDR prefix
# Usage:
#
# - address or address/prefix | ipsubnet
# returns CIDR subnet of a given input
#
# - address/prefix | ipsubnet(cidr)
# returns number of possible subnets for given CIDR prefix
#
# - address/prefix | ipsubnet(cidr, index)
# returns new subnet with given CIDR prefix
#
# - address | ipsubnet(cidr)
# returns biggest subnet with given CIDR prefix that address belongs to
#
# - address | ipsubnet(cidr, index)
# returns next indexed subnet which contains given address
def ipsubnet(value, query = '', index = 'x'):
''' Manipulate IPv4/IPv6 subnets '''
try:
vtype = ipaddr(value, 'type')
if vtype == 'address':
v = ipaddr(value, 'cidr')
elif vtype == 'network':
v = ipaddr(value, 'subnet')
value = netaddr.IPNetwork(v)
except:
return False
if not query:
return str(value)
elif str(query).isdigit():
vsize = ipaddr(v, 'size')
query = int(query)
try:
float(index)
index = int(index)
if vsize > 1:
try:
return str(list(value.subnet(query))[index])
except:
return False
elif vsize == 1:
try:
return str(value.supernet(query)[index])
except:
return False
except:
if vsize > 1:
try:
return str(len(list(value.subnet(query))))
except:
return False
elif vsize == 1:
try:
return str(value.supernet(query)[0])
except:
return False
return False
# ---- HWaddr / MAC address filters ----
def hwaddr(value, query = '', alias = 'hwaddr'):
''' Check if string is a HW/MAC address and filter it '''
try:
v = netaddr.EUI(value)
except:
if query and query not in [ 'bool' ]:
raise errors.AnsibleFilterError(alias + ': not a hardware address: %s' % value)
if not query:
if v:
return value
elif query == 'bool':
if v:
return True
elif query in [ 'win', 'eui48' ]:
v.dialect = netaddr.mac_eui48
return str(v)
elif query == 'unix':
v.dialect = netaddr.mac_unix
return str(v)
elif query in [ 'pgsql', 'postgresql', 'psql' ]:
v.dialect = netaddr.mac_pgsql
return str(v)
elif query == 'cisco':
v.dialect = netaddr.mac_cisco
return str(v)
elif query == 'bare':
v.dialect = netaddr.mac_bare
return str(v)
elif query == 'linux':
v.dialect = mac_linux
return str(v)
else:
raise errors.AnsibleFilterError(alias + ': unknown filter type: %s' % query)
return False
class mac_linux(netaddr.mac_unix): pass
mac_linux.word_fmt = '%.2x'
def macaddr(value, query = ''):
return hwaddr(value, query, alias = 'macaddr')
# ---- Ansible filters ----
class FilterModule(object):
''' IP address and network manipulation filters '''
def filters(self):
return {
# IP addresses and networks
'ipaddr': ipaddr,
'ipwrap': ipwrap,
'ipv4': ipv4,
'ipv6': ipv6,
'ipsubnet': ipsubnet,
# MAC / HW addresses
'hwaddr': hwaddr,
'macaddr': macaddr
}
| {
"content_hash": "d393b135f1a0d8e95f1c09e577de6819",
"timestamp": "",
"source": "github",
"line_count": 514,
"max_line_length": 92,
"avg_line_length": 27.381322957198442,
"alnum_prop": 0.48642887594145234,
"repo_name": "le9i0nx/ansible-home",
"id": "68e2fd778c4ce41d652ae2a9e435a8be455066b5",
"size": "14780",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "filter_plugins/ipaddr.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "68849"
}
],
"symlink_target": ""
} |
Microsoft Office related utilities
## About TimedTask.ps1
### TimedTask.ps1 Installation
You can download the Time Tracking script by downloading the full repository from:
https://github.com/CailleauThierry/PSThUtils > "Download ZIP"
All you need are the following 2 files + WMF 5.0 installed (PowerShell 5, already installed by default in Windows 10 and Server 2016) available from:
- https://www.microsoft.com/en-us/download/details.aspx?id=50395
- TimedTask.bat
- TimedTask.ps1
You can set your execution policies to Unrestricted or Bypass:
1. In a PowerShell prompt launch with "Run As Administrator" priviledges
2. Set-ExecutionPolicy -ExecutionPolicy Bypass # say yes
The auto-generated .csv file will be in the $profile\TimedTask_Logs directory it creates (just type “$profile” in PowerShell to find out where that is)
To launch the script, launch your edited version of "TimedTask.bat".
You can launch the script from anywhere as long as you adjust the path in "TimedTask.bat".
### TimedTask.ps1 User Guide
1. Double-clicking "TimedTask.bat"
2. A PowerShell console will open and then a Windows Form Pop-up will appear > this is what we will use
3. Enter the text in the form and do either:
* OK > this will close the form and add that text to the .csv file (it will also create that file the first time)
* Leave the Form open and only click "OK" when the task is completed. This will update the "Duration" column of the .csv file with that time-span
- Note: Do not have Excel open that .csv if you want the script to be able to add another entry to it. Excel "locks" access to that .csv file...
| {
"content_hash": "18082306adce2fd90c337679c3b19e1c",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 151,
"avg_line_length": 47.705882352941174,
"alnum_prop": 0.7669543773119606,
"repo_name": "CailleauThierry/PSThUtils",
"id": "be83f10bb8c41126bb6987f1237f0fed911ec494",
"size": "1635",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Office/README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "1083"
},
{
"name": "PowerShell",
"bytes": "216187"
}
],
"symlink_target": ""
} |
package org.vash.vate.console.graphical.menu;
import java.awt.MenuItem;
import org.vash.vate.console.graphical.menu.listener.VTGraphicalConsoleMenuItemListener;
public class VTGraphicalConsoleMenuItem extends MenuItem
{
private static final long serialVersionUID = 1L;
public VTGraphicalConsoleMenuItem(String label, String command)
{
this.setLabel(label.trim());
this.setActionCommand(command);
this.addActionListener(new VTGraphicalConsoleMenuItemListener());
}
} | {
"content_hash": "b25aeb2909e1996cee5efe74622e8bfa",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 88,
"avg_line_length": 29.705882352941178,
"alnum_prop": 0.7762376237623763,
"repo_name": "wknishio/variable-terminal",
"id": "4bd991a0392f284e3ae1333af122707acccc6598",
"size": "505",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/vate/org/vash/vate/console/graphical/menu/VTGraphicalConsoleMenuItem.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "13395"
},
{
"name": "HTML",
"bytes": "56394"
},
{
"name": "Java",
"bytes": "15234650"
},
{
"name": "Shell",
"bytes": "16874"
}
],
"symlink_target": ""
} |
namespace chi {
ObjectWrap::~ObjectWrap() {
if (!handle_.IsEmpty()) {
assert(handle_.IsNearDeath());
handle_.ClearWeak();
handle_->SetInternalField(0, v8::Undefined());
handle_.Dispose();
handle_.Clear();
}
}
void ObjectWrap::WeakCallback(v8::Persistent<v8::Value> value, void *data) {
ObjectWrap *obj = static_cast<ObjectWrap*>(data);
assert(value == obj->handle_);
assert(value.IsNearDeath());
delete obj;
}
}
| {
"content_hash": "0974c624e588cb05c8d521cf820db901",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 76,
"avg_line_length": 21.55,
"alnum_prop": 0.6705336426914154,
"repo_name": "cha0s/Worlds-Beyond",
"id": "145eec419dd92d0f9c2a75a69de4aada3adaa436",
"size": "480",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/ObjectWrap.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "660"
},
{
"name": "C++",
"bytes": "144776"
},
{
"name": "Prolog",
"bytes": "3560"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<script src="/w3c/resources/testharness.js"></script>
<script src="/w3c/resources/testharnessreport.js"></script>
<script src="mediasource-util.js"></script>
<link rel='stylesheet' href='/w3c/resources/testharness.css'>
</head>
<body>
<div id="log"></div>
<script>
mediasource_test(function(test, mediaElement, mediaSource)
{
var sourceBuffer = mediaSource.addSourceBuffer(MediaSourceUtil.AUDIO_VIDEO_TYPE);
mediaSource.duration = 10;
assert_throws_js(TypeError, function()
{
sourceBuffer.remove(-1, 2);
}, "remove");
test.done();
}, "Test remove with a negative start.");
mediasource_test(function(test, mediaElement, mediaSource)
{
var sourceBuffer = mediaSource.addSourceBuffer(MediaSourceUtil.AUDIO_VIDEO_TYPE);
mediaSource.duration = 10;
[ undefined, NaN, Infinity, -Infinity ].forEach(function(item)
{
assert_throws_js(TypeError, function()
{
sourceBuffer.remove(item, 2);
}, "remove");
});
test.done();
}, "Test remove with non-finite start.");
mediasource_test(function(test, mediaElement, mediaSource)
{
var sourceBuffer = mediaSource.addSourceBuffer(MediaSourceUtil.AUDIO_VIDEO_TYPE);
mediaSource.duration = 10;
assert_throws_js(TypeError, function()
{
sourceBuffer.remove(11, 12);
}, "remove");
test.done();
}, "Test remove with a start beyond the duration.");
mediasource_test(function(test, mediaElement, mediaSource)
{
var sourceBuffer = mediaSource.addSourceBuffer(MediaSourceUtil.AUDIO_VIDEO_TYPE);
mediaSource.duration = 10;
assert_throws_js(TypeError, function()
{
sourceBuffer.remove(2, 1);
}, "remove");
test.done();
}, "Test remove with a start larger than the end.");
mediasource_test(function(test, mediaElement, mediaSource)
{
var sourceBuffer = mediaSource.addSourceBuffer(MediaSourceUtil.AUDIO_VIDEO_TYPE);
mediaSource.duration = 10;
assert_throws_js(TypeError, function()
{
sourceBuffer.remove(0, Number.NEGATIVE_INFINITY);
}, "remove");
test.done();
}, "Test remove with a NEGATIVE_INFINITY end.");
mediasource_test(function(test, mediaElement, mediaSource)
{
var sourceBuffer = mediaSource.addSourceBuffer(MediaSourceUtil.AUDIO_VIDEO_TYPE);
mediaSource.duration = 10;
assert_throws_js(TypeError, function()
{
sourceBuffer.remove(0, Number.NaN);
}, "remove");
test.done();
}, "Test remove with a NaN end.");
mediasource_test(function(test, mediaElement, mediaSource)
{
var sourceBuffer = mediaSource.addSourceBuffer(MediaSourceUtil.AUDIO_VIDEO_TYPE);
mediaSource.duration = 10;
mediaSource.removeSourceBuffer(sourceBuffer);
assert_throws_dom("InvalidStateError", function()
{
sourceBuffer.remove(1, 2);
}, "remove");
test.done();
}, "Test remove after SourceBuffer removed from mediaSource.");
mediasource_test(function(test, mediaElement, mediaSource)
{
var sourceBuffer = mediaSource.addSourceBuffer(MediaSourceUtil.AUDIO_VIDEO_TYPE);
mediaSource.duration = 10;
test.expectEvent(sourceBuffer, "updatestart");
test.expectEvent(sourceBuffer, "update");
test.expectEvent(sourceBuffer, "updateend");
sourceBuffer.remove(1, 2);
assert_true(sourceBuffer.updating, "updating");
assert_throws_dom("InvalidStateError", function()
{
sourceBuffer.remove(3, 4);
}, "remove");
test.waitForExpectedEvents(function()
{
test.done();
});
}, "Test remove while update pending.");
mediasource_test(function(test, mediaElement, mediaSource)
{
var sourceBuffer = mediaSource.addSourceBuffer(MediaSourceUtil.AUDIO_VIDEO_TYPE);
mediaSource.duration = 10;
test.expectEvent(sourceBuffer, "updatestart");
test.expectEvent(sourceBuffer, "updateend");
sourceBuffer.remove(1, 2);
assert_true(sourceBuffer.updating, "updating");
assert_throws_dom('InvalidStateError',
function() { sourceBuffer.abort(); },
'abort() of remove() throws an exception');
assert_true(sourceBuffer.updating, "updating");
test.waitForExpectedEvents(function()
{
test.done();
});
}, "Test aborting a remove operation throws exception.");
mediasource_testafterdataloaded(function(test, mediaElement, mediaSource, segmentInfo, sourceBuffer, mediaData)
{
sourceBuffer.appendBuffer(mediaData);
test.expectEvent(sourceBuffer, "updatestart");
test.expectEvent(sourceBuffer, "update");
test.expectEvent(sourceBuffer, "updateend");
test.waitForExpectedEvents(function()
{
assert_less_than(mediaSource.duration, 10)
mediaSource.duration = 10;
sourceBuffer.remove(mediaSource.duration, mediaSource.duration + 2);
assert_true(sourceBuffer.updating, "updating");
test.expectEvent(sourceBuffer, "updatestart");
test.expectEvent(sourceBuffer, "update");
test.expectEvent(sourceBuffer, "updateend");
});
test.waitForExpectedEvents(function()
{
test.done();
});
}, "Test remove with a start at the duration.");
mediasource_testafterdataloaded(function(test, mediaElement, mediaSource, segmentInfo, sourceBuffer, mediaData)
{
test.expectEvent(sourceBuffer, "updatestart");
test.expectEvent(sourceBuffer, "update");
test.expectEvent(sourceBuffer, "updateend");
sourceBuffer.appendBuffer(mediaData);
test.waitForExpectedEvents(function()
{
mediaSource.endOfStream();
assert_equals(mediaSource.readyState, "ended");
test.expectEvent(sourceBuffer, "updatestart");
test.expectEvent(sourceBuffer, "update");
test.expectEvent(sourceBuffer, "updateend");
sourceBuffer.remove(1, 2);
assert_true(sourceBuffer.updating, "updating");
assert_equals(mediaSource.readyState, "open");
});
test.waitForExpectedEvents(function()
{
assert_false(sourceBuffer.updating, "updating");
test.done();
});
}, "Test remove transitioning readyState from 'ended' to 'open'.");
function removeAppendedDataTests(callback, description)
{
mediasource_testafterdataloaded(function(test, mediaElement, mediaSource, segmentInfo, sourceBuffer, mediaData)
{
test.expectEvent(sourceBuffer, "updatestart");
test.expectEvent(sourceBuffer, "update");
test.expectEvent(sourceBuffer, "updateend");
sourceBuffer.appendBuffer(mediaData);
test.waitForExpectedEvents(function()
{
var bufferedRangeEnd = segmentInfo.bufferedRangeEndBeforeEndOfStream.toFixed(3);
var subType = MediaSourceUtil.getSubType(segmentInfo.type);
assertBufferedEquals(sourceBuffer, "{ [0.000, " + bufferedRangeEnd + ") }", "Initial buffered range.");
callback(test, sourceBuffer, bufferedRangeEnd, subType);
});
}, description);
};
function removeAndCheckBufferedRanges(test, sourceBuffer, start, end, expected)
{
test.expectEvent(sourceBuffer, "updatestart");
test.expectEvent(sourceBuffer, "update");
test.expectEvent(sourceBuffer, "updateend");
sourceBuffer.remove(start, end);
test.waitForExpectedEvents(function()
{
assertBufferedEquals(sourceBuffer, expected, "Buffered ranges after remove().");
test.done();
});
}
removeAppendedDataTests(function(test, sourceBuffer, bufferedRangeEnd, subType)
{
removeAndCheckBufferedRanges(test, sourceBuffer, 0, Number.POSITIVE_INFINITY, "{ }");
}, "Test removing all appended data.");
removeAppendedDataTests(function(test, sourceBuffer, bufferedRangeEnd, subType)
{
var expectations = {
webm: ("{ [3.187, " + bufferedRangeEnd + ") }"),
mp4: ("{ [3.021, " + bufferedRangeEnd + ") }"),
};
// Note: Range doesn't start exactly at the end of the remove range because there isn't
// a keyframe there. The resulting range starts at the first keyframe >= the end time.
removeAndCheckBufferedRanges(test, sourceBuffer, 0, 3, expectations[subType]);
}, "Test removing beginning of appended data.");
removeAppendedDataTests(function(test, sourceBuffer, bufferedRangeEnd, subType)
{
var expectations = {
webm: ("{ [0.000, 1.012) [3.187, " + bufferedRangeEnd + ") }"),
mp4: ("{ [0.000, 1.022) [3.021, " + bufferedRangeEnd + ") }"),
};
// Note: The first resulting range ends slightly after start because the removal algorithm only removes
// frames with a timestamp >= the start time. If a frame starts before and ends after the remove() start
// timestamp, then it stays in the buffer.
removeAndCheckBufferedRanges(test, sourceBuffer, 1, 3, expectations[subType]);
}, "Test removing the middle of appended data.");
removeAppendedDataTests(function(test, sourceBuffer, bufferedRangeEnd, subType)
{
var expectations = {
webm: "{ [0.000, 1.012) }",
mp4: "{ [0.000, 1.022) }",
};
// Using MAX_VALUE rather than POSITIVE_INFINITY here due to lack
// of 'unrestricted' on end parameter. (See comment in SourceBuffer.idl)
removeAndCheckBufferedRanges(test, sourceBuffer, 1, Number.MAX_VALUE, expectations[subType]);
}, "Test removing the end of appended data.");
</script>
</body>
</html>
| {
"content_hash": "058b7556e09e4ce7e9137a97c7df55cd",
"timestamp": "",
"source": "github",
"line_count": 300,
"max_line_length": 125,
"avg_line_length": 38.4,
"alnum_prop": 0.5544270833333333,
"repo_name": "nwjs/chromium.src",
"id": "a030cf2db1af9e2bb6c69192019c9cc3c52e09e4",
"size": "11520",
"binary": false,
"copies": "9",
"ref": "refs/heads/nw70",
"path": "third_party/blink/web_tests/http/tests/media/media-source/mediasource-remove.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
<?php
/**
* This code was generated by
* \ / _ _ _| _ _
* | (_)\/(_)(_|\/| |(/_ v1.0.0
* / /
*/
namespace Twilio\Rest\Api\V2010\Account\Usage\Record;
use Twilio\ListResource;
use Twilio\Options;
use Twilio\Serialize;
use Twilio\Values;
use Twilio\Version;
class YesterdayList extends ListResource {
/**
* Construct the YesterdayList
*
* @param Version $version Version that contains the resource
* @param string $accountSid A 34 character string that uniquely identifies
* this resource.
* @return \Twilio\Rest\Api\V2010\Account\Usage\Record\YesterdayList
*/
public function __construct(Version $version, $accountSid) {
parent::__construct($version);
// Path Solution
$this->solution = array(
'accountSid' => $accountSid,
);
$this->uri = '/Accounts/' . rawurlencode($accountSid) . '/Usage/Records/Yesterday.json';
}
/**
* Streams YesterdayInstance records from the API as a generator stream.
* This operation lazily loads records as efficiently as possible until the
* limit
* is reached.
* The results are returned as a generator, so this operation is memory
* efficient.
*
* @param array|Options $options Optional Arguments
* @param int $limit Upper limit for the number of records to return. stream()
* guarantees to never return more than limit. Default is no
* limit
* @param mixed $pageSize Number of records to fetch per request, when not set
* will use the default value of 50 records. If no
* page_size is defined but a limit is defined, stream()
* will attempt to read the limit with the most
* efficient page size, i.e. min(limit, 1000)
* @return \Twilio\Stream stream of results
*/
public function stream($options = array(), $limit = null, $pageSize = null) {
$limits = $this->version->readLimits($limit, $pageSize);
$page = $this->page($options, $limits['pageSize']);
return $this->version->stream($page, $limits['limit'], $limits['pageLimit']);
}
/**
* Reads YesterdayInstance records from the API as a list.
* Unlike stream(), this operation is eager and will load `limit` records into
* memory before returning.
*
* @param array|Options $options Optional Arguments
* @param int $limit Upper limit for the number of records to return. read()
* guarantees to never return more than limit. Default is no
* limit
* @param mixed $pageSize Number of records to fetch per request, when not set
* will use the default value of 50 records. If no
* page_size is defined but a limit is defined, read()
* will attempt to read the limit with the most
* efficient page size, i.e. min(limit, 1000)
* @return YesterdayInstance[] Array of results
*/
public function read($options = array(), $limit = null, $pageSize = null) {
return iterator_to_array($this->stream($options, $limit, $pageSize), false);
}
/**
* Retrieve a single page of YesterdayInstance records from the API.
* Request is executed immediately
*
* @param array|Options $options Optional Arguments
* @param mixed $pageSize Number of records to return, defaults to 50
* @param string $pageToken PageToken provided by the API
* @param mixed $pageNumber Page Number, this value is simply for client state
* @return \Twilio\Page Page of YesterdayInstance
*/
public function page($options = array(), $pageSize = Values::NONE, $pageToken = Values::NONE, $pageNumber = Values::NONE) {
$options = new Values($options);
$params = Values::of(array(
'Category' => $options['category'],
'StartDate' => Serialize::iso8601Date($options['startDate']),
'EndDate' => Serialize::iso8601Date($options['endDate']),
'PageToken' => $pageToken,
'Page' => $pageNumber,
'PageSize' => $pageSize,
));
$response = $this->version->page(
'GET',
$this->uri,
$params
);
return new YesterdayPage($this->version, $response, $this->solution);
}
/**
* Retrieve a specific page of YesterdayInstance records from the API.
* Request is executed immediately
*
* @param string $targetUrl API-generated URL for the requested results page
* @return \Twilio\Page Page of YesterdayInstance
*/
public function getPage($targetUrl) {
$response = $this->version->getDomain()->getClient()->request(
'GET',
$targetUrl
);
return new YesterdayPage($this->version, $response, $this->solution);
}
/**
* Provide a friendly representation
*
* @return string Machine friendly representation
*/
public function __toString() {
return '[Twilio.Api.V2010.YesterdayList]';
}
} | {
"content_hash": "8b4c4843c1eab32a01d8d460fd55e90e",
"timestamp": "",
"source": "github",
"line_count": 139,
"max_line_length": 127,
"avg_line_length": 37.906474820143885,
"alnum_prop": 0.5919529322452078,
"repo_name": "talent-webmobiledeveloper/codeigniter3_twiliosms",
"id": "0d2aae68c356cbd162a9513e88179454ca5b33ab",
"size": "5269",
"binary": false,
"copies": "11",
"ref": "refs/heads/master",
"path": "application/libraries/twilio/vendor/twilio/sdk/Twilio/Rest/Api/V2010/Account/Usage/Record/YesterdayList.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "646318"
},
{
"name": "HTML",
"bytes": "219178"
},
{
"name": "Hack",
"bytes": "85484"
},
{
"name": "JavaScript",
"bytes": "1171423"
},
{
"name": "PHP",
"bytes": "2276648"
},
{
"name": "Smarty",
"bytes": "436"
}
],
"symlink_target": ""
} |
// Knockout JavaScript library v2.1.0
// (c) Steven Sanderson - http://knockoutjs.com/
// License: MIT (http://www.opensource.org/licenses/mit-license.php)
(function(window,document,navigator,undefined){
var DEBUG=true;
!function(factory) {
// Support three module loading scenarios
if (typeof require === 'function' && typeof exports === 'object' && typeof module === 'object') {
// [1] CommonJS/Node.js
var target = module['exports'] || exports; // module.exports is for Node.js
factory(target);
} else if (typeof define === 'function' && define['amd']) {
// [2] AMD anonymous module
define(['exports'], factory);
} else {
// [3] No module loader (plain <script> tag) - put directly in global namespace
factory(window['ko'] = {});
}
}(function(koExports){
// Internally, all KO objects are attached to koExports (even the non-exported ones whose names will be minified by the closure compiler).
// In the future, the following "ko" variable may be made distinct from "koExports" so that private objects are not externally reachable.
var ko = typeof koExports !== 'undefined' ? koExports : {};
// Google Closure Compiler helpers (used only to make the minified file smaller)
ko.exportSymbol = function(koPath, object) {
var tokens = koPath.split(".");
// In the future, "ko" may become distinct from "koExports" (so that non-exported objects are not reachable)
// At that point, "target" would be set to: (typeof koExports !== "undefined" ? koExports : ko)
var target = ko;
for (var i = 0; i < tokens.length - 1; i++)
target = target[tokens[i]];
target[tokens[tokens.length - 1]] = object;
};
ko.exportProperty = function(owner, publicName, object) {
owner[publicName] = object;
};
ko.version = "2.1.0";
ko.exportSymbol('version', ko.version);
ko.utils = new (function () {
var stringTrimRegex = /^(\s|\u00A0)+|(\s|\u00A0)+$/g;
// Represent the known event types in a compact way, then at runtime transform it into a hash with event name as key (for fast lookup)
var knownEvents = {}, knownEventTypesByEventName = {};
var keyEventTypeName = /Firefox\/2/i.test(navigator.userAgent) ? 'KeyboardEvent' : 'UIEvents';
knownEvents[keyEventTypeName] = ['keyup', 'keydown', 'keypress'];
knownEvents['MouseEvents'] = ['click', 'dblclick', 'mousedown', 'mouseup', 'mousemove', 'mouseover', 'mouseout', 'mouseenter', 'mouseleave'];
for (var eventType in knownEvents) {
var knownEventsForType = knownEvents[eventType];
if (knownEventsForType.length) {
for (var i = 0, j = knownEventsForType.length; i < j; i++)
knownEventTypesByEventName[knownEventsForType[i]] = eventType;
}
}
var eventsThatMustBeRegisteredUsingAttachEvent = { 'propertychange': true }; // Workaround for an IE9 issue - https://github.com/SteveSanderson/knockout/issues/406
// Detect IE versions for bug workarounds (uses IE conditionals, not UA string, for robustness)
var ieVersion = (function() {
var version = 3, div = document.createElement('div'), iElems = div.getElementsByTagName('i');
// Keep constructing conditional HTML blocks until we hit one that resolves to an empty fragment
while (
div.innerHTML = '<!--[if gt IE ' + (++version) + ']><i></i><![endif]-->',
iElems[0]
);
return version > 4 ? version : undefined;
}());
var isIe6 = ieVersion === 6,
isIe7 = ieVersion === 7;
function isClickOnCheckableElement(element, eventType) {
if ((ko.utils.tagNameLower(element) !== "input") || !element.type) return false;
if (eventType.toLowerCase() != "click") return false;
var inputType = element.type;
return (inputType == "checkbox") || (inputType == "radio");
}
return {
fieldsIncludedWithJsonPost: ['authenticity_token', /^__RequestVerificationToken(_.*)?$/],
arrayForEach: function (array, action) {
for (var i = 0, j = array.length; i < j; i++)
action(array[i]);
},
arrayIndexOf: function (array, item) {
if (typeof Array.prototype.indexOf == "function")
return Array.prototype.indexOf.call(array, item);
for (var i = 0, j = array.length; i < j; i++)
if (array[i] === item)
return i;
return -1;
},
arrayFirst: function (array, predicate, predicateOwner) {
for (var i = 0, j = array.length; i < j; i++)
if (predicate.call(predicateOwner, array[i]))
return array[i];
return null;
},
arrayRemoveItem: function (array, itemToRemove) {
var index = ko.utils.arrayIndexOf(array, itemToRemove);
if (index >= 0)
array.splice(index, 1);
},
arrayGetDistinctValues: function (array) {
array = array || [];
var result = [];
for (var i = 0, j = array.length; i < j; i++) {
if (ko.utils.arrayIndexOf(result, array[i]) < 0)
result.push(array[i]);
}
return result;
},
arrayMap: function (array, mapping) {
array = array || [];
var result = [];
for (var i = 0, j = array.length; i < j; i++)
result.push(mapping(array[i]));
return result;
},
arrayFilter: function (array, predicate) {
array = array || [];
var result = [];
for (var i = 0, j = array.length; i < j; i++)
if (predicate(array[i]))
result.push(array[i]);
return result;
},
arrayPushAll: function (array, valuesToPush) {
if (valuesToPush instanceof Array)
array.push.apply(array, valuesToPush);
else
for (var i = 0, j = valuesToPush.length; i < j; i++)
array.push(valuesToPush[i]);
return array;
},
extend: function (target, source) {
if (source) {
for(var prop in source) {
if(source.hasOwnProperty(prop)) {
target[prop] = source[prop];
}
}
}
return target;
},
emptyDomNode: function (domNode) {
while (domNode.firstChild) {
ko.removeNode(domNode.firstChild);
}
},
moveCleanedNodesToContainerElement: function(nodes) {
// Ensure it's a real array, as we're about to reparent the nodes and
// we don't want the underlying collection to change while we're doing that.
var nodesArray = ko.utils.makeArray(nodes);
var container = document.createElement('div');
for (var i = 0, j = nodesArray.length; i < j; i++) {
ko.cleanNode(nodesArray[i]);
container.appendChild(nodesArray[i]);
}
return container;
},
setDomNodeChildren: function (domNode, childNodes) {
ko.utils.emptyDomNode(domNode);
if (childNodes) {
for (var i = 0, j = childNodes.length; i < j; i++)
domNode.appendChild(childNodes[i]);
}
},
replaceDomNodes: function (nodeToReplaceOrNodeArray, newNodesArray) {
var nodesToReplaceArray = nodeToReplaceOrNodeArray.nodeType ? [nodeToReplaceOrNodeArray] : nodeToReplaceOrNodeArray;
if (nodesToReplaceArray.length > 0) {
var insertionPoint = nodesToReplaceArray[0];
var parent = insertionPoint.parentNode;
for (var i = 0, j = newNodesArray.length; i < j; i++)
parent.insertBefore(newNodesArray[i], insertionPoint);
for (var i = 0, j = nodesToReplaceArray.length; i < j; i++) {
ko.removeNode(nodesToReplaceArray[i]);
}
}
},
setOptionNodeSelectionState: function (optionNode, isSelected) {
// IE6 sometimes throws "unknown error" if you try to write to .selected directly, whereas Firefox struggles with setAttribute. Pick one based on browser.
if (navigator.userAgent.indexOf("MSIE 6") >= 0)
optionNode.setAttribute("selected", isSelected);
else
optionNode.selected = isSelected;
},
stringTrim: function (string) {
return (string || "").replace(stringTrimRegex, "");
},
stringTokenize: function (string, delimiter) {
var result = [];
var tokens = (string || "").split(delimiter);
for (var i = 0, j = tokens.length; i < j; i++) {
var trimmed = ko.utils.stringTrim(tokens[i]);
if (trimmed !== "")
result.push(trimmed);
}
return result;
},
stringStartsWith: function (string, startsWith) {
string = string || "";
if (startsWith.length > string.length)
return false;
return string.substring(0, startsWith.length) === startsWith;
},
buildEvalWithinScopeFunction: function (expression, scopeLevels) {
// Build the source for a function that evaluates "expression"
// For each scope variable, add an extra level of "with" nesting
// Example result: with(sc[1]) { with(sc[0]) { return (expression) } }
var functionBody = "return (" + expression + ")";
for (var i = 0; i < scopeLevels; i++) {
functionBody = "with(sc[" + i + "]) { " + functionBody + " } ";
}
return new Function("sc", functionBody);
},
domNodeIsContainedBy: function (node, containedByNode) {
if (containedByNode.compareDocumentPosition)
return (containedByNode.compareDocumentPosition(node) & 16) == 16;
while (node != null) {
if (node == containedByNode)
return true;
node = node.parentNode;
}
return false;
},
domNodeIsAttachedToDocument: function (node) {
return ko.utils.domNodeIsContainedBy(node, node.ownerDocument);
},
tagNameLower: function(element) {
// For HTML elements, tagName will always be upper case; for XHTML elements, it'll be lower case.
// Possible future optimization: If we know it's an element from an XHTML document (not HTML),
// we don't need to do the .toLowerCase() as it will always be lower case anyway.
return element && element.tagName && element.tagName.toLowerCase();
},
registerEventHandler: function (element, eventType, handler) {
var mustUseAttachEvent = ieVersion && eventsThatMustBeRegisteredUsingAttachEvent[eventType];
if (!mustUseAttachEvent && typeof jQuery != "undefined") {
if (isClickOnCheckableElement(element, eventType)) {
// For click events on checkboxes, jQuery interferes with the event handling in an awkward way:
// it toggles the element checked state *after* the click event handlers run, whereas native
// click events toggle the checked state *before* the event handler.
// Fix this by intecepting the handler and applying the correct checkedness before it runs.
var originalHandler = handler;
handler = function(event, eventData) {
var jQuerySuppliedCheckedState = this.checked;
if (eventData)
this.checked = eventData.checkedStateBeforeEvent !== true;
originalHandler.call(this, event);
this.checked = jQuerySuppliedCheckedState; // Restore the state jQuery applied
};
}
jQuery(element)['bind'](eventType, handler);
} else if (!mustUseAttachEvent && typeof element.addEventListener == "function")
element.addEventListener(eventType, handler, false);
else if (typeof element.attachEvent != "undefined")
element.attachEvent("on" + eventType, function (event) {
handler.call(element, event);
});
else
throw new Error("Browser doesn't support addEventListener or attachEvent");
},
triggerEvent: function (element, eventType) {
if (!(element && element.nodeType))
throw new Error("element must be a DOM node when calling triggerEvent");
if (typeof jQuery != "undefined") {
var eventData = [];
if (isClickOnCheckableElement(element, eventType)) {
// Work around the jQuery "click events on checkboxes" issue described above by storing the original checked state before triggering the handler
eventData.push({ checkedStateBeforeEvent: element.checked });
}
jQuery(element)['trigger'](eventType, eventData);
} else if (typeof document.createEvent == "function") {
if (typeof element.dispatchEvent == "function") {
var eventCategory = knownEventTypesByEventName[eventType] || "HTMLEvents";
var event = document.createEvent(eventCategory);
event.initEvent(eventType, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, element);
element.dispatchEvent(event);
}
else
throw new Error("The supplied element doesn't support dispatchEvent");
} else if (typeof element.fireEvent != "undefined") {
// Unlike other browsers, IE doesn't change the checked state of checkboxes/radiobuttons when you trigger their "click" event
// so to make it consistent, we'll do it manually here
if (isClickOnCheckableElement(element, eventType))
element.checked = element.checked !== true;
element.fireEvent("on" + eventType);
}
else
throw new Error("Browser doesn't support triggering events");
},
unwrapObservable: function (value) {
return ko.isObservable(value) ? value() : value;
},
toggleDomNodeCssClass: function (node, className, shouldHaveClass) {
var currentClassNames = (node.className || "").split(/\s+/);
var hasClass = ko.utils.arrayIndexOf(currentClassNames, className) >= 0;
if (shouldHaveClass && !hasClass) {
node.className += (currentClassNames[0] ? " " : "") + className;
} else if (hasClass && !shouldHaveClass) {
var newClassName = "";
for (var i = 0; i < currentClassNames.length; i++)
if (currentClassNames[i] != className)
newClassName += currentClassNames[i] + " ";
node.className = ko.utils.stringTrim(newClassName);
}
},
setTextContent: function(element, textContent) {
var value = ko.utils.unwrapObservable(textContent);
if ((value === null) || (value === undefined))
value = "";
'innerText' in element ? element.innerText = value
: element.textContent = value;
if (ieVersion >= 9) {
// Believe it or not, this actually fixes an IE9 rendering bug
// (See https://github.com/SteveSanderson/knockout/issues/209)
element.style.display = element.style.display;
}
},
ensureSelectElementIsRenderedCorrectly: function(selectElement) {
// Workaround for IE9 rendering bug - it doesn't reliably display all the text in dynamically-added select boxes unless you force it to re-render by updating the width.
// (See https://github.com/SteveSanderson/knockout/issues/312, http://stackoverflow.com/questions/5908494/select-only-shows-first-char-of-selected-option)
if (ieVersion >= 9) {
var originalWidth = selectElement.style.width;
selectElement.style.width = 0;
selectElement.style.width = originalWidth;
}
},
range: function (min, max) {
min = ko.utils.unwrapObservable(min);
max = ko.utils.unwrapObservable(max);
var result = [];
for (var i = min; i <= max; i++)
result.push(i);
return result;
},
makeArray: function(arrayLikeObject) {
var result = [];
for (var i = 0, j = arrayLikeObject.length; i < j; i++) {
result.push(arrayLikeObject[i]);
};
return result;
},
isIe6 : isIe6,
isIe7 : isIe7,
ieVersion : ieVersion,
getFormFields: function(form, fieldName) {
var fields = ko.utils.makeArray(form.getElementsByTagName("input")).concat(ko.utils.makeArray(form.getElementsByTagName("textarea")));
var isMatchingField = (typeof fieldName == 'string')
? function(field) { return field.name === fieldName }
: function(field) { return fieldName.test(field.name) }; // Treat fieldName as regex or object containing predicate
var matches = [];
for (var i = fields.length - 1; i >= 0; i--) {
if (isMatchingField(fields[i]))
matches.push(fields[i]);
};
return matches;
},
parseJson: function (jsonString) {
if (typeof jsonString == "string") {
jsonString = ko.utils.stringTrim(jsonString);
if (jsonString) {
if (window.JSON && window.JSON.parse) // Use native parsing where available
return window.JSON.parse(jsonString);
return (new Function("return " + jsonString))(); // Fallback on less safe parsing for older browsers
}
}
return null;
},
stringifyJson: function (data, replacer, space) { // replacer and space are optional
if ((typeof JSON == "undefined") || (typeof JSON.stringify == "undefined"))
throw new Error("Cannot find JSON.stringify(). Some browsers (e.g., IE < 8) don't support it natively, but you can overcome this by adding a script reference to json2.js, downloadable from http://www.json.org/json2.js");
return JSON.stringify(ko.utils.unwrapObservable(data), replacer, space);
},
postJson: function (urlOrForm, data, options) {
options = options || {};
var params = options['params'] || {};
var includeFields = options['includeFields'] || this.fieldsIncludedWithJsonPost;
var url = urlOrForm;
// If we were given a form, use its 'action' URL and pick out any requested field values
if((typeof urlOrForm == 'object') && (ko.utils.tagNameLower(urlOrForm) === "form")) {
var originalForm = urlOrForm;
url = originalForm.action;
for (var i = includeFields.length - 1; i >= 0; i--) {
var fields = ko.utils.getFormFields(originalForm, includeFields[i]);
for (var j = fields.length - 1; j >= 0; j--)
params[fields[j].name] = fields[j].value;
}
}
data = ko.utils.unwrapObservable(data);
var form = document.createElement("form");
form.style.display = "none";
form.action = url;
form.method = "post";
for (var key in data) {
var input = document.createElement("input");
input.name = key;
input.value = ko.utils.stringifyJson(ko.utils.unwrapObservable(data[key]));
form.appendChild(input);
}
for (var key in params) {
var input = document.createElement("input");
input.name = key;
input.value = params[key];
form.appendChild(input);
}
document.body.appendChild(form);
options['submitter'] ? options['submitter'](form) : form.submit();
setTimeout(function () { form.parentNode.removeChild(form); }, 0);
}
}
})();
ko.exportSymbol('utils', ko.utils);
ko.exportSymbol('utils.arrayForEach', ko.utils.arrayForEach);
ko.exportSymbol('utils.arrayFirst', ko.utils.arrayFirst);
ko.exportSymbol('utils.arrayFilter', ko.utils.arrayFilter);
ko.exportSymbol('utils.arrayGetDistinctValues', ko.utils.arrayGetDistinctValues);
ko.exportSymbol('utils.arrayIndexOf', ko.utils.arrayIndexOf);
ko.exportSymbol('utils.arrayMap', ko.utils.arrayMap);
ko.exportSymbol('utils.arrayPushAll', ko.utils.arrayPushAll);
ko.exportSymbol('utils.arrayRemoveItem', ko.utils.arrayRemoveItem);
ko.exportSymbol('utils.extend', ko.utils.extend);
ko.exportSymbol('utils.fieldsIncludedWithJsonPost', ko.utils.fieldsIncludedWithJsonPost);
ko.exportSymbol('utils.getFormFields', ko.utils.getFormFields);
ko.exportSymbol('utils.postJson', ko.utils.postJson);
ko.exportSymbol('utils.parseJson', ko.utils.parseJson);
ko.exportSymbol('utils.registerEventHandler', ko.utils.registerEventHandler);
ko.exportSymbol('utils.stringifyJson', ko.utils.stringifyJson);
ko.exportSymbol('utils.range', ko.utils.range);
ko.exportSymbol('utils.toggleDomNodeCssClass', ko.utils.toggleDomNodeCssClass);
ko.exportSymbol('utils.triggerEvent', ko.utils.triggerEvent);
ko.exportSymbol('utils.unwrapObservable', ko.utils.unwrapObservable);
if (!Function.prototype['bind']) {
// Function.prototype.bind is a standard part of ECMAScript 5th Edition (December 2009, http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf)
// In case the browser doesn't implement it natively, provide a JavaScript implementation. This implementation is based on the one in prototype.js
Function.prototype['bind'] = function (object) {
var originalFunction = this, args = Array.prototype.slice.call(arguments), object = args.shift();
return function () {
return originalFunction.apply(object, args.concat(Array.prototype.slice.call(arguments)));
};
};
}
ko.utils.domData = new (function () {
var uniqueId = 0;
var dataStoreKeyExpandoPropertyName = "__ko__" + (new Date).getTime();
var dataStore = {};
return {
get: function (node, key) {
var allDataForNode = ko.utils.domData.getAll(node, false);
return allDataForNode === undefined ? undefined : allDataForNode[key];
},
set: function (node, key, value) {
if (value === undefined) {
// Make sure we don't actually create a new domData key if we are actually deleting a value
if (ko.utils.domData.getAll(node, false) === undefined)
return;
}
var allDataForNode = ko.utils.domData.getAll(node, true);
allDataForNode[key] = value;
},
getAll: function (node, createIfNotFound) {
var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
var hasExistingDataStore = dataStoreKey && (dataStoreKey !== "null");
if (!hasExistingDataStore) {
if (!createIfNotFound)
return undefined;
dataStoreKey = node[dataStoreKeyExpandoPropertyName] = "ko" + uniqueId++;
dataStore[dataStoreKey] = {};
}
return dataStore[dataStoreKey];
},
clear: function (node) {
var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
if (dataStoreKey) {
delete dataStore[dataStoreKey];
node[dataStoreKeyExpandoPropertyName] = null;
}
}
}
})();
ko.exportSymbol('utils.domData', ko.utils.domData);
ko.exportSymbol('utils.domData.clear', ko.utils.domData.clear); // Exporting only so specs can clear up after themselves fully
ko.utils.domNodeDisposal = new (function () {
var domDataKey = "__ko_domNodeDisposal__" + (new Date).getTime();
var cleanableNodeTypes = { 1: true, 8: true, 9: true }; // Element, Comment, Document
var cleanableNodeTypesWithDescendants = { 1: true, 9: true }; // Element, Document
function getDisposeCallbacksCollection(node, createIfNotFound) {
var allDisposeCallbacks = ko.utils.domData.get(node, domDataKey);
if ((allDisposeCallbacks === undefined) && createIfNotFound) {
allDisposeCallbacks = [];
ko.utils.domData.set(node, domDataKey, allDisposeCallbacks);
}
return allDisposeCallbacks;
}
function destroyCallbacksCollection(node) {
ko.utils.domData.set(node, domDataKey, undefined);
}
function cleanSingleNode(node) {
// Run all the dispose callbacks
var callbacks = getDisposeCallbacksCollection(node, false);
if (callbacks) {
callbacks = callbacks.slice(0); // Clone, as the array may be modified during iteration (typically, callbacks will remove themselves)
for (var i = 0; i < callbacks.length; i++)
callbacks[i](node);
}
// Also erase the DOM data
ko.utils.domData.clear(node);
// Special support for jQuery here because it's so commonly used.
// Many jQuery plugins (including jquery.tmpl) store data using jQuery's equivalent of domData
// so notify it to tear down any resources associated with the node & descendants here.
if ((typeof jQuery == "function") && (typeof jQuery['cleanData'] == "function"))
jQuery['cleanData']([node]);
// Also clear any immediate-child comment nodes, as these wouldn't have been found by
// node.getElementsByTagName("*") in cleanNode() (comment nodes aren't elements)
if (cleanableNodeTypesWithDescendants[node.nodeType])
cleanImmediateCommentTypeChildren(node);
}
function cleanImmediateCommentTypeChildren(nodeWithChildren) {
var child, nextChild = nodeWithChildren.firstChild;
while (child = nextChild) {
nextChild = child.nextSibling;
if (child.nodeType === 8)
cleanSingleNode(child);
}
}
return {
addDisposeCallback : function(node, callback) {
if (typeof callback != "function")
throw new Error("Callback must be a function");
getDisposeCallbacksCollection(node, true).push(callback);
},
removeDisposeCallback : function(node, callback) {
var callbacksCollection = getDisposeCallbacksCollection(node, false);
if (callbacksCollection) {
ko.utils.arrayRemoveItem(callbacksCollection, callback);
if (callbacksCollection.length == 0)
destroyCallbacksCollection(node);
}
},
cleanNode : function(node) {
// First clean this node, where applicable
if (cleanableNodeTypes[node.nodeType]) {
cleanSingleNode(node);
// ... then its descendants, where applicable
if (cleanableNodeTypesWithDescendants[node.nodeType]) {
// Clone the descendants list in case it changes during iteration
var descendants = [];
ko.utils.arrayPushAll(descendants, node.getElementsByTagName("*"));
for (var i = 0, j = descendants.length; i < j; i++)
cleanSingleNode(descendants[i]);
}
}
},
removeNode : function(node) {
ko.cleanNode(node);
if (node.parentNode)
node.parentNode.removeChild(node);
}
}
})();
ko.cleanNode = ko.utils.domNodeDisposal.cleanNode; // Shorthand name for convenience
ko.removeNode = ko.utils.domNodeDisposal.removeNode; // Shorthand name for convenience
ko.exportSymbol('cleanNode', ko.cleanNode);
ko.exportSymbol('removeNode', ko.removeNode);
ko.exportSymbol('utils.domNodeDisposal', ko.utils.domNodeDisposal);
ko.exportSymbol('utils.domNodeDisposal.addDisposeCallback', ko.utils.domNodeDisposal.addDisposeCallback);
ko.exportSymbol('utils.domNodeDisposal.removeDisposeCallback', ko.utils.domNodeDisposal.removeDisposeCallback);
(function () {
var leadingCommentRegex = /^(\s*)<!--(.*?)-->/;
function simpleHtmlParse(html) {
// Based on jQuery's "clean" function, but only accounting for table-related elements.
// If you have referenced jQuery, this won't be used anyway - KO will use jQuery's "clean" function directly
// Note that there's still an issue in IE < 9 whereby it will discard comment nodes that are the first child of
// a descendant node. For example: "<div><!-- mycomment -->abc</div>" will get parsed as "<div>abc</div>"
// This won't affect anyone who has referenced jQuery, and there's always the workaround of inserting a dummy node
// (possibly a text node) in front of the comment. So, KO does not attempt to workaround this IE issue automatically at present.
// Trim whitespace, otherwise indexOf won't work as expected
var tags = ko.utils.stringTrim(html).toLowerCase(), div = document.createElement("div");
// Finds the first match from the left column, and returns the corresponding "wrap" data from the right column
var wrap = tags.match(/^<(thead|tbody|tfoot)/) && [1, "<table>", "</table>"] ||
!tags.indexOf("<tr") && [2, "<table><tbody>", "</tbody></table>"] ||
(!tags.indexOf("<td") || !tags.indexOf("<th")) && [3, "<table><tbody><tr>", "</tr></tbody></table>"] ||
/* anything else */ [0, "", ""];
// Go to html and back, then peel off extra wrappers
// Note that we always prefix with some dummy text, because otherwise, IE<9 will strip out leading comment nodes in descendants. Total madness.
var markup = "ignored<div>" + wrap[1] + html + wrap[2] + "</div>";
if (typeof window['innerShiv'] == "function") {
div.appendChild(window['innerShiv'](markup));
} else {
div.innerHTML = markup;
}
// Move to the right depth
while (wrap[0]--)
div = div.lastChild;
return ko.utils.makeArray(div.lastChild.childNodes);
}
function jQueryHtmlParse(html) {
var elems = jQuery['clean']([html]);
// As of jQuery 1.7.1, jQuery parses the HTML by appending it to some dummy parent nodes held in an in-memory document fragment.
// Unfortunately, it never clears the dummy parent nodes from the document fragment, so it leaks memory over time.
// Fix this by finding the top-most dummy parent element, and detaching it from its owner fragment.
if (elems && elems[0]) {
// Find the top-most parent element that's a direct child of a document fragment
var elem = elems[0];
while (elem.parentNode && elem.parentNode.nodeType !== 11 /* i.e., DocumentFragment */)
elem = elem.parentNode;
// ... then detach it
if (elem.parentNode)
elem.parentNode.removeChild(elem);
}
return elems;
}
ko.utils.parseHtmlFragment = function(html) {
return typeof jQuery != 'undefined' ? jQueryHtmlParse(html) // As below, benefit from jQuery's optimisations where possible
: simpleHtmlParse(html); // ... otherwise, this simple logic will do in most common cases.
};
ko.utils.setHtml = function(node, html) {
ko.utils.emptyDomNode(node);
if ((html !== null) && (html !== undefined)) {
if (typeof html != 'string')
html = html.toString();
// jQuery contains a lot of sophisticated code to parse arbitrary HTML fragments,
// for example <tr> elements which are not normally allowed to exist on their own.
// If you've referenced jQuery we'll use that rather than duplicating its code.
if (typeof jQuery != 'undefined') {
jQuery(node)['html'](html);
} else {
// ... otherwise, use KO's own parsing logic.
var parsedNodes = ko.utils.parseHtmlFragment(html);
for (var i = 0; i < parsedNodes.length; i++)
node.appendChild(parsedNodes[i]);
}
}
};
})();
ko.exportSymbol('utils.parseHtmlFragment', ko.utils.parseHtmlFragment);
ko.exportSymbol('utils.setHtml', ko.utils.setHtml);
ko.memoization = (function () {
var memos = {};
function randomMax8HexChars() {
return (((1 + Math.random()) * 0x100000000) | 0).toString(16).substring(1);
}
function generateRandomId() {
return randomMax8HexChars() + randomMax8HexChars();
}
function findMemoNodes(rootNode, appendToArray) {
if (!rootNode)
return;
if (rootNode.nodeType == 8) {
var memoId = ko.memoization.parseMemoText(rootNode.nodeValue);
if (memoId != null)
appendToArray.push({ domNode: rootNode, memoId: memoId });
} else if (rootNode.nodeType == 1) {
for (var i = 0, childNodes = rootNode.childNodes, j = childNodes.length; i < j; i++)
findMemoNodes(childNodes[i], appendToArray);
}
}
return {
memoize: function (callback) {
if (typeof callback != "function")
throw new Error("You can only pass a function to ko.memoization.memoize()");
var memoId = generateRandomId();
memos[memoId] = callback;
return "<!--[ko_memo:" + memoId + "]-->";
},
unmemoize: function (memoId, callbackParams) {
var callback = memos[memoId];
if (callback === undefined)
throw new Error("Couldn't find any memo with ID " + memoId + ". Perhaps it's already been unmemoized.");
try {
callback.apply(null, callbackParams || []);
return true;
}
finally { delete memos[memoId]; }
},
unmemoizeDomNodeAndDescendants: function (domNode, extraCallbackParamsArray) {
var memos = [];
findMemoNodes(domNode, memos);
for (var i = 0, j = memos.length; i < j; i++) {
var node = memos[i].domNode;
var combinedParams = [node];
if (extraCallbackParamsArray)
ko.utils.arrayPushAll(combinedParams, extraCallbackParamsArray);
ko.memoization.unmemoize(memos[i].memoId, combinedParams);
node.nodeValue = ""; // Neuter this node so we don't try to unmemoize it again
if (node.parentNode)
node.parentNode.removeChild(node); // If possible, erase it totally (not always possible - someone else might just hold a reference to it then call unmemoizeDomNodeAndDescendants again)
}
},
parseMemoText: function (memoText) {
var match = memoText.match(/^\[ko_memo\:(.*?)\]$/);
return match ? match[1] : null;
}
};
})();
ko.exportSymbol('memoization', ko.memoization);
ko.exportSymbol('memoization.memoize', ko.memoization.memoize);
ko.exportSymbol('memoization.unmemoize', ko.memoization.unmemoize);
ko.exportSymbol('memoization.parseMemoText', ko.memoization.parseMemoText);
ko.exportSymbol('memoization.unmemoizeDomNodeAndDescendants', ko.memoization.unmemoizeDomNodeAndDescendants);
ko.extenders = {
'throttle': function(target, timeout) {
// Throttling means two things:
// (1) For dependent observables, we throttle *evaluations* so that, no matter how fast its dependencies
// notify updates, the target doesn't re-evaluate (and hence doesn't notify) faster than a certain rate
target['throttleEvaluation'] = timeout;
// (2) For writable targets (observables, or writable dependent observables), we throttle *writes*
// so the target cannot change value synchronously or faster than a certain rate
var writeTimeoutInstance = null;
return ko.dependentObservable({
'read': target,
'write': function(value) {
clearTimeout(writeTimeoutInstance);
writeTimeoutInstance = setTimeout(function() {
target(value);
}, timeout);
}
});
},
'notify': function(target, notifyWhen) {
target["equalityComparer"] = notifyWhen == "always"
? function() { return false } // Treat all values as not equal
: ko.observable["fn"]["equalityComparer"];
return target;
}
};
function applyExtenders(requestedExtenders) {
var target = this;
if (requestedExtenders) {
for (var key in requestedExtenders) {
var extenderHandler = ko.extenders[key];
if (typeof extenderHandler == 'function') {
target = extenderHandler(target, requestedExtenders[key]);
}
}
}
return target;
}
ko.exportSymbol('extenders', ko.extenders);
ko.subscription = function (target, callback, disposeCallback) {
this.target = target;
this.callback = callback;
this.disposeCallback = disposeCallback;
ko.exportProperty(this, 'dispose', this.dispose);
};
ko.subscription.prototype.dispose = function () {
this.isDisposed = true;
this.disposeCallback();
};
ko.subscribable = function () {
this._subscriptions = {};
ko.utils.extend(this, ko.subscribable['fn']);
ko.exportProperty(this, 'subscribe', this.subscribe);
ko.exportProperty(this, 'extend', this.extend);
ko.exportProperty(this, 'getSubscriptionsCount', this.getSubscriptionsCount);
}
var defaultEvent = "change";
ko.subscribable['fn'] = {
subscribe: function (callback, callbackTarget, event) {
event = event || defaultEvent;
var boundCallback = callbackTarget ? callback.bind(callbackTarget) : callback;
var subscription = new ko.subscription(this, boundCallback, function () {
ko.utils.arrayRemoveItem(this._subscriptions[event], subscription);
}.bind(this));
if (!this._subscriptions[event])
this._subscriptions[event] = [];
this._subscriptions[event].push(subscription);
return subscription;
},
"notifySubscribers": function (valueToNotify, event) {
event = event || defaultEvent;
if (this._subscriptions[event]) {
ko.utils.arrayForEach(this._subscriptions[event].slice(0), function (subscription) {
// In case a subscription was disposed during the arrayForEach cycle, check
// for isDisposed on each subscription before invoking its callback
if (subscription && (subscription.isDisposed !== true))
subscription.callback(valueToNotify);
});
}
},
getSubscriptionsCount: function () {
var total = 0;
for (var eventName in this._subscriptions) {
if (this._subscriptions.hasOwnProperty(eventName))
total += this._subscriptions[eventName].length;
}
return total;
},
extend: applyExtenders
};
ko.isSubscribable = function (instance) {
return typeof instance.subscribe == "function" && typeof instance["notifySubscribers"] == "function";
};
ko.exportSymbol('subscribable', ko.subscribable);
ko.exportSymbol('isSubscribable', ko.isSubscribable);
ko.dependencyDetection = (function () {
var _frames = [];
return {
begin: function (callback) {
_frames.push({ callback: callback, distinctDependencies:[] });
},
end: function () {
_frames.pop();
},
registerDependency: function (subscribable) {
if (!ko.isSubscribable(subscribable))
throw new Error("Only subscribable things can act as dependencies");
if (_frames.length > 0) {
var topFrame = _frames[_frames.length - 1];
if (ko.utils.arrayIndexOf(topFrame.distinctDependencies, subscribable) >= 0)
return;
topFrame.distinctDependencies.push(subscribable);
topFrame.callback(subscribable);
}
}
};
})();
var primitiveTypes = { 'undefined':true, 'boolean':true, 'number':true, 'string':true };
ko.observable = function (initialValue) {
var _latestValue = initialValue;
function observable() {
if (arguments.length > 0) {
// Write
// Ignore writes if the value hasn't changed
if ((!observable['equalityComparer']) || !observable['equalityComparer'](_latestValue, arguments[0])) {
observable.valueWillMutate();
_latestValue = arguments[0];
if (DEBUG) observable._latestValue = _latestValue;
observable.valueHasMutated();
}
return this; // Permits chained assignments
}
else {
// Read
ko.dependencyDetection.registerDependency(observable); // The caller only needs to be notified of changes if they did a "read" operation
return _latestValue;
}
}
if (DEBUG) observable._latestValue = _latestValue;
ko.subscribable.call(observable);
observable.valueHasMutated = function () { observable["notifySubscribers"](_latestValue); }
observable.valueWillMutate = function () { observable["notifySubscribers"](_latestValue, "beforeChange"); }
ko.utils.extend(observable, ko.observable['fn']);
ko.exportProperty(observable, "valueHasMutated", observable.valueHasMutated);
ko.exportProperty(observable, "valueWillMutate", observable.valueWillMutate);
return observable;
}
ko.observable['fn'] = {
"equalityComparer": function valuesArePrimitiveAndEqual(a, b) {
var oldValueIsPrimitive = (a === null) || (typeof(a) in primitiveTypes);
return oldValueIsPrimitive ? (a === b) : false;
}
};
var protoProperty = ko.observable.protoProperty = "__ko_proto__";
ko.observable['fn'][protoProperty] = ko.observable;
ko.hasPrototype = function(instance, prototype) {
if ((instance === null) || (instance === undefined) || (instance[protoProperty] === undefined)) return false;
if (instance[protoProperty] === prototype) return true;
return ko.hasPrototype(instance[protoProperty], prototype); // Walk the prototype chain
};
ko.isObservable = function (instance) {
return ko.hasPrototype(instance, ko.observable);
}
ko.isWriteableObservable = function (instance) {
// Observable
if ((typeof instance == "function") && instance[protoProperty] === ko.observable)
return true;
// Writeable dependent observable
if ((typeof instance == "function") && (instance[protoProperty] === ko.dependentObservable) && (instance.hasWriteFunction))
return true;
// Anything else
return false;
}
ko.exportSymbol('observable', ko.observable);
ko.exportSymbol('isObservable', ko.isObservable);
ko.exportSymbol('isWriteableObservable', ko.isWriteableObservable);
ko.observableArray = function (initialValues) {
if (arguments.length == 0) {
// Zero-parameter constructor initializes to empty array
initialValues = [];
}
if ((initialValues !== null) && (initialValues !== undefined) && !('length' in initialValues))
throw new Error("The argument passed when initializing an observable array must be an array, or null, or undefined.");
var result = ko.observable(initialValues);
ko.utils.extend(result, ko.observableArray['fn']);
return result;
}
ko.observableArray['fn'] = {
'remove': function (valueOrPredicate) {
var underlyingArray = this();
var removedValues = [];
var predicate = typeof valueOrPredicate == "function" ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
for (var i = 0; i < underlyingArray.length; i++) {
var value = underlyingArray[i];
if (predicate(value)) {
if (removedValues.length === 0) {
this.valueWillMutate();
}
removedValues.push(value);
underlyingArray.splice(i, 1);
i--;
}
}
if (removedValues.length) {
this.valueHasMutated();
}
return removedValues;
},
'removeAll': function (arrayOfValues) {
// If you passed zero args, we remove everything
if (arrayOfValues === undefined) {
var underlyingArray = this();
var allValues = underlyingArray.slice(0);
this.valueWillMutate();
underlyingArray.splice(0, underlyingArray.length);
this.valueHasMutated();
return allValues;
}
// If you passed an arg, we interpret it as an array of entries to remove
if (!arrayOfValues)
return [];
return this['remove'](function (value) {
return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
});
},
'destroy': function (valueOrPredicate) {
var underlyingArray = this();
var predicate = typeof valueOrPredicate == "function" ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
this.valueWillMutate();
for (var i = underlyingArray.length - 1; i >= 0; i--) {
var value = underlyingArray[i];
if (predicate(value))
underlyingArray[i]["_destroy"] = true;
}
this.valueHasMutated();
},
'destroyAll': function (arrayOfValues) {
// If you passed zero args, we destroy everything
if (arrayOfValues === undefined)
return this['destroy'](function() { return true });
// If you passed an arg, we interpret it as an array of entries to destroy
if (!arrayOfValues)
return [];
return this['destroy'](function (value) {
return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
});
},
'indexOf': function (item) {
var underlyingArray = this();
return ko.utils.arrayIndexOf(underlyingArray, item);
},
'replace': function(oldItem, newItem) {
var index = this['indexOf'](oldItem);
if (index >= 0) {
this.valueWillMutate();
this()[index] = newItem;
this.valueHasMutated();
}
}
}
// Populate ko.observableArray.fn with read/write functions from native arrays
ko.utils.arrayForEach(["pop", "push", "reverse", "shift", "sort", "splice", "unshift"], function (methodName) {
ko.observableArray['fn'][methodName] = function () {
var underlyingArray = this();
this.valueWillMutate();
var methodCallResult = underlyingArray[methodName].apply(underlyingArray, arguments);
this.valueHasMutated();
return methodCallResult;
};
});
// Populate ko.observableArray.fn with read-only functions from native arrays
ko.utils.arrayForEach(["slice"], function (methodName) {
ko.observableArray['fn'][methodName] = function () {
var underlyingArray = this();
return underlyingArray[methodName].apply(underlyingArray, arguments);
};
});
ko.exportSymbol('observableArray', ko.observableArray);
ko.dependentObservable = function (evaluatorFunctionOrOptions, evaluatorFunctionTarget, options) {
var _latestValue,
_hasBeenEvaluated = false,
_isBeingEvaluated = false,
readFunction = evaluatorFunctionOrOptions;
if (readFunction && typeof readFunction == "object") {
// Single-parameter syntax - everything is on this "options" param
options = readFunction;
readFunction = options["read"];
} else {
// Multi-parameter syntax - construct the options according to the params passed
options = options || {};
if (!readFunction)
readFunction = options["read"];
}
// By here, "options" is always non-null
if (typeof readFunction != "function")
throw new Error("Pass a function that returns the value of the ko.computed");
var writeFunction = options["write"];
if (!evaluatorFunctionTarget)
evaluatorFunctionTarget = options["owner"];
var _subscriptionsToDependencies = [];
function disposeAllSubscriptionsToDependencies() {
ko.utils.arrayForEach(_subscriptionsToDependencies, function (subscription) {
subscription.dispose();
});
_subscriptionsToDependencies = [];
}
var dispose = disposeAllSubscriptionsToDependencies;
// Build "disposeWhenNodeIsRemoved" and "disposeWhenNodeIsRemovedCallback" option values
// (Note: "disposeWhenNodeIsRemoved" option both proactively disposes as soon as the node is removed using ko.removeNode(),
// plus adds a "disposeWhen" callback that, on each evaluation, disposes if the node was removed by some other means.)
var disposeWhenNodeIsRemoved = (typeof options["disposeWhenNodeIsRemoved"] == "object") ? options["disposeWhenNodeIsRemoved"] : null;
var disposeWhen = options["disposeWhen"] || function() { return false; };
if (disposeWhenNodeIsRemoved) {
dispose = function() {
ko.utils.domNodeDisposal.removeDisposeCallback(disposeWhenNodeIsRemoved, arguments.callee);
disposeAllSubscriptionsToDependencies();
};
ko.utils.domNodeDisposal.addDisposeCallback(disposeWhenNodeIsRemoved, dispose);
var existingDisposeWhenFunction = disposeWhen;
disposeWhen = function () {
return !ko.utils.domNodeIsAttachedToDocument(disposeWhenNodeIsRemoved) || existingDisposeWhenFunction();
}
}
var evaluationTimeoutInstance = null;
function evaluatePossiblyAsync() {
var throttleEvaluationTimeout = dependentObservable['throttleEvaluation'];
if (throttleEvaluationTimeout && throttleEvaluationTimeout >= 0) {
clearTimeout(evaluationTimeoutInstance);
evaluationTimeoutInstance = setTimeout(evaluateImmediate, throttleEvaluationTimeout);
} else
evaluateImmediate();
}
function evaluateImmediate() {
if (_isBeingEvaluated) {
// If the evaluation of a ko.computed causes side effects, it's possible that it will trigger its own re-evaluation.
// This is not desirable (it's hard for a developer to realise a chain of dependencies might cause this, and they almost
// certainly didn't intend infinite re-evaluations). So, for predictability, we simply prevent ko.computeds from causing
// their own re-evaluation. Further discussion at https://github.com/SteveSanderson/knockout/pull/387
return;
}
// Don't dispose on first evaluation, because the "disposeWhen" callback might
// e.g., dispose when the associated DOM element isn't in the doc, and it's not
// going to be in the doc until *after* the first evaluation
if (_hasBeenEvaluated && disposeWhen()) {
dispose();
return;
}
_isBeingEvaluated = true;
try {
// Initially, we assume that none of the subscriptions are still being used (i.e., all are candidates for disposal).
// Then, during evaluation, we cross off any that are in fact still being used.
var disposalCandidates = ko.utils.arrayMap(_subscriptionsToDependencies, function(item) {return item.target;});
ko.dependencyDetection.begin(function(subscribable) {
var inOld;
if ((inOld = ko.utils.arrayIndexOf(disposalCandidates, subscribable)) >= 0)
disposalCandidates[inOld] = undefined; // Don't want to dispose this subscription, as it's still being used
else
_subscriptionsToDependencies.push(subscribable.subscribe(evaluatePossiblyAsync)); // Brand new subscription - add it
});
var newValue = readFunction.call(evaluatorFunctionTarget);
// For each subscription no longer being used, remove it from the active subscriptions list and dispose it
for (var i = disposalCandidates.length - 1; i >= 0; i--) {
if (disposalCandidates[i])
_subscriptionsToDependencies.splice(i, 1)[0].dispose();
}
_hasBeenEvaluated = true;
dependentObservable["notifySubscribers"](_latestValue, "beforeChange");
_latestValue = newValue;
if (DEBUG) dependentObservable._latestValue = _latestValue;
} finally {
ko.dependencyDetection.end();
}
dependentObservable["notifySubscribers"](_latestValue);
_isBeingEvaluated = false;
}
function dependentObservable() {
if (arguments.length > 0) {
set.apply(dependentObservable, arguments);
} else {
return get();
}
}
function set() {
if (typeof writeFunction === "function") {
// Writing a value
writeFunction.apply(evaluatorFunctionTarget, arguments);
} else {
throw new Error("Cannot write a value to a ko.computed unless you specify a 'write' option. If you wish to read the current value, don't pass any parameters.");
}
}
function get() {
// Reading the value
if (!_hasBeenEvaluated)
evaluateImmediate();
ko.dependencyDetection.registerDependency(dependentObservable);
return _latestValue;
}
dependentObservable.getDependenciesCount = function () { return _subscriptionsToDependencies.length; };
dependentObservable.hasWriteFunction = typeof options["write"] === "function";
dependentObservable.dispose = function () { dispose(); };
ko.subscribable.call(dependentObservable);
ko.utils.extend(dependentObservable, ko.dependentObservable['fn']);
if (options['deferEvaluation'] !== true)
evaluateImmediate();
ko.exportProperty(dependentObservable, 'dispose', dependentObservable.dispose);
ko.exportProperty(dependentObservable, 'getDependenciesCount', dependentObservable.getDependenciesCount);
return dependentObservable;
};
ko.isComputed = function(instance) {
return ko.hasPrototype(instance, ko.dependentObservable);
};
var protoProp = ko.observable.protoProperty; // == "__ko_proto__"
ko.dependentObservable[protoProp] = ko.observable;
ko.dependentObservable['fn'] = {};
ko.dependentObservable['fn'][protoProp] = ko.dependentObservable;
ko.exportSymbol('dependentObservable', ko.dependentObservable);
ko.exportSymbol('computed', ko.dependentObservable); // Make "ko.computed" an alias for "ko.dependentObservable"
ko.exportSymbol('isComputed', ko.isComputed);
(function() {
var maxNestedObservableDepth = 10; // Escape the (unlikely) pathalogical case where an observable's current value is itself (or similar reference cycle)
ko.toJS = function(rootObject) {
if (arguments.length == 0)
throw new Error("When calling ko.toJS, pass the object you want to convert.");
// We just unwrap everything at every level in the object graph
return mapJsObjectGraph(rootObject, function(valueToMap) {
// Loop because an observable's value might in turn be another observable wrapper
for (var i = 0; ko.isObservable(valueToMap) && (i < maxNestedObservableDepth); i++)
valueToMap = valueToMap();
return valueToMap;
});
};
ko.toJSON = function(rootObject, replacer, space) { // replacer and space are optional
var plainJavaScriptObject = ko.toJS(rootObject);
return ko.utils.stringifyJson(plainJavaScriptObject, replacer, space);
};
function mapJsObjectGraph(rootObject, mapInputCallback, visitedObjects) {
visitedObjects = visitedObjects || new objectLookup();
rootObject = mapInputCallback(rootObject);
var canHaveProperties = (typeof rootObject == "object") && (rootObject !== null) && (rootObject !== undefined) && (!(rootObject instanceof Date));
if (!canHaveProperties)
return rootObject;
var outputProperties = rootObject instanceof Array ? [] : {};
visitedObjects.save(rootObject, outputProperties);
visitPropertiesOrArrayEntries(rootObject, function(indexer) {
var propertyValue = mapInputCallback(rootObject[indexer]);
switch (typeof propertyValue) {
case "boolean":
case "number":
case "string":
case "function":
outputProperties[indexer] = propertyValue;
break;
case "object":
case "undefined":
var previouslyMappedValue = visitedObjects.get(propertyValue);
outputProperties[indexer] = (previouslyMappedValue !== undefined)
? previouslyMappedValue
: mapJsObjectGraph(propertyValue, mapInputCallback, visitedObjects);
break;
}
});
return outputProperties;
}
function visitPropertiesOrArrayEntries(rootObject, visitorCallback) {
if (rootObject instanceof Array) {
for (var i = 0; i < rootObject.length; i++)
visitorCallback(i);
// For arrays, also respect toJSON property for custom mappings (fixes #278)
if (typeof rootObject['toJSON'] == 'function')
visitorCallback('toJSON');
} else {
for (var propertyName in rootObject)
visitorCallback(propertyName);
}
};
function objectLookup() {
var keys = [];
var values = [];
this.save = function(key, value) {
var existingIndex = ko.utils.arrayIndexOf(keys, key);
if (existingIndex >= 0)
values[existingIndex] = value;
else {
keys.push(key);
values.push(value);
}
};
this.get = function(key) {
var existingIndex = ko.utils.arrayIndexOf(keys, key);
return (existingIndex >= 0) ? values[existingIndex] : undefined;
};
};
})();
ko.exportSymbol('toJS', ko.toJS);
ko.exportSymbol('toJSON', ko.toJSON);
(function () {
var hasDomDataExpandoProperty = '__ko__hasDomDataOptionValue__';
// Normally, SELECT elements and their OPTIONs can only take value of type 'string' (because the values
// are stored on DOM attributes). ko.selectExtensions provides a way for SELECTs/OPTIONs to have values
// that are arbitrary objects. This is very convenient when implementing things like cascading dropdowns.
ko.selectExtensions = {
readValue : function(element) {
switch (ko.utils.tagNameLower(element)) {
case 'option':
if (element[hasDomDataExpandoProperty] === true)
return ko.utils.domData.get(element, ko.bindingHandlers.options.optionValueDomDataKey);
return element.getAttribute("value");
case 'select':
return element.selectedIndex >= 0 ? ko.selectExtensions.readValue(element.options[element.selectedIndex]) : undefined;
default:
return element.value;
}
},
writeValue: function(element, value) {
switch (ko.utils.tagNameLower(element)) {
case 'option':
switch(typeof value) {
case "string":
ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, undefined);
if (hasDomDataExpandoProperty in element) { // IE <= 8 throws errors if you delete non-existent properties from a DOM node
delete element[hasDomDataExpandoProperty];
}
element.value = value;
break;
default:
// Store arbitrary object using DomData
ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, value);
element[hasDomDataExpandoProperty] = true;
// Special treatment of numbers is just for backward compatibility. KO 1.2.1 wrote numerical values to element.value.
element.value = typeof value === "number" ? value : "";
break;
}
break;
case 'select':
for (var i = element.options.length - 1; i >= 0; i--) {
if (ko.selectExtensions.readValue(element.options[i]) == value) {
element.selectedIndex = i;
break;
}
}
break;
default:
if ((value === null) || (value === undefined))
value = "";
element.value = value;
break;
}
}
};
})();
ko.exportSymbol('selectExtensions', ko.selectExtensions);
ko.exportSymbol('selectExtensions.readValue', ko.selectExtensions.readValue);
ko.exportSymbol('selectExtensions.writeValue', ko.selectExtensions.writeValue);
ko.jsonExpressionRewriting = (function () {
var restoreCapturedTokensRegex = /\@ko_token_(\d+)\@/g;
var javaScriptAssignmentTarget = /^[\_$a-z][\_$a-z0-9]*(\[.*?\])*(\.[\_$a-z][\_$a-z0-9]*(\[.*?\])*)*$/i;
var javaScriptReservedWords = ["true", "false"];
function restoreTokens(string, tokens) {
var prevValue = null;
while (string != prevValue) { // Keep restoring tokens until it no longer makes a difference (they may be nested)
prevValue = string;
string = string.replace(restoreCapturedTokensRegex, function (match, tokenIndex) {
return tokens[tokenIndex];
});
}
return string;
}
function isWriteableValue(expression) {
if (ko.utils.arrayIndexOf(javaScriptReservedWords, ko.utils.stringTrim(expression).toLowerCase()) >= 0)
return false;
return expression.match(javaScriptAssignmentTarget) !== null;
}
function ensureQuoted(key) {
var trimmedKey = ko.utils.stringTrim(key);
switch (trimmedKey.length && trimmedKey.charAt(0)) {
case "'":
case '"':
return key;
default:
return "'" + trimmedKey + "'";
}
}
return {
bindingRewriteValidators: [],
parseObjectLiteral: function(objectLiteralString) {
// A full tokeniser+lexer would add too much weight to this library, so here's a simple parser
// that is sufficient just to split an object literal string into a set of top-level key-value pairs
var str = ko.utils.stringTrim(objectLiteralString);
if (str.length < 3)
return [];
if (str.charAt(0) === "{")// Ignore any braces surrounding the whole object literal
str = str.substring(1, str.length - 1);
// Pull out any string literals and regex literals
var tokens = [];
var tokenStart = null, tokenEndChar;
for (var position = 0; position < str.length; position++) {
var c = str.charAt(position);
if (tokenStart === null) {
switch (c) {
case '"':
case "'":
case "/":
tokenStart = position;
tokenEndChar = c;
break;
}
} else if ((c == tokenEndChar) && (str.charAt(position - 1) !== "\\")) {
var token = str.substring(tokenStart, position + 1);
tokens.push(token);
var replacement = "@ko_token_" + (tokens.length - 1) + "@";
str = str.substring(0, tokenStart) + replacement + str.substring(position + 1);
position -= (token.length - replacement.length);
tokenStart = null;
}
}
// Next pull out balanced paren, brace, and bracket blocks
tokenStart = null;
tokenEndChar = null;
var tokenDepth = 0, tokenStartChar = null;
for (var position = 0; position < str.length; position++) {
var c = str.charAt(position);
if (tokenStart === null) {
switch (c) {
case "{": tokenStart = position; tokenStartChar = c;
tokenEndChar = "}";
break;
case "(": tokenStart = position; tokenStartChar = c;
tokenEndChar = ")";
break;
case "[": tokenStart = position; tokenStartChar = c;
tokenEndChar = "]";
break;
}
}
if (c === tokenStartChar)
tokenDepth++;
else if (c === tokenEndChar) {
tokenDepth--;
if (tokenDepth === 0) {
var token = str.substring(tokenStart, position + 1);
tokens.push(token);
var replacement = "@ko_token_" + (tokens.length - 1) + "@";
str = str.substring(0, tokenStart) + replacement + str.substring(position + 1);
position -= (token.length - replacement.length);
tokenStart = null;
}
}
}
// Now we can safely split on commas to get the key/value pairs
var result = [];
var keyValuePairs = str.split(",");
for (var i = 0, j = keyValuePairs.length; i < j; i++) {
var pair = keyValuePairs[i];
var colonPos = pair.indexOf(":");
if ((colonPos > 0) && (colonPos < pair.length - 1)) {
var key = pair.substring(0, colonPos);
var value = pair.substring(colonPos + 1);
result.push({ 'key': restoreTokens(key, tokens), 'value': restoreTokens(value, tokens) });
} else {
result.push({ 'unknown': restoreTokens(pair, tokens) });
}
}
return result;
},
insertPropertyAccessorsIntoJson: function (objectLiteralStringOrKeyValueArray) {
var keyValueArray = typeof objectLiteralStringOrKeyValueArray === "string"
? ko.jsonExpressionRewriting.parseObjectLiteral(objectLiteralStringOrKeyValueArray)
: objectLiteralStringOrKeyValueArray;
var resultStrings = [], propertyAccessorResultStrings = [];
var keyValueEntry;
for (var i = 0; keyValueEntry = keyValueArray[i]; i++) {
if (resultStrings.length > 0)
resultStrings.push(",");
if (keyValueEntry['key']) {
var quotedKey = ensureQuoted(keyValueEntry['key']), val = keyValueEntry['value'];
resultStrings.push(quotedKey);
resultStrings.push(":");
resultStrings.push(val);
if (isWriteableValue(ko.utils.stringTrim(val))) {
if (propertyAccessorResultStrings.length > 0)
propertyAccessorResultStrings.push(", ");
propertyAccessorResultStrings.push(quotedKey + " : function(__ko_value) { " + val + " = __ko_value; }");
}
} else if (keyValueEntry['unknown']) {
resultStrings.push(keyValueEntry['unknown']);
}
}
var combinedResult = resultStrings.join("");
if (propertyAccessorResultStrings.length > 0) {
var allPropertyAccessors = propertyAccessorResultStrings.join("");
combinedResult = combinedResult + ", '_ko_property_writers' : { " + allPropertyAccessors + " } ";
}
return combinedResult;
},
keyValueArrayContainsKey: function(keyValueArray, key) {
for (var i = 0; i < keyValueArray.length; i++)
if (ko.utils.stringTrim(keyValueArray[i]['key']) == key)
return true;
return false;
},
// Internal, private KO utility for updating model properties from within bindings
// property: If the property being updated is (or might be) an observable, pass it here
// If it turns out to be a writable observable, it will be written to directly
// allBindingsAccessor: All bindings in the current execution context.
// This will be searched for a '_ko_property_writers' property in case you're writing to a non-observable
// key: The key identifying the property to be written. Example: for { hasFocus: myValue }, write to 'myValue' by specifying the key 'hasFocus'
// value: The value to be written
// checkIfDifferent: If true, and if the property being written is a writable observable, the value will only be written if
// it is !== existing value on that writable observable
writeValueToProperty: function(property, allBindingsAccessor, key, value, checkIfDifferent) {
if (!property || !ko.isWriteableObservable(property)) {
var propWriters = allBindingsAccessor()['_ko_property_writers'];
if (propWriters && propWriters[key])
propWriters[key](value);
} else if (!checkIfDifferent || property() !== value) {
property(value);
}
}
};
})();
ko.exportSymbol('jsonExpressionRewriting', ko.jsonExpressionRewriting);
ko.exportSymbol('jsonExpressionRewriting.bindingRewriteValidators', ko.jsonExpressionRewriting.bindingRewriteValidators);
ko.exportSymbol('jsonExpressionRewriting.parseObjectLiteral', ko.jsonExpressionRewriting.parseObjectLiteral);
ko.exportSymbol('jsonExpressionRewriting.insertPropertyAccessorsIntoJson', ko.jsonExpressionRewriting.insertPropertyAccessorsIntoJson);
(function() {
// "Virtual elements" is an abstraction on top of the usual DOM API which understands the notion that comment nodes
// may be used to represent hierarchy (in addition to the DOM's natural hierarchy).
// If you call the DOM-manipulating functions on ko.virtualElements, you will be able to read and write the state
// of that virtual hierarchy
//
// The point of all this is to support containerless templates (e.g., <!-- ko foreach:someCollection -->blah<!-- /ko -->)
// without having to scatter special cases all over the binding and templating code.
// IE 9 cannot reliably read the "nodeValue" property of a comment node (see https://github.com/SteveSanderson/knockout/issues/186)
// but it does give them a nonstandard alternative property called "text" that it can read reliably. Other browsers don't have that property.
// So, use node.text where available, and node.nodeValue elsewhere
var commentNodesHaveTextProperty = document.createComment("test").text === "<!--test-->";
var startCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*ko\s+(.*\:.*)\s*-->$/ : /^\s*ko\s+(.*\:.*)\s*$/;
var endCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*\/ko\s*-->$/ : /^\s*\/ko\s*$/;
var htmlTagsWithOptionallyClosingChildren = { 'ul': true, 'ol': true };
function isStartComment(node) {
return (node.nodeType == 8) && (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(startCommentRegex);
}
function isEndComment(node) {
return (node.nodeType == 8) && (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(endCommentRegex);
}
function getVirtualChildren(startComment, allowUnbalanced) {
var currentNode = startComment;
var depth = 1;
var children = [];
while (currentNode = currentNode.nextSibling) {
if (isEndComment(currentNode)) {
depth--;
if (depth === 0)
return children;
}
children.push(currentNode);
if (isStartComment(currentNode))
depth++;
}
if (!allowUnbalanced)
throw new Error("Cannot find closing comment tag to match: " + startComment.nodeValue);
return null;
}
function getMatchingEndComment(startComment, allowUnbalanced) {
var allVirtualChildren = getVirtualChildren(startComment, allowUnbalanced);
if (allVirtualChildren) {
if (allVirtualChildren.length > 0)
return allVirtualChildren[allVirtualChildren.length - 1].nextSibling;
return startComment.nextSibling;
} else
return null; // Must have no matching end comment, and allowUnbalanced is true
}
function getUnbalancedChildTags(node) {
// e.g., from <div>OK</div><!-- ko blah --><span>Another</span>, returns: <!-- ko blah --><span>Another</span>
// from <div>OK</div><!-- /ko --><!-- /ko -->, returns: <!-- /ko --><!-- /ko -->
var childNode = node.firstChild, captureRemaining = null;
if (childNode) {
do {
if (captureRemaining) // We already hit an unbalanced node and are now just scooping up all subsequent nodes
captureRemaining.push(childNode);
else if (isStartComment(childNode)) {
var matchingEndComment = getMatchingEndComment(childNode, /* allowUnbalanced: */ true);
if (matchingEndComment) // It's a balanced tag, so skip immediately to the end of this virtual set
childNode = matchingEndComment;
else
captureRemaining = [childNode]; // It's unbalanced, so start capturing from this point
} else if (isEndComment(childNode)) {
captureRemaining = [childNode]; // It's unbalanced (if it wasn't, we'd have skipped over it already), so start capturing
}
} while (childNode = childNode.nextSibling);
}
return captureRemaining;
}
ko.virtualElements = {
allowedBindings: {},
childNodes: function(node) {
return isStartComment(node) ? getVirtualChildren(node) : node.childNodes;
},
emptyNode: function(node) {
if (!isStartComment(node))
ko.utils.emptyDomNode(node);
else {
var virtualChildren = ko.virtualElements.childNodes(node);
for (var i = 0, j = virtualChildren.length; i < j; i++)
ko.removeNode(virtualChildren[i]);
}
},
setDomNodeChildren: function(node, childNodes) {
if (!isStartComment(node))
ko.utils.setDomNodeChildren(node, childNodes);
else {
ko.virtualElements.emptyNode(node);
var endCommentNode = node.nextSibling; // Must be the next sibling, as we just emptied the children
for (var i = 0, j = childNodes.length; i < j; i++)
endCommentNode.parentNode.insertBefore(childNodes[i], endCommentNode);
}
},
prepend: function(containerNode, nodeToPrepend) {
if (!isStartComment(containerNode)) {
if (containerNode.firstChild)
containerNode.insertBefore(nodeToPrepend, containerNode.firstChild);
else
containerNode.appendChild(nodeToPrepend);
} else {
// Start comments must always have a parent and at least one following sibling (the end comment)
containerNode.parentNode.insertBefore(nodeToPrepend, containerNode.nextSibling);
}
},
insertAfter: function(containerNode, nodeToInsert, insertAfterNode) {
if (!isStartComment(containerNode)) {
// Insert after insertion point
if (insertAfterNode.nextSibling)
containerNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
else
containerNode.appendChild(nodeToInsert);
} else {
// Children of start comments must always have a parent and at least one following sibling (the end comment)
containerNode.parentNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
}
},
firstChild: function(node) {
if (!isStartComment(node))
return node.firstChild;
if (!node.nextSibling || isEndComment(node.nextSibling))
return null;
return node.nextSibling;
},
nextSibling: function(node) {
if (isStartComment(node))
node = getMatchingEndComment(node);
if (node.nextSibling && isEndComment(node.nextSibling))
return null;
return node.nextSibling;
},
virtualNodeBindingValue: function(node) {
var regexMatch = isStartComment(node);
return regexMatch ? regexMatch[1] : null;
},
normaliseVirtualElementDomStructure: function(elementVerified) {
// Workaround for https://github.com/SteveSanderson/knockout/issues/155
// (IE <= 8 or IE 9 quirks mode parses your HTML weirdly, treating closing </li> tags as if they don't exist, thereby moving comment nodes
// that are direct descendants of <ul> into the preceding <li>)
if (!htmlTagsWithOptionallyClosingChildren[ko.utils.tagNameLower(elementVerified)])
return;
// Scan immediate children to see if they contain unbalanced comment tags. If they do, those comment tags
// must be intended to appear *after* that child, so move them there.
var childNode = elementVerified.firstChild;
if (childNode) {
do {
if (childNode.nodeType === 1) {
var unbalancedTags = getUnbalancedChildTags(childNode);
if (unbalancedTags) {
// Fix up the DOM by moving the unbalanced tags to where they most likely were intended to be placed - *after* the child
var nodeToInsertBefore = childNode.nextSibling;
for (var i = 0; i < unbalancedTags.length; i++) {
if (nodeToInsertBefore)
elementVerified.insertBefore(unbalancedTags[i], nodeToInsertBefore);
else
elementVerified.appendChild(unbalancedTags[i]);
}
}
}
} while (childNode = childNode.nextSibling);
}
}
};
})();
ko.exportSymbol('virtualElements', ko.virtualElements);
ko.exportSymbol('virtualElements.allowedBindings', ko.virtualElements.allowedBindings);
ko.exportSymbol('virtualElements.emptyNode', ko.virtualElements.emptyNode);
//ko.exportSymbol('virtualElements.firstChild', ko.virtualElements.firstChild); // firstChild is not minified
ko.exportSymbol('virtualElements.insertAfter', ko.virtualElements.insertAfter);
//ko.exportSymbol('virtualElements.nextSibling', ko.virtualElements.nextSibling); // nextSibling is not minified
ko.exportSymbol('virtualElements.prepend', ko.virtualElements.prepend);
ko.exportSymbol('virtualElements.setDomNodeChildren', ko.virtualElements.setDomNodeChildren);
(function() {
var defaultBindingAttributeName = "data-bind";
ko.bindingProvider = function() {
this.bindingCache = {};
};
ko.utils.extend(ko.bindingProvider.prototype, {
'nodeHasBindings': function(node) {
switch (node.nodeType) {
case 1: return node.getAttribute(defaultBindingAttributeName) != null; // Element
case 8: return ko.virtualElements.virtualNodeBindingValue(node) != null; // Comment node
default: return false;
}
},
'getBindings': function(node, bindingContext) {
var bindingsString = this['getBindingsString'](node, bindingContext);
return bindingsString ? this['parseBindingsString'](bindingsString, bindingContext) : null;
},
// The following function is only used internally by this default provider.
// It's not part of the interface definition for a general binding provider.
'getBindingsString': function(node, bindingContext) {
switch (node.nodeType) {
case 1: return node.getAttribute(defaultBindingAttributeName); // Element
case 8: return ko.virtualElements.virtualNodeBindingValue(node); // Comment node
default: return null;
}
},
// The following function is only used internally by this default provider.
// It's not part of the interface definition for a general binding provider.
'parseBindingsString': function(bindingsString, bindingContext) {
try {
var viewModel = bindingContext['$data'],
scopes = (typeof viewModel == 'object' && viewModel != null) ? [viewModel, bindingContext] : [bindingContext],
bindingFunction = createBindingsStringEvaluatorViaCache(bindingsString, scopes.length, this.bindingCache);
return bindingFunction(scopes);
} catch (ex) {
throw new Error("Unable to parse bindings.\nMessage: " + ex + ";\nBindings value: " + bindingsString);
}
}
});
ko.bindingProvider['instance'] = new ko.bindingProvider();
function createBindingsStringEvaluatorViaCache(bindingsString, scopesCount, cache) {
var cacheKey = scopesCount + '_' + bindingsString;
return cache[cacheKey]
|| (cache[cacheKey] = createBindingsStringEvaluator(bindingsString, scopesCount));
}
function createBindingsStringEvaluator(bindingsString, scopesCount) {
var rewrittenBindings = " { " + ko.jsonExpressionRewriting.insertPropertyAccessorsIntoJson(bindingsString) + " } ";
return ko.utils.buildEvalWithinScopeFunction(rewrittenBindings, scopesCount);
}
})();
ko.exportSymbol('bindingProvider', ko.bindingProvider);
(function () {
ko.bindingHandlers = {};
ko.bindingContext = function(dataItem, parentBindingContext) {
if (parentBindingContext) {
ko.utils.extend(this, parentBindingContext); // Inherit $root and any custom properties
this['$parentContext'] = parentBindingContext;
this['$parent'] = parentBindingContext['$data'];
this['$parents'] = (parentBindingContext['$parents'] || []).slice(0);
this['$parents'].unshift(this['$parent']);
} else {
this['$parents'] = [];
this['$root'] = dataItem;
}
this['$data'] = dataItem;
}
ko.bindingContext.prototype['createChildContext'] = function (dataItem) {
return new ko.bindingContext(dataItem, this);
};
ko.bindingContext.prototype['extend'] = function(properties) {
var clone = ko.utils.extend(new ko.bindingContext(), this);
return ko.utils.extend(clone, properties);
};
function validateThatBindingIsAllowedForVirtualElements(bindingName) {
var validator = ko.virtualElements.allowedBindings[bindingName];
if (!validator)
throw new Error("The binding '" + bindingName + "' cannot be used with virtual elements")
}
function applyBindingsToDescendantsInternal (viewModel, elementOrVirtualElement, bindingContextsMayDifferFromDomParentElement) {
var currentChild, nextInQueue = ko.virtualElements.firstChild(elementOrVirtualElement);
while (currentChild = nextInQueue) {
// Keep a record of the next child *before* applying bindings, in case the binding removes the current child from its position
nextInQueue = ko.virtualElements.nextSibling(currentChild);
applyBindingsToNodeAndDescendantsInternal(viewModel, currentChild, bindingContextsMayDifferFromDomParentElement);
}
}
function applyBindingsToNodeAndDescendantsInternal (viewModel, nodeVerified, bindingContextMayDifferFromDomParentElement) {
var shouldBindDescendants = true;
// Perf optimisation: Apply bindings only if...
// (1) We need to store the binding context on this node (because it may differ from the DOM parent node's binding context)
// Note that we can't store binding contexts on non-elements (e.g., text nodes), as IE doesn't allow expando properties for those
// (2) It might have bindings (e.g., it has a data-bind attribute, or it's a marker for a containerless template)
var isElement = (nodeVerified.nodeType === 1);
if (isElement) // Workaround IE <= 8 HTML parsing weirdness
ko.virtualElements.normaliseVirtualElementDomStructure(nodeVerified);
var shouldApplyBindings = (isElement && bindingContextMayDifferFromDomParentElement) // Case (1)
|| ko.bindingProvider['instance']['nodeHasBindings'](nodeVerified); // Case (2)
if (shouldApplyBindings)
shouldBindDescendants = applyBindingsToNodeInternal(nodeVerified, null, viewModel, bindingContextMayDifferFromDomParentElement).shouldBindDescendants;
if (shouldBindDescendants) {
// We're recursing automatically into (real or virtual) child nodes without changing binding contexts. So,
// * For children of a *real* element, the binding context is certainly the same as on their DOM .parentNode,
// hence bindingContextsMayDifferFromDomParentElement is false
// * For children of a *virtual* element, we can't be sure. Evaluating .parentNode on those children may
// skip over any number of intermediate virtual elements, any of which might define a custom binding context,
// hence bindingContextsMayDifferFromDomParentElement is true
applyBindingsToDescendantsInternal(viewModel, nodeVerified, /* bindingContextsMayDifferFromDomParentElement: */ !isElement);
}
}
function applyBindingsToNodeInternal (node, bindings, viewModelOrBindingContext, bindingContextMayDifferFromDomParentElement) {
// Need to be sure that inits are only run once, and updates never run until all the inits have been run
var initPhase = 0; // 0 = before all inits, 1 = during inits, 2 = after all inits
// Each time the dependentObservable is evaluated (after data changes),
// the binding attribute is reparsed so that it can pick out the correct
// model properties in the context of the changed data.
// DOM event callbacks need to be able to access this changed data,
// so we need a single parsedBindings variable (shared by all callbacks
// associated with this node's bindings) that all the closures can access.
var parsedBindings;
function makeValueAccessor(bindingKey) {
return function () { return parsedBindings[bindingKey] }
}
function parsedBindingsAccessor() {
return parsedBindings;
}
var bindingHandlerThatControlsDescendantBindings;
ko.dependentObservable(
function () {
// Ensure we have a nonnull binding context to work with
var bindingContextInstance = viewModelOrBindingContext && (viewModelOrBindingContext instanceof ko.bindingContext)
? viewModelOrBindingContext
: new ko.bindingContext(ko.utils.unwrapObservable(viewModelOrBindingContext));
var viewModel = bindingContextInstance['$data'];
// Optimization: Don't store the binding context on this node if it's definitely the same as on node.parentNode, because
// we can easily recover it just by scanning up the node's ancestors in the DOM
// (note: here, parent node means "real DOM parent" not "virtual parent", as there's no O(1) way to find the virtual parent)
if (bindingContextMayDifferFromDomParentElement)
ko.storedBindingContextForNode(node, bindingContextInstance);
// Use evaluatedBindings if given, otherwise fall back on asking the bindings provider to give us some bindings
var evaluatedBindings = (typeof bindings == "function") ? bindings() : bindings;
parsedBindings = evaluatedBindings || ko.bindingProvider['instance']['getBindings'](node, bindingContextInstance);
if (parsedBindings) {
// First run all the inits, so bindings can register for notification on changes
if (initPhase === 0) {
initPhase = 1;
for (var bindingKey in parsedBindings) {
var binding = ko.bindingHandlers[bindingKey];
if (binding && node.nodeType === 8)
validateThatBindingIsAllowedForVirtualElements(bindingKey);
if (binding && typeof binding["init"] == "function") {
var handlerInitFn = binding["init"];
var initResult = handlerInitFn(node, makeValueAccessor(bindingKey), parsedBindingsAccessor, viewModel, bindingContextInstance);
// If this binding handler claims to control descendant bindings, make a note of this
if (initResult && initResult['controlsDescendantBindings']) {
if (bindingHandlerThatControlsDescendantBindings !== undefined)
throw new Error("Multiple bindings (" + bindingHandlerThatControlsDescendantBindings + " and " + bindingKey + ") are trying to control descendant bindings of the same element. You cannot use these bindings together on the same element.");
bindingHandlerThatControlsDescendantBindings = bindingKey;
}
}
}
initPhase = 2;
}
// ... then run all the updates, which might trigger changes even on the first evaluation
if (initPhase === 2) {
for (var bindingKey in parsedBindings) {
var binding = ko.bindingHandlers[bindingKey];
if (binding && typeof binding["update"] == "function") {
var handlerUpdateFn = binding["update"];
handlerUpdateFn(node, makeValueAccessor(bindingKey), parsedBindingsAccessor, viewModel, bindingContextInstance);
}
}
}
}
},
null,
{ 'disposeWhenNodeIsRemoved' : node }
);
return {
shouldBindDescendants: bindingHandlerThatControlsDescendantBindings === undefined
};
};
var storedBindingContextDomDataKey = "__ko_bindingContext__";
ko.storedBindingContextForNode = function (node, bindingContext) {
if (arguments.length == 2)
ko.utils.domData.set(node, storedBindingContextDomDataKey, bindingContext);
else
return ko.utils.domData.get(node, storedBindingContextDomDataKey);
}
ko.applyBindingsToNode = function (node, bindings, viewModel) {
if (node.nodeType === 1) // If it's an element, workaround IE <= 8 HTML parsing weirdness
ko.virtualElements.normaliseVirtualElementDomStructure(node);
return applyBindingsToNodeInternal(node, bindings, viewModel, true);
};
ko.applyBindingsToDescendants = function(viewModel, rootNode) {
if (rootNode.nodeType === 1 || rootNode.nodeType === 8)
applyBindingsToDescendantsInternal(viewModel, rootNode, true);
};
ko.applyBindings = function (viewModel, rootNode) {
if (rootNode && (rootNode.nodeType !== 1) && (rootNode.nodeType !== 8))
throw new Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node");
rootNode = rootNode || window.document.body; // Make "rootNode" parameter optional
applyBindingsToNodeAndDescendantsInternal(viewModel, rootNode, true);
};
// Retrieving binding context from arbitrary nodes
ko.contextFor = function(node) {
// We can only do something meaningful for elements and comment nodes (in particular, not text nodes, as IE can't store domdata for them)
switch (node.nodeType) {
case 1:
case 8:
var context = ko.storedBindingContextForNode(node);
if (context) return context;
if (node.parentNode) return ko.contextFor(node.parentNode);
break;
}
return undefined;
};
ko.dataFor = function(node) {
var context = ko.contextFor(node);
return context ? context['$data'] : undefined;
};
ko.exportSymbol('bindingHandlers', ko.bindingHandlers);
ko.exportSymbol('applyBindings', ko.applyBindings);
ko.exportSymbol('applyBindingsToDescendants', ko.applyBindingsToDescendants);
ko.exportSymbol('applyBindingsToNode', ko.applyBindingsToNode);
ko.exportSymbol('contextFor', ko.contextFor);
ko.exportSymbol('dataFor', ko.dataFor);
})();
// For certain common events (currently just 'click'), allow a simplified data-binding syntax
// e.g. click:handler instead of the usual full-length event:{click:handler}
var eventHandlersWithShortcuts = ['click'];
ko.utils.arrayForEach(eventHandlersWithShortcuts, function(eventName) {
ko.bindingHandlers[eventName] = {
'init': function(element, valueAccessor, allBindingsAccessor, viewModel) {
var newValueAccessor = function () {
var result = {};
result[eventName] = valueAccessor();
return result;
};
return ko.bindingHandlers['event']['init'].call(this, element, newValueAccessor, allBindingsAccessor, viewModel);
}
}
});
ko.bindingHandlers['event'] = {
'init' : function (element, valueAccessor, allBindingsAccessor, viewModel) {
var eventsToHandle = valueAccessor() || {};
for(var eventNameOutsideClosure in eventsToHandle) {
(function() {
var eventName = eventNameOutsideClosure; // Separate variable to be captured by event handler closure
if (typeof eventName == "string") {
ko.utils.registerEventHandler(element, eventName, function (event) {
var handlerReturnValue;
var handlerFunction = valueAccessor()[eventName];
if (!handlerFunction)
return;
var allBindings = allBindingsAccessor();
try {
// Take all the event args, and prefix with the viewmodel
var argsForHandler = ko.utils.makeArray(arguments);
argsForHandler.unshift(viewModel);
handlerReturnValue = handlerFunction.apply(viewModel, argsForHandler);
} finally {
if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
if (event.preventDefault)
event.preventDefault();
else
event.returnValue = false;
}
}
var bubble = allBindings[eventName + 'Bubble'] !== false;
if (!bubble) {
event.cancelBubble = true;
if (event.stopPropagation)
event.stopPropagation();
}
});
}
})();
}
}
};
ko.bindingHandlers['submit'] = {
'init': function (element, valueAccessor, allBindingsAccessor, viewModel) {
if (typeof valueAccessor() != "function")
throw new Error("The value for a submit binding must be a function");
ko.utils.registerEventHandler(element, "submit", function (event) {
var handlerReturnValue;
var value = valueAccessor();
try { handlerReturnValue = value.call(viewModel, element); }
finally {
if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
if (event.preventDefault)
event.preventDefault();
else
event.returnValue = false;
}
}
});
}
};
ko.bindingHandlers['visible'] = {
'update': function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
var isCurrentlyVisible = !(element.style.display == "none");
if (value && !isCurrentlyVisible)
element.style.display = "";
else if ((!value) && isCurrentlyVisible)
element.style.display = "none";
}
}
ko.bindingHandlers['enable'] = {
'update': function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
if (value && element.disabled)
element.removeAttribute("disabled");
else if ((!value) && (!element.disabled))
element.disabled = true;
}
};
ko.bindingHandlers['disable'] = {
'update': function (element, valueAccessor) {
ko.bindingHandlers['enable']['update'](element, function() { return !ko.utils.unwrapObservable(valueAccessor()) });
}
};
function ensureDropdownSelectionIsConsistentWithModelValue(element, modelValue, preferModelValue) {
if (preferModelValue) {
if (modelValue !== ko.selectExtensions.readValue(element))
ko.selectExtensions.writeValue(element, modelValue);
}
// No matter which direction we're syncing in, we want the end result to be equality between dropdown value and model value.
// If they aren't equal, either we prefer the dropdown value, or the model value couldn't be represented, so either way,
// change the model value to match the dropdown.
if (modelValue !== ko.selectExtensions.readValue(element))
ko.utils.triggerEvent(element, "change");
};
ko.bindingHandlers['value'] = {
'init': function (element, valueAccessor, allBindingsAccessor) {
// Always catch "change" event; possibly other events too if asked
var eventsToCatch = ["change"];
var requestedEventsToCatch = allBindingsAccessor()["valueUpdate"];
if (requestedEventsToCatch) {
if (typeof requestedEventsToCatch == "string") // Allow both individual event names, and arrays of event names
requestedEventsToCatch = [requestedEventsToCatch];
ko.utils.arrayPushAll(eventsToCatch, requestedEventsToCatch);
eventsToCatch = ko.utils.arrayGetDistinctValues(eventsToCatch);
}
var valueUpdateHandler = function() {
var modelValue = valueAccessor();
var elementValue = ko.selectExtensions.readValue(element);
ko.jsonExpressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'value', elementValue, /* checkIfDifferent: */ true);
}
// Workaround for https://github.com/SteveSanderson/knockout/issues/122
// IE doesn't fire "change" events on textboxes if the user selects a value from its autocomplete list
var ieAutoCompleteHackNeeded = ko.utils.ieVersion && element.tagName.toLowerCase() == "input" && element.type == "text"
&& element.autocomplete != "off" && (!element.form || element.form.autocomplete != "off");
if (ieAutoCompleteHackNeeded && ko.utils.arrayIndexOf(eventsToCatch, "propertychange") == -1) {
var propertyChangedFired = false;
ko.utils.registerEventHandler(element, "propertychange", function () { propertyChangedFired = true });
ko.utils.registerEventHandler(element, "blur", function() {
if (propertyChangedFired) {
propertyChangedFired = false;
valueUpdateHandler();
}
});
}
ko.utils.arrayForEach(eventsToCatch, function(eventName) {
// The syntax "after<eventname>" means "run the handler asynchronously after the event"
// This is useful, for example, to catch "keydown" events after the browser has updated the control
// (otherwise, ko.selectExtensions.readValue(this) will receive the control's value *before* the key event)
var handler = valueUpdateHandler;
if (ko.utils.stringStartsWith(eventName, "after")) {
handler = function() { setTimeout(valueUpdateHandler, 0) };
eventName = eventName.substring("after".length);
}
ko.utils.registerEventHandler(element, eventName, handler);
});
},
'update': function (element, valueAccessor) {
var valueIsSelectOption = ko.utils.tagNameLower(element) === "select";
var newValue = ko.utils.unwrapObservable(valueAccessor());
var elementValue = ko.selectExtensions.readValue(element);
var valueHasChanged = (newValue != elementValue);
// JavaScript's 0 == "" behavious is unfortunate here as it prevents writing 0 to an empty text box (loose equality suggests the values are the same).
// We don't want to do a strict equality comparison as that is more confusing for developers in certain cases, so we specifically special case 0 != "" here.
if ((newValue === 0) && (elementValue !== 0) && (elementValue !== "0"))
valueHasChanged = true;
if (valueHasChanged) {
var applyValueAction = function () { ko.selectExtensions.writeValue(element, newValue); };
applyValueAction();
// Workaround for IE6 bug: It won't reliably apply values to SELECT nodes during the same execution thread
// right after you've changed the set of OPTION nodes on it. So for that node type, we'll schedule a second thread
// to apply the value as well.
var alsoApplyAsynchronously = valueIsSelectOption;
if (alsoApplyAsynchronously)
setTimeout(applyValueAction, 0);
}
// If you try to set a model value that can't be represented in an already-populated dropdown, reject that change,
// because you're not allowed to have a model value that disagrees with a visible UI selection.
if (valueIsSelectOption && (element.length > 0))
ensureDropdownSelectionIsConsistentWithModelValue(element, newValue, /* preferModelValue */ false);
}
};
ko.bindingHandlers['options'] = {
'update': function (element, valueAccessor, allBindingsAccessor) {
if (ko.utils.tagNameLower(element) !== "select")
throw new Error("options binding applies only to SELECT elements");
var selectWasPreviouslyEmpty = element.length == 0;
var previousSelectedValues = ko.utils.arrayMap(ko.utils.arrayFilter(element.childNodes, function (node) {
return node.tagName && (ko.utils.tagNameLower(node) === "option") && node.selected;
}), function (node) {
return ko.selectExtensions.readValue(node) || node.innerText || node.textContent;
});
var previousScrollTop = element.scrollTop;
var value = ko.utils.unwrapObservable(valueAccessor());
var selectedValue = element.value;
// Remove all existing <option>s.
// Need to use .remove() rather than .removeChild() for <option>s otherwise IE behaves oddly (https://github.com/SteveSanderson/knockout/issues/134)
while (element.length > 0) {
ko.cleanNode(element.options[0]);
element.remove(0);
}
if (value) {
var allBindings = allBindingsAccessor();
if (typeof value.length != "number")
value = [value];
if (allBindings['optionsCaption']) {
var option = document.createElement("option");
ko.utils.setHtml(option, allBindings['optionsCaption']);
ko.selectExtensions.writeValue(option, undefined);
element.appendChild(option);
}
for (var i = 0, j = value.length; i < j; i++) {
var option = document.createElement("option");
// Apply a value to the option element
var optionValue = typeof allBindings['optionsValue'] == "string" ? value[i][allBindings['optionsValue']] : value[i];
optionValue = ko.utils.unwrapObservable(optionValue);
ko.selectExtensions.writeValue(option, optionValue);
// Apply some text to the option element
var optionsTextValue = allBindings['optionsText'];
var optionText;
if (typeof optionsTextValue == "function")
optionText = optionsTextValue(value[i]); // Given a function; run it against the data value
else if (typeof optionsTextValue == "string")
optionText = value[i][optionsTextValue]; // Given a string; treat it as a property name on the data value
else
optionText = optionValue; // Given no optionsText arg; use the data value itself
if ((optionText === null) || (optionText === undefined))
optionText = "";
ko.utils.setTextContent(option, optionText);
element.appendChild(option);
}
// IE6 doesn't like us to assign selection to OPTION nodes before they're added to the document.
// That's why we first added them without selection. Now it's time to set the selection.
var newOptions = element.getElementsByTagName("option");
var countSelectionsRetained = 0;
for (var i = 0, j = newOptions.length; i < j; i++) {
if (ko.utils.arrayIndexOf(previousSelectedValues, ko.selectExtensions.readValue(newOptions[i])) >= 0) {
ko.utils.setOptionNodeSelectionState(newOptions[i], true);
countSelectionsRetained++;
}
}
element.scrollTop = previousScrollTop;
if (selectWasPreviouslyEmpty && ('value' in allBindings)) {
// Ensure consistency between model value and selected option.
// If the dropdown is being populated for the first time here (or was otherwise previously empty),
// the dropdown selection state is meaningless, so we preserve the model value.
ensureDropdownSelectionIsConsistentWithModelValue(element, ko.utils.unwrapObservable(allBindings['value']), /* preferModelValue */ true);
}
// Workaround for IE9 bug
ko.utils.ensureSelectElementIsRenderedCorrectly(element);
}
}
};
ko.bindingHandlers['options'].optionValueDomDataKey = '__ko.optionValueDomData__';
ko.bindingHandlers['selectedOptions'] = {
getSelectedValuesFromSelectNode: function (selectNode) {
var result = [];
var nodes = selectNode.childNodes;
for (var i = 0, j = nodes.length; i < j; i++) {
var node = nodes[i], tagName = ko.utils.tagNameLower(node);
if (tagName == "option" && node.selected)
result.push(ko.selectExtensions.readValue(node));
else if (tagName == "optgroup") {
var selectedValuesFromOptGroup = ko.bindingHandlers['selectedOptions'].getSelectedValuesFromSelectNode(node);
Array.prototype.splice.apply(result, [result.length, 0].concat(selectedValuesFromOptGroup)); // Add new entries to existing 'result' instance
}
}
return result;
},
'init': function (element, valueAccessor, allBindingsAccessor) {
ko.utils.registerEventHandler(element, "change", function () {
var value = valueAccessor();
var valueToWrite = ko.bindingHandlers['selectedOptions'].getSelectedValuesFromSelectNode(this);
ko.jsonExpressionRewriting.writeValueToProperty(value, allBindingsAccessor, 'value', valueToWrite);
});
},
'update': function (element, valueAccessor) {
if (ko.utils.tagNameLower(element) != "select")
throw new Error("values binding applies only to SELECT elements");
var newValue = ko.utils.unwrapObservable(valueAccessor());
if (newValue && typeof newValue.length == "number") {
var nodes = element.childNodes;
for (var i = 0, j = nodes.length; i < j; i++) {
var node = nodes[i];
if (ko.utils.tagNameLower(node) === "option")
ko.utils.setOptionNodeSelectionState(node, ko.utils.arrayIndexOf(newValue, ko.selectExtensions.readValue(node)) >= 0);
}
}
}
};
ko.bindingHandlers['text'] = {
'update': function (element, valueAccessor) {
ko.utils.setTextContent(element, valueAccessor());
}
};
ko.bindingHandlers['html'] = {
'init': function() {
// Prevent binding on the dynamically-injected HTML (as developers are unlikely to expect that, and it has security implications)
return { 'controlsDescendantBindings': true };
},
'update': function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
ko.utils.setHtml(element, value);
}
};
ko.bindingHandlers['css'] = {
'update': function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor() || {});
for (var className in value) {
if (typeof className == "string") {
var shouldHaveClass = ko.utils.unwrapObservable(value[className]);
ko.utils.toggleDomNodeCssClass(element, className, shouldHaveClass);
}
}
}
};
ko.bindingHandlers['style'] = {
'update': function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor() || {});
for (var styleName in value) {
if (typeof styleName == "string") {
var styleValue = ko.utils.unwrapObservable(value[styleName]);
element.style[styleName] = styleValue || ""; // Empty string removes the value, whereas null/undefined have no effect
}
}
}
};
ko.bindingHandlers['uniqueName'] = {
'init': function (element, valueAccessor) {
if (valueAccessor()) {
element.name = "ko_unique_" + (++ko.bindingHandlers['uniqueName'].currentIndex);
// Workaround IE 6/7 issue
// - https://github.com/SteveSanderson/knockout/issues/197
// - http://www.matts411.com/post/setting_the_name_attribute_in_ie_dom/
if (ko.utils.isIe6 || ko.utils.isIe7)
element.mergeAttributes(document.createElement("<input name='" + element.name + "'/>"), false);
}
}
};
ko.bindingHandlers['uniqueName'].currentIndex = 0;
ko.bindingHandlers['checked'] = {
'init': function (element, valueAccessor, allBindingsAccessor) {
var updateHandler = function() {
var valueToWrite;
if (element.type == "checkbox") {
valueToWrite = element.checked;
} else if ((element.type == "radio") && (element.checked)) {
valueToWrite = element.value;
} else {
return; // "checked" binding only responds to checkboxes and selected radio buttons
}
var modelValue = valueAccessor();
if ((element.type == "checkbox") && (ko.utils.unwrapObservable(modelValue) instanceof Array)) {
// For checkboxes bound to an array, we add/remove the checkbox value to that array
// This works for both observable and non-observable arrays
var existingEntryIndex = ko.utils.arrayIndexOf(ko.utils.unwrapObservable(modelValue), element.value);
if (element.checked && (existingEntryIndex < 0))
modelValue.push(element.value);
else if ((!element.checked) && (existingEntryIndex >= 0))
modelValue.splice(existingEntryIndex, 1);
} else {
ko.jsonExpressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'checked', valueToWrite, true);
}
};
ko.utils.registerEventHandler(element, "click", updateHandler);
// IE 6 won't allow radio buttons to be selected unless they have a name
if ((element.type == "radio") && !element.name)
ko.bindingHandlers['uniqueName']['init'](element, function() { return true });
},
'update': function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
if (element.type == "checkbox") {
if (value instanceof Array) {
// When bound to an array, the checkbox being checked represents its value being present in that array
element.checked = ko.utils.arrayIndexOf(value, element.value) >= 0;
} else {
// When bound to anything other value (not an array), the checkbox being checked represents the value being trueish
element.checked = value;
}
} else if (element.type == "radio") {
element.checked = (element.value == value);
}
}
};
var attrHtmlToJavascriptMap = { 'class': 'className', 'for': 'htmlFor' };
ko.bindingHandlers['attr'] = {
'update': function(element, valueAccessor, allBindingsAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor()) || {};
for (var attrName in value) {
if (typeof attrName == "string") {
var attrValue = ko.utils.unwrapObservable(value[attrName]);
// To cover cases like "attr: { checked:someProp }", we want to remove the attribute entirely
// when someProp is a "no value"-like value (strictly null, false, or undefined)
// (because the absence of the "checked" attr is how to mark an element as not checked, etc.)
var toRemove = (attrValue === false) || (attrValue === null) || (attrValue === undefined);
if (toRemove)
element.removeAttribute(attrName);
// In IE <= 7 and IE8 Quirks Mode, you have to use the Javascript property name instead of the
// HTML attribute name for certain attributes. IE8 Standards Mode supports the correct behavior,
// but instead of figuring out the mode, we'll just set the attribute through the Javascript
// property for IE <= 8.
if (ko.utils.ieVersion <= 8 && attrName in attrHtmlToJavascriptMap) {
attrName = attrHtmlToJavascriptMap[attrName];
if (toRemove)
element.removeAttribute(attrName);
else
element[attrName] = attrValue;
} else if (!toRemove) {
element.setAttribute(attrName, attrValue.toString());
}
}
}
}
};
ko.bindingHandlers['hasfocus'] = {
'init': function(element, valueAccessor, allBindingsAccessor) {
var writeValue = function(valueToWrite) {
var modelValue = valueAccessor();
ko.jsonExpressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'hasfocus', valueToWrite, true);
};
ko.utils.registerEventHandler(element, "focus", function() { writeValue(true) });
ko.utils.registerEventHandler(element, "focusin", function() { writeValue(true) }); // For IE
ko.utils.registerEventHandler(element, "blur", function() { writeValue(false) });
ko.utils.registerEventHandler(element, "focusout", function() { writeValue(false) }); // For IE
},
'update': function(element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
value ? element.focus() : element.blur();
ko.utils.triggerEvent(element, value ? "focusin" : "focusout"); // For IE, which doesn't reliably fire "focus" or "blur" events synchronously
}
};
// "with: someExpression" is equivalent to "template: { if: someExpression, data: someExpression }"
ko.bindingHandlers['with'] = {
makeTemplateValueAccessor: function(valueAccessor) {
return function() { var value = valueAccessor(); return { 'if': value, 'data': value, 'templateEngine': ko.nativeTemplateEngine.instance } };
},
'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['with'].makeTemplateValueAccessor(valueAccessor));
},
'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['with'].makeTemplateValueAccessor(valueAccessor), allBindingsAccessor, viewModel, bindingContext);
}
};
ko.jsonExpressionRewriting.bindingRewriteValidators['with'] = false; // Can't rewrite control flow bindings
ko.virtualElements.allowedBindings['with'] = true;
// "if: someExpression" is equivalent to "template: { if: someExpression }"
ko.bindingHandlers['if'] = {
makeTemplateValueAccessor: function(valueAccessor) {
return function() { return { 'if': valueAccessor(), 'templateEngine': ko.nativeTemplateEngine.instance } };
},
'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['if'].makeTemplateValueAccessor(valueAccessor));
},
'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['if'].makeTemplateValueAccessor(valueAccessor), allBindingsAccessor, viewModel, bindingContext);
}
};
ko.jsonExpressionRewriting.bindingRewriteValidators['if'] = false; // Can't rewrite control flow bindings
ko.virtualElements.allowedBindings['if'] = true;
// "ifnot: someExpression" is equivalent to "template: { ifnot: someExpression }"
ko.bindingHandlers['ifnot'] = {
makeTemplateValueAccessor: function(valueAccessor) {
return function() { return { 'ifnot': valueAccessor(), 'templateEngine': ko.nativeTemplateEngine.instance } };
},
'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['ifnot'].makeTemplateValueAccessor(valueAccessor));
},
'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['ifnot'].makeTemplateValueAccessor(valueAccessor), allBindingsAccessor, viewModel, bindingContext);
}
};
ko.jsonExpressionRewriting.bindingRewriteValidators['ifnot'] = false; // Can't rewrite control flow bindings
ko.virtualElements.allowedBindings['ifnot'] = true;
// "foreach: someExpression" is equivalent to "template: { foreach: someExpression }"
// "foreach: { data: someExpression, afterAdd: myfn }" is equivalent to "template: { foreach: someExpression, afterAdd: myfn }"
ko.bindingHandlers['foreach'] = {
makeTemplateValueAccessor: function(valueAccessor) {
return function() {
var bindingValue = ko.utils.unwrapObservable(valueAccessor());
// If bindingValue is the array, just pass it on its own
if ((!bindingValue) || typeof bindingValue.length == "number")
return { 'foreach': bindingValue, 'templateEngine': ko.nativeTemplateEngine.instance };
// If bindingValue.data is the array, preserve all relevant options
return {
'foreach': bindingValue['data'],
'includeDestroyed': bindingValue['includeDestroyed'],
'afterAdd': bindingValue['afterAdd'],
'beforeRemove': bindingValue['beforeRemove'],
'afterRender': bindingValue['afterRender'],
'templateEngine': ko.nativeTemplateEngine.instance
};
};
},
'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor));
},
'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor), allBindingsAccessor, viewModel, bindingContext);
}
};
ko.jsonExpressionRewriting.bindingRewriteValidators['foreach'] = false; // Can't rewrite control flow bindings
ko.virtualElements.allowedBindings['foreach'] = true;
// If you want to make a custom template engine,
//
// [1] Inherit from this class (like ko.nativeTemplateEngine does)
// [2] Override 'renderTemplateSource', supplying a function with this signature:
//
// function (templateSource, bindingContext, options) {
// // - templateSource.text() is the text of the template you should render
// // - bindingContext.$data is the data you should pass into the template
// // - you might also want to make bindingContext.$parent, bindingContext.$parents,
// // and bindingContext.$root available in the template too
// // - options gives you access to any other properties set on "data-bind: { template: options }"
// //
// // Return value: an array of DOM nodes
// }
//
// [3] Override 'createJavaScriptEvaluatorBlock', supplying a function with this signature:
//
// function (script) {
// // Return value: Whatever syntax means "Evaluate the JavaScript statement 'script' and output the result"
// // For example, the jquery.tmpl template engine converts 'someScript' to '${ someScript }'
// }
//
// This is only necessary if you want to allow data-bind attributes to reference arbitrary template variables.
// If you don't want to allow that, you can set the property 'allowTemplateRewriting' to false (like ko.nativeTemplateEngine does)
// and then you don't need to override 'createJavaScriptEvaluatorBlock'.
ko.templateEngine = function () { };
ko.templateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
throw new Error("Override renderTemplateSource");
};
ko.templateEngine.prototype['createJavaScriptEvaluatorBlock'] = function (script) {
throw new Error("Override createJavaScriptEvaluatorBlock");
};
ko.templateEngine.prototype['makeTemplateSource'] = function(template, templateDocument) {
// Named template
if (typeof template == "string") {
templateDocument = templateDocument || document;
var elem = templateDocument.getElementById(template);
if (!elem)
throw new Error("Cannot find template with ID " + template);
return new ko.templateSources.domElement(elem);
} else if ((template.nodeType == 1) || (template.nodeType == 8)) {
// Anonymous template
return new ko.templateSources.anonymousTemplate(template);
} else
throw new Error("Unknown template type: " + template);
};
ko.templateEngine.prototype['renderTemplate'] = function (template, bindingContext, options, templateDocument) {
var templateSource = this['makeTemplateSource'](template, templateDocument);
return this['renderTemplateSource'](templateSource, bindingContext, options);
};
ko.templateEngine.prototype['isTemplateRewritten'] = function (template, templateDocument) {
// Skip rewriting if requested
if (this['allowTemplateRewriting'] === false)
return true;
// Perf optimisation - see below
var templateIsInExternalDocument = templateDocument && templateDocument != document;
if (!templateIsInExternalDocument && this.knownRewrittenTemplates && this.knownRewrittenTemplates[template])
return true;
return this['makeTemplateSource'](template, templateDocument)['data']("isRewritten");
};
ko.templateEngine.prototype['rewriteTemplate'] = function (template, rewriterCallback, templateDocument) {
var templateSource = this['makeTemplateSource'](template, templateDocument);
var rewritten = rewriterCallback(templateSource['text']());
templateSource['text'](rewritten);
templateSource['data']("isRewritten", true);
// Perf optimisation - for named templates, track which ones have been rewritten so we can
// answer 'isTemplateRewritten' *without* having to use getElementById (which is slow on IE < 8)
//
// Note that we only cache the status for templates in the main document, because caching on a per-doc
// basis complicates the implementation excessively. In a future version of KO, we will likely remove
// this 'isRewritten' cache entirely anyway, because the benefit is extremely minor and only applies
// to rewritable templates, which are pretty much deprecated since KO 2.0.
var templateIsInExternalDocument = templateDocument && templateDocument != document;
if (!templateIsInExternalDocument && typeof template == "string") {
this.knownRewrittenTemplates = this.knownRewrittenTemplates || {};
this.knownRewrittenTemplates[template] = true;
}
};
ko.exportSymbol('templateEngine', ko.templateEngine);
ko.templateRewriting = (function () {
var memoizeDataBindingAttributeSyntaxRegex = /(<[a-z]+\d*(\s+(?!data-bind=)[a-z0-9\-]+(=(\"[^\"]*\"|\'[^\']*\'))?)*\s+)data-bind=(["'])([\s\S]*?)\5/gi;
var memoizeVirtualContainerBindingSyntaxRegex = /<!--\s*ko\b\s*([\s\S]*?)\s*-->/g;
function validateDataBindValuesForRewriting(keyValueArray) {
var allValidators = ko.jsonExpressionRewriting.bindingRewriteValidators;
for (var i = 0; i < keyValueArray.length; i++) {
var key = keyValueArray[i]['key'];
if (allValidators.hasOwnProperty(key)) {
var validator = allValidators[key];
if (typeof validator === "function") {
var possibleErrorMessage = validator(keyValueArray[i]['value']);
if (possibleErrorMessage)
throw new Error(possibleErrorMessage);
} else if (!validator) {
throw new Error("This template engine does not support the '" + key + "' binding within its templates");
}
}
}
}
function constructMemoizedTagReplacement(dataBindAttributeValue, tagToRetain, templateEngine) {
var dataBindKeyValueArray = ko.jsonExpressionRewriting.parseObjectLiteral(dataBindAttributeValue);
validateDataBindValuesForRewriting(dataBindKeyValueArray);
var rewrittenDataBindAttributeValue = ko.jsonExpressionRewriting.insertPropertyAccessorsIntoJson(dataBindKeyValueArray);
// For no obvious reason, Opera fails to evaluate rewrittenDataBindAttributeValue unless it's wrapped in an additional
// anonymous function, even though Opera's built-in debugger can evaluate it anyway. No other browser requires this
// extra indirection.
var applyBindingsToNextSiblingScript = "ko.templateRewriting.applyMemoizedBindingsToNextSibling(function() { \
return (function() { return { " + rewrittenDataBindAttributeValue + " } })() \
})";
return templateEngine['createJavaScriptEvaluatorBlock'](applyBindingsToNextSiblingScript) + tagToRetain;
}
return {
ensureTemplateIsRewritten: function (template, templateEngine, templateDocument) {
if (!templateEngine['isTemplateRewritten'](template, templateDocument))
templateEngine['rewriteTemplate'](template, function (htmlString) {
return ko.templateRewriting.memoizeBindingAttributeSyntax(htmlString, templateEngine);
}, templateDocument);
},
memoizeBindingAttributeSyntax: function (htmlString, templateEngine) {
return htmlString.replace(memoizeDataBindingAttributeSyntaxRegex, function () {
return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[6], /* tagToRetain: */ arguments[1], templateEngine);
}).replace(memoizeVirtualContainerBindingSyntaxRegex, function() {
return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[1], /* tagToRetain: */ "<!-- ko -->", templateEngine);
});
},
applyMemoizedBindingsToNextSibling: function (bindings) {
return ko.memoization.memoize(function (domNode, bindingContext) {
if (domNode.nextSibling)
ko.applyBindingsToNode(domNode.nextSibling, bindings, bindingContext);
});
}
}
})();
ko.exportSymbol('templateRewriting', ko.templateRewriting);
ko.exportSymbol('templateRewriting.applyMemoizedBindingsToNextSibling', ko.templateRewriting.applyMemoizedBindingsToNextSibling); // Exported only because it has to be referenced by string lookup from within rewritten template
(function() {
// A template source represents a read/write way of accessing a template. This is to eliminate the need for template loading/saving
// logic to be duplicated in every template engine (and means they can all work with anonymous templates, etc.)
//
// Two are provided by default:
// 1. ko.templateSources.domElement - reads/writes the text content of an arbitrary DOM element
// 2. ko.templateSources.anonymousElement - uses ko.utils.domData to read/write text *associated* with the DOM element, but
// without reading/writing the actual element text content, since it will be overwritten
// with the rendered template output.
// You can implement your own template source if you want to fetch/store templates somewhere other than in DOM elements.
// Template sources need to have the following functions:
// text() - returns the template text from your storage location
// text(value) - writes the supplied template text to your storage location
// data(key) - reads values stored using data(key, value) - see below
// data(key, value) - associates "value" with this template and the key "key". Is used to store information like "isRewritten".
//
// Optionally, template sources can also have the following functions:
// nodes() - returns a DOM element containing the nodes of this template, where available
// nodes(value) - writes the given DOM element to your storage location
// If a DOM element is available for a given template source, template engines are encouraged to use it in preference over text()
// for improved speed. However, all templateSources must supply text() even if they don't supply nodes().
//
// Once you've implemented a templateSource, make your template engine use it by subclassing whatever template engine you were
// using and overriding "makeTemplateSource" to return an instance of your custom template source.
ko.templateSources = {};
// ---- ko.templateSources.domElement -----
ko.templateSources.domElement = function(element) {
this.domElement = element;
}
ko.templateSources.domElement.prototype['text'] = function(/* valueToWrite */) {
var tagNameLower = ko.utils.tagNameLower(this.domElement),
elemContentsProperty = tagNameLower === "script" ? "text"
: tagNameLower === "textarea" ? "value"
: "innerHTML";
if (arguments.length == 0) {
return this.domElement[elemContentsProperty];
} else {
var valueToWrite = arguments[0];
if (elemContentsProperty === "innerHTML")
ko.utils.setHtml(this.domElement, valueToWrite);
else
this.domElement[elemContentsProperty] = valueToWrite;
}
};
ko.templateSources.domElement.prototype['data'] = function(key /*, valueToWrite */) {
if (arguments.length === 1) {
return ko.utils.domData.get(this.domElement, "templateSourceData_" + key);
} else {
ko.utils.domData.set(this.domElement, "templateSourceData_" + key, arguments[1]);
}
};
// ---- ko.templateSources.anonymousTemplate -----
// Anonymous templates are normally saved/retrieved as DOM nodes through "nodes".
// For compatibility, you can also read "text"; it will be serialized from the nodes on demand.
// Writing to "text" is still supported, but then the template data will not be available as DOM nodes.
var anonymousTemplatesDomDataKey = "__ko_anon_template__";
ko.templateSources.anonymousTemplate = function(element) {
this.domElement = element;
}
ko.templateSources.anonymousTemplate.prototype = new ko.templateSources.domElement();
ko.templateSources.anonymousTemplate.prototype['text'] = function(/* valueToWrite */) {
if (arguments.length == 0) {
var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
if (templateData.textData === undefined && templateData.containerData)
templateData.textData = templateData.containerData.innerHTML;
return templateData.textData;
} else {
var valueToWrite = arguments[0];
ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {textData: valueToWrite});
}
};
ko.templateSources.domElement.prototype['nodes'] = function(/* valueToWrite */) {
if (arguments.length == 0) {
var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
return templateData.containerData;
} else {
var valueToWrite = arguments[0];
ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {containerData: valueToWrite});
}
};
ko.exportSymbol('templateSources', ko.templateSources);
ko.exportSymbol('templateSources.domElement', ko.templateSources.domElement);
ko.exportSymbol('templateSources.anonymousTemplate', ko.templateSources.anonymousTemplate);
})();
(function () {
var _templateEngine;
ko.setTemplateEngine = function (templateEngine) {
if ((templateEngine != undefined) && !(templateEngine instanceof ko.templateEngine))
throw new Error("templateEngine must inherit from ko.templateEngine");
_templateEngine = templateEngine;
}
function invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, action) {
var node, nextInQueue = firstNode, firstOutOfRangeNode = ko.virtualElements.nextSibling(lastNode);
while (nextInQueue && ((node = nextInQueue) !== firstOutOfRangeNode)) {
nextInQueue = ko.virtualElements.nextSibling(node);
if (node.nodeType === 1 || node.nodeType === 8)
action(node);
}
}
function activateBindingsOnContinuousNodeArray(continuousNodeArray, bindingContext) {
// To be used on any nodes that have been rendered by a template and have been inserted into some parent element
// Walks through continuousNodeArray (which *must* be continuous, i.e., an uninterrupted sequence of sibling nodes, because
// the algorithm for walking them relies on this), and for each top-level item in the virtual-element sense,
// (1) Does a regular "applyBindings" to associate bindingContext with this node and to activate any non-memoized bindings
// (2) Unmemoizes any memos in the DOM subtree (e.g., to activate bindings that had been memoized during template rewriting)
if (continuousNodeArray.length) {
var firstNode = continuousNodeArray[0], lastNode = continuousNodeArray[continuousNodeArray.length - 1];
// Need to applyBindings *before* unmemoziation, because unmemoization might introduce extra nodes (that we don't want to re-bind)
// whereas a regular applyBindings won't introduce new memoized nodes
invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, function(node) {
ko.applyBindings(bindingContext, node);
});
invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, function(node) {
ko.memoization.unmemoizeDomNodeAndDescendants(node, [bindingContext]);
});
}
}
function getFirstNodeFromPossibleArray(nodeOrNodeArray) {
return nodeOrNodeArray.nodeType ? nodeOrNodeArray
: nodeOrNodeArray.length > 0 ? nodeOrNodeArray[0]
: null;
}
function executeTemplate(targetNodeOrNodeArray, renderMode, template, bindingContext, options) {
options = options || {};
var firstTargetNode = targetNodeOrNodeArray && getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
var templateDocument = firstTargetNode && firstTargetNode.ownerDocument;
var templateEngineToUse = (options['templateEngine'] || _templateEngine);
ko.templateRewriting.ensureTemplateIsRewritten(template, templateEngineToUse, templateDocument);
var renderedNodesArray = templateEngineToUse['renderTemplate'](template, bindingContext, options, templateDocument);
// Loosely check result is an array of DOM nodes
if ((typeof renderedNodesArray.length != "number") || (renderedNodesArray.length > 0 && typeof renderedNodesArray[0].nodeType != "number"))
throw new Error("Template engine must return an array of DOM nodes");
var haveAddedNodesToParent = false;
switch (renderMode) {
case "replaceChildren":
ko.virtualElements.setDomNodeChildren(targetNodeOrNodeArray, renderedNodesArray);
haveAddedNodesToParent = true;
break;
case "replaceNode":
ko.utils.replaceDomNodes(targetNodeOrNodeArray, renderedNodesArray);
haveAddedNodesToParent = true;
break;
case "ignoreTargetNode": break;
default:
throw new Error("Unknown renderMode: " + renderMode);
}
if (haveAddedNodesToParent) {
activateBindingsOnContinuousNodeArray(renderedNodesArray, bindingContext);
if (options['afterRender'])
options['afterRender'](renderedNodesArray, bindingContext['$data']);
}
return renderedNodesArray;
}
ko.renderTemplate = function (template, dataOrBindingContext, options, targetNodeOrNodeArray, renderMode) {
options = options || {};
if ((options['templateEngine'] || _templateEngine) == undefined)
throw new Error("Set a template engine before calling renderTemplate");
renderMode = renderMode || "replaceChildren";
if (targetNodeOrNodeArray) {
var firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
var whenToDispose = function () { return (!firstTargetNode) || !ko.utils.domNodeIsAttachedToDocument(firstTargetNode); }; // Passive disposal (on next evaluation)
var activelyDisposeWhenNodeIsRemoved = (firstTargetNode && renderMode == "replaceNode") ? firstTargetNode.parentNode : firstTargetNode;
return ko.dependentObservable( // So the DOM is automatically updated when any dependency changes
function () {
// Ensure we've got a proper binding context to work with
var bindingContext = (dataOrBindingContext && (dataOrBindingContext instanceof ko.bindingContext))
? dataOrBindingContext
: new ko.bindingContext(ko.utils.unwrapObservable(dataOrBindingContext));
// Support selecting template as a function of the data being rendered
var templateName = typeof(template) == 'function' ? template(bindingContext['$data']) : template;
var renderedNodesArray = executeTemplate(targetNodeOrNodeArray, renderMode, templateName, bindingContext, options);
if (renderMode == "replaceNode") {
targetNodeOrNodeArray = renderedNodesArray;
firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
}
},
null,
{ 'disposeWhen': whenToDispose, 'disposeWhenNodeIsRemoved': activelyDisposeWhenNodeIsRemoved }
);
} else {
// We don't yet have a DOM node to evaluate, so use a memo and render the template later when there is a DOM node
return ko.memoization.memoize(function (domNode) {
ko.renderTemplate(template, dataOrBindingContext, options, domNode, "replaceNode");
});
}
};
ko.renderTemplateForEach = function (template, arrayOrObservableArray, options, targetNode, parentBindingContext) {
// Since setDomNodeChildrenFromArrayMapping always calls executeTemplateForArrayItem and then
// activateBindingsCallback for added items, we can store the binding context in the former to use in the latter.
var arrayItemContext;
// This will be called by setDomNodeChildrenFromArrayMapping to get the nodes to add to targetNode
var executeTemplateForArrayItem = function (arrayValue, index) {
// Support selecting template as a function of the data being rendered
var templateName = typeof(template) == 'function' ? template(arrayValue) : template;
arrayItemContext = parentBindingContext['createChildContext'](ko.utils.unwrapObservable(arrayValue));
arrayItemContext['$index'] = index;
return executeTemplate(null, "ignoreTargetNode", templateName, arrayItemContext, options);
}
// This will be called whenever setDomNodeChildrenFromArrayMapping has added nodes to targetNode
var activateBindingsCallback = function(arrayValue, addedNodesArray, index) {
activateBindingsOnContinuousNodeArray(addedNodesArray, arrayItemContext);
if (options['afterRender'])
options['afterRender'](addedNodesArray, arrayValue);
};
return ko.dependentObservable(function () {
var unwrappedArray = ko.utils.unwrapObservable(arrayOrObservableArray) || [];
if (typeof unwrappedArray.length == "undefined") // Coerce single value into array
unwrappedArray = [unwrappedArray];
// Filter out any entries marked as destroyed
var filteredArray = ko.utils.arrayFilter(unwrappedArray, function(item) {
return options['includeDestroyed'] || item === undefined || item === null || !ko.utils.unwrapObservable(item['_destroy']);
});
ko.utils.setDomNodeChildrenFromArrayMapping(targetNode, filteredArray, executeTemplateForArrayItem, options, activateBindingsCallback);
}, null, { 'disposeWhenNodeIsRemoved': targetNode });
};
var templateSubscriptionDomDataKey = '__ko__templateSubscriptionDomDataKey__';
function disposeOldSubscriptionAndStoreNewOne(element, newSubscription) {
var oldSubscription = ko.utils.domData.get(element, templateSubscriptionDomDataKey);
if (oldSubscription && (typeof(oldSubscription.dispose) == 'function'))
oldSubscription.dispose();
ko.utils.domData.set(element, templateSubscriptionDomDataKey, newSubscription);
}
ko.bindingHandlers['template'] = {
'init': function(element, valueAccessor) {
// Support anonymous templates
var bindingValue = ko.utils.unwrapObservable(valueAccessor());
if ((typeof bindingValue != "string") && (!bindingValue['name']) && (element.nodeType == 1 || element.nodeType == 8)) {
// It's an anonymous template - store the element contents, then clear the element
var templateNodes = element.nodeType == 1 ? element.childNodes : ko.virtualElements.childNodes(element),
container = ko.utils.moveCleanedNodesToContainerElement(templateNodes); // This also removes the nodes from their current parent
new ko.templateSources.anonymousTemplate(element)['nodes'](container);
}
return { 'controlsDescendantBindings': true };
},
'update': function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var bindingValue = ko.utils.unwrapObservable(valueAccessor());
var templateName;
var shouldDisplay = true;
if (typeof bindingValue == "string") {
templateName = bindingValue;
} else {
templateName = bindingValue['name'];
// Support "if"/"ifnot" conditions
if ('if' in bindingValue)
shouldDisplay = shouldDisplay && ko.utils.unwrapObservable(bindingValue['if']);
if ('ifnot' in bindingValue)
shouldDisplay = shouldDisplay && !ko.utils.unwrapObservable(bindingValue['ifnot']);
}
var templateSubscription = null;
if ((typeof bindingValue === 'object') && ('foreach' in bindingValue)) { // Note: can't use 'in' operator on strings
// Render once for each data point (treating data set as empty if shouldDisplay==false)
var dataArray = (shouldDisplay && bindingValue['foreach']) || [];
templateSubscription = ko.renderTemplateForEach(templateName || element, dataArray, /* options: */ bindingValue, element, bindingContext);
} else {
if (shouldDisplay) {
// Render once for this single data point (or use the viewModel if no data was provided)
var innerBindingContext = (typeof bindingValue == 'object') && ('data' in bindingValue)
? bindingContext['createChildContext'](ko.utils.unwrapObservable(bindingValue['data'])) // Given an explitit 'data' value, we create a child binding context for it
: bindingContext; // Given no explicit 'data' value, we retain the same binding context
templateSubscription = ko.renderTemplate(templateName || element, innerBindingContext, /* options: */ bindingValue, element);
} else
ko.virtualElements.emptyNode(element);
}
// It only makes sense to have a single template subscription per element (otherwise which one should have its output displayed?)
disposeOldSubscriptionAndStoreNewOne(element, templateSubscription);
}
};
// Anonymous templates can't be rewritten. Give a nice error message if you try to do it.
ko.jsonExpressionRewriting.bindingRewriteValidators['template'] = function(bindingValue) {
var parsedBindingValue = ko.jsonExpressionRewriting.parseObjectLiteral(bindingValue);
if ((parsedBindingValue.length == 1) && parsedBindingValue[0]['unknown'])
return null; // It looks like a string literal, not an object literal, so treat it as a named template (which is allowed for rewriting)
if (ko.jsonExpressionRewriting.keyValueArrayContainsKey(parsedBindingValue, "name"))
return null; // Named templates can be rewritten, so return "no error"
return "This template engine does not support anonymous templates nested within its templates";
};
ko.virtualElements.allowedBindings['template'] = true;
})();
ko.exportSymbol('setTemplateEngine', ko.setTemplateEngine);
ko.exportSymbol('renderTemplate', ko.renderTemplate);
(function () {
// Simple calculation based on Levenshtein distance.
function calculateEditDistanceMatrix(oldArray, newArray, maxAllowedDistance) {
var distances = [];
for (var i = 0; i <= newArray.length; i++)
distances[i] = [];
// Top row - transform old array into empty array via deletions
for (var i = 0, j = Math.min(oldArray.length, maxAllowedDistance); i <= j; i++)
distances[0][i] = i;
// Left row - transform empty array into new array via additions
for (var i = 1, j = Math.min(newArray.length, maxAllowedDistance); i <= j; i++) {
distances[i][0] = i;
}
// Fill out the body of the array
var oldIndex, oldIndexMax = oldArray.length, newIndex, newIndexMax = newArray.length;
var distanceViaAddition, distanceViaDeletion;
for (oldIndex = 1; oldIndex <= oldIndexMax; oldIndex++) {
var newIndexMinForRow = Math.max(1, oldIndex - maxAllowedDistance);
var newIndexMaxForRow = Math.min(newIndexMax, oldIndex + maxAllowedDistance);
for (newIndex = newIndexMinForRow; newIndex <= newIndexMaxForRow; newIndex++) {
if (oldArray[oldIndex - 1] === newArray[newIndex - 1])
distances[newIndex][oldIndex] = distances[newIndex - 1][oldIndex - 1];
else {
var northDistance = distances[newIndex - 1][oldIndex] === undefined ? Number.MAX_VALUE : distances[newIndex - 1][oldIndex] + 1;
var westDistance = distances[newIndex][oldIndex - 1] === undefined ? Number.MAX_VALUE : distances[newIndex][oldIndex - 1] + 1;
distances[newIndex][oldIndex] = Math.min(northDistance, westDistance);
}
}
}
return distances;
}
function findEditScriptFromEditDistanceMatrix(editDistanceMatrix, oldArray, newArray) {
var oldIndex = oldArray.length;
var newIndex = newArray.length;
var editScript = [];
var maxDistance = editDistanceMatrix[newIndex][oldIndex];
if (maxDistance === undefined)
return null; // maxAllowedDistance must be too small
while ((oldIndex > 0) || (newIndex > 0)) {
var me = editDistanceMatrix[newIndex][oldIndex];
var distanceViaAdd = (newIndex > 0) ? editDistanceMatrix[newIndex - 1][oldIndex] : maxDistance + 1;
var distanceViaDelete = (oldIndex > 0) ? editDistanceMatrix[newIndex][oldIndex - 1] : maxDistance + 1;
var distanceViaRetain = (newIndex > 0) && (oldIndex > 0) ? editDistanceMatrix[newIndex - 1][oldIndex - 1] : maxDistance + 1;
if ((distanceViaAdd === undefined) || (distanceViaAdd < me - 1)) distanceViaAdd = maxDistance + 1;
if ((distanceViaDelete === undefined) || (distanceViaDelete < me - 1)) distanceViaDelete = maxDistance + 1;
if (distanceViaRetain < me - 1) distanceViaRetain = maxDistance + 1;
if ((distanceViaAdd <= distanceViaDelete) && (distanceViaAdd < distanceViaRetain)) {
editScript.push({ status: "added", value: newArray[newIndex - 1] });
newIndex--;
} else if ((distanceViaDelete < distanceViaAdd) && (distanceViaDelete < distanceViaRetain)) {
editScript.push({ status: "deleted", value: oldArray[oldIndex - 1] });
oldIndex--;
} else {
editScript.push({ status: "retained", value: oldArray[oldIndex - 1] });
newIndex--;
oldIndex--;
}
}
return editScript.reverse();
}
ko.utils.compareArrays = function (oldArray, newArray, maxEditsToConsider) {
if (maxEditsToConsider === undefined) {
return ko.utils.compareArrays(oldArray, newArray, 1) // First consider likely case where there is at most one edit (very fast)
|| ko.utils.compareArrays(oldArray, newArray, 10) // If that fails, account for a fair number of changes while still being fast
|| ko.utils.compareArrays(oldArray, newArray, Number.MAX_VALUE); // Ultimately give the right answer, even though it may take a long time
} else {
oldArray = oldArray || [];
newArray = newArray || [];
var editDistanceMatrix = calculateEditDistanceMatrix(oldArray, newArray, maxEditsToConsider);
return findEditScriptFromEditDistanceMatrix(editDistanceMatrix, oldArray, newArray);
}
};
})();
ko.exportSymbol('utils.compareArrays', ko.utils.compareArrays);
(function () {
// Objective:
// * Given an input array, a container DOM node, and a function from array elements to arrays of DOM nodes,
// map the array elements to arrays of DOM nodes, concatenate together all these arrays, and use them to populate the container DOM node
// * Next time we're given the same combination of things (with the array possibly having mutated), update the container DOM node
// so that its children is again the concatenation of the mappings of the array elements, but don't re-map any array elements that we
// previously mapped - retain those nodes, and just insert/delete other ones
// "callbackAfterAddingNodes" will be invoked after any "mapping"-generated nodes are inserted into the container node
// You can use this, for example, to activate bindings on those nodes.
function fixUpVirtualElements(contiguousNodeArray) {
// Ensures that contiguousNodeArray really *is* an array of contiguous siblings, even if some of the interior
// ones have changed since your array was first built (e.g., because your array contains virtual elements, and
// their virtual children changed when binding was applied to them).
// This is needed so that we can reliably remove or update the nodes corresponding to a given array item
if (contiguousNodeArray.length > 2) {
// Build up the actual new contiguous node set
var current = contiguousNodeArray[0], last = contiguousNodeArray[contiguousNodeArray.length - 1], newContiguousSet = [current];
while (current !== last) {
current = current.nextSibling;
if (!current) // Won't happen, except if the developer has manually removed some DOM elements (then we're in an undefined scenario)
return;
newContiguousSet.push(current);
}
// ... then mutate the input array to match this.
// (The following line replaces the contents of contiguousNodeArray with newContiguousSet)
Array.prototype.splice.apply(contiguousNodeArray, [0, contiguousNodeArray.length].concat(newContiguousSet));
}
}
function mapNodeAndRefreshWhenChanged(containerNode, mapping, valueToMap, callbackAfterAddingNodes, index) {
// Map this array value inside a dependentObservable so we re-map when any dependency changes
var mappedNodes = [];
var dependentObservable = ko.dependentObservable(function() {
var newMappedNodes = mapping(valueToMap, index) || [];
// On subsequent evaluations, just replace the previously-inserted DOM nodes
if (mappedNodes.length > 0) {
fixUpVirtualElements(mappedNodes);
ko.utils.replaceDomNodes(mappedNodes, newMappedNodes);
if (callbackAfterAddingNodes)
callbackAfterAddingNodes(valueToMap, newMappedNodes);
}
// Replace the contents of the mappedNodes array, thereby updating the record
// of which nodes would be deleted if valueToMap was itself later removed
mappedNodes.splice(0, mappedNodes.length);
ko.utils.arrayPushAll(mappedNodes, newMappedNodes);
}, null, { 'disposeWhenNodeIsRemoved': containerNode, 'disposeWhen': function() { return (mappedNodes.length == 0) || !ko.utils.domNodeIsAttachedToDocument(mappedNodes[0]) } });
return { mappedNodes : mappedNodes, dependentObservable : dependentObservable };
}
var lastMappingResultDomDataKey = "setDomNodeChildrenFromArrayMapping_lastMappingResult";
ko.utils.setDomNodeChildrenFromArrayMapping = function (domNode, array, mapping, options, callbackAfterAddingNodes) {
// Compare the provided array against the previous one
array = array || [];
options = options || {};
var isFirstExecution = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) === undefined;
var lastMappingResult = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) || [];
var lastArray = ko.utils.arrayMap(lastMappingResult, function (x) { return x.arrayEntry; });
var editScript = ko.utils.compareArrays(lastArray, array);
// Build the new mapping result
var newMappingResult = [];
var lastMappingResultIndex = 0;
var nodesToDelete = [];
var newMappingResultIndex = 0;
var nodesAdded = [];
var insertAfterNode = null;
for (var i = 0, j = editScript.length; i < j; i++) {
switch (editScript[i].status) {
case "retained":
// Just keep the information - don't touch the nodes
var dataToRetain = lastMappingResult[lastMappingResultIndex];
dataToRetain.indexObservable(newMappingResultIndex);
newMappingResultIndex = newMappingResult.push(dataToRetain);
if (dataToRetain.domNodes.length > 0)
insertAfterNode = dataToRetain.domNodes[dataToRetain.domNodes.length - 1];
lastMappingResultIndex++;
break;
case "deleted":
// Stop tracking changes to the mapping for these nodes
lastMappingResult[lastMappingResultIndex].dependentObservable.dispose();
// Queue these nodes for later removal
fixUpVirtualElements(lastMappingResult[lastMappingResultIndex].domNodes);
ko.utils.arrayForEach(lastMappingResult[lastMappingResultIndex].domNodes, function (node) {
nodesToDelete.push({
element: node,
index: i,
value: editScript[i].value
});
insertAfterNode = node;
});
lastMappingResultIndex++;
break;
case "added":
var valueToMap = editScript[i].value;
var indexObservable = ko.observable(newMappingResultIndex);
var mapData = mapNodeAndRefreshWhenChanged(domNode, mapping, valueToMap, callbackAfterAddingNodes, indexObservable);
var mappedNodes = mapData.mappedNodes;
// On the first evaluation, insert the nodes at the current insertion point
newMappingResultIndex = newMappingResult.push({
arrayEntry: editScript[i].value,
domNodes: mappedNodes,
dependentObservable: mapData.dependentObservable,
indexObservable: indexObservable
});
for (var nodeIndex = 0, nodeIndexMax = mappedNodes.length; nodeIndex < nodeIndexMax; nodeIndex++) {
var node = mappedNodes[nodeIndex];
nodesAdded.push({
element: node,
index: i,
value: editScript[i].value
});
if (insertAfterNode == null) {
// Insert "node" (the newly-created node) as domNode's first child
ko.virtualElements.prepend(domNode, node);
} else {
// Insert "node" into "domNode" immediately after "insertAfterNode"
ko.virtualElements.insertAfter(domNode, node, insertAfterNode);
}
insertAfterNode = node;
}
if (callbackAfterAddingNodes)
callbackAfterAddingNodes(valueToMap, mappedNodes, indexObservable);
break;
}
}
ko.utils.arrayForEach(nodesToDelete, function (node) { ko.cleanNode(node.element) });
var invokedBeforeRemoveCallback = false;
if (!isFirstExecution) {
if (options['afterAdd']) {
for (var i = 0; i < nodesAdded.length; i++)
options['afterAdd'](nodesAdded[i].element, nodesAdded[i].index, nodesAdded[i].value);
}
if (options['beforeRemove']) {
for (var i = 0; i < nodesToDelete.length; i++)
options['beforeRemove'](nodesToDelete[i].element, nodesToDelete[i].index, nodesToDelete[i].value);
invokedBeforeRemoveCallback = true;
}
}
if (!invokedBeforeRemoveCallback && nodesToDelete.length) {
for (var i = 0; i < nodesToDelete.length; i++) {
var element = nodesToDelete[i].element;
if (element.parentNode)
element.parentNode.removeChild(element);
}
}
// Store a copy of the array items we just considered so we can difference it next time
ko.utils.domData.set(domNode, lastMappingResultDomDataKey, newMappingResult);
}
})();
ko.exportSymbol('utils.setDomNodeChildrenFromArrayMapping', ko.utils.setDomNodeChildrenFromArrayMapping);
ko.nativeTemplateEngine = function () {
this['allowTemplateRewriting'] = false;
}
ko.nativeTemplateEngine.prototype = new ko.templateEngine();
ko.nativeTemplateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
var useNodesIfAvailable = !(ko.utils.ieVersion < 9), // IE<9 cloneNode doesn't work properly
templateNodesFunc = useNodesIfAvailable ? templateSource['nodes'] : null,
templateNodes = templateNodesFunc ? templateSource['nodes']() : null;
if (templateNodes) {
return ko.utils.makeArray(templateNodes.cloneNode(true).childNodes);
} else {
var templateText = templateSource['text']();
return ko.utils.parseHtmlFragment(templateText);
}
};
ko.nativeTemplateEngine.instance = new ko.nativeTemplateEngine();
ko.setTemplateEngine(ko.nativeTemplateEngine.instance);
ko.exportSymbol('nativeTemplateEngine', ko.nativeTemplateEngine);
(function() {
ko.jqueryTmplTemplateEngine = function () {
// Detect which version of jquery-tmpl you're using. Unfortunately jquery-tmpl
// doesn't expose a version number, so we have to infer it.
// Note that as of Knockout 1.3, we only support jQuery.tmpl 1.0.0pre and later,
// which KO internally refers to as version "2", so older versions are no longer detected.
var jQueryTmplVersion = this.jQueryTmplVersion = (function() {
if ((typeof(jQuery) == "undefined") || !(jQuery['tmpl']))
return 0;
// Since it exposes no official version number, we use our own numbering system. To be updated as jquery-tmpl evolves.
try {
if (jQuery['tmpl']['tag']['tmpl']['open'].toString().indexOf('__') >= 0) {
// Since 1.0.0pre, custom tags should append markup to an array called "__"
return 2; // Final version of jquery.tmpl
}
} catch(ex) { /* Apparently not the version we were looking for */ }
return 1; // Any older version that we don't support
})();
function ensureHasReferencedJQueryTemplates() {
if (jQueryTmplVersion < 2)
throw new Error("Your version of jQuery.tmpl is too old. Please upgrade to jQuery.tmpl 1.0.0pre or later.");
}
function executeTemplate(compiledTemplate, data, jQueryTemplateOptions) {
return jQuery['tmpl'](compiledTemplate, data, jQueryTemplateOptions);
}
this['renderTemplateSource'] = function(templateSource, bindingContext, options) {
options = options || {};
ensureHasReferencedJQueryTemplates();
// Ensure we have stored a precompiled version of this template (don't want to reparse on every render)
var precompiled = templateSource['data']('precompiled');
if (!precompiled) {
var templateText = templateSource['text']() || "";
// Wrap in "with($whatever.koBindingContext) { ... }"
templateText = "{{ko_with $item.koBindingContext}}" + templateText + "{{/ko_with}}";
precompiled = jQuery['template'](null, templateText);
templateSource['data']('precompiled', precompiled);
}
var data = [bindingContext['$data']]; // Prewrap the data in an array to stop jquery.tmpl from trying to unwrap any arrays
var jQueryTemplateOptions = jQuery['extend']({ 'koBindingContext': bindingContext }, options['templateOptions']);
var resultNodes = executeTemplate(precompiled, data, jQueryTemplateOptions);
resultNodes['appendTo'](document.createElement("div")); // Using "appendTo" forces jQuery/jQuery.tmpl to perform necessary cleanup work
jQuery['fragments'] = {}; // Clear jQuery's fragment cache to avoid a memory leak after a large number of template renders
return resultNodes;
};
this['createJavaScriptEvaluatorBlock'] = function(script) {
return "{{ko_code ((function() { return " + script + " })()) }}";
};
this['addTemplate'] = function(templateName, templateMarkup) {
document.write("<script type='text/html' id='" + templateName + "'>" + templateMarkup + "</script>");
};
if (jQueryTmplVersion > 0) {
jQuery['tmpl']['tag']['ko_code'] = {
open: "__.push($1 || '');"
};
jQuery['tmpl']['tag']['ko_with'] = {
open: "with($1) {",
close: "} "
};
}
};
ko.jqueryTmplTemplateEngine.prototype = new ko.templateEngine();
// Use this one by default *only if jquery.tmpl is referenced*
var jqueryTmplTemplateEngineInstance = new ko.jqueryTmplTemplateEngine();
if (jqueryTmplTemplateEngineInstance.jQueryTmplVersion > 0)
ko.setTemplateEngine(jqueryTmplTemplateEngineInstance);
ko.exportSymbol('jqueryTmplTemplateEngine', ko.jqueryTmplTemplateEngine);
})();
});
})(window,document,navigator);
// SIG // Begin signature block
// SIG // MIIaaAYJKoZIhvcNAQcCoIIaWTCCGlUCAQExCzAJBgUr
// SIG // DgMCGgUAMGcGCisGAQQBgjcCAQSgWTBXMDIGCisGAQQB
// SIG // gjcCAR4wJAIBAQQQEODJBs441BGiowAQS9NQkAIBAAIB
// SIG // AAIBAAIBAAIBADAhMAkGBSsOAwIaBQAEFCf7JfvOGxZd
// SIG // 7cJaqkI2qdy0NFAnoIIVLzCCBJkwggOBoAMCAQICEzMA
// SIG // AACdHo0nrrjz2DgAAQAAAJ0wDQYJKoZIhvcNAQEFBQAw
// SIG // eTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hpbmd0
// SIG // b24xEDAOBgNVBAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1p
// SIG // Y3Jvc29mdCBDb3Jwb3JhdGlvbjEjMCEGA1UEAxMaTWlj
// SIG // cm9zb2Z0IENvZGUgU2lnbmluZyBQQ0EwHhcNMTIwOTA0
// SIG // MjE0MjA5WhcNMTMwMzA0MjE0MjA5WjCBgzELMAkGA1UE
// SIG // BhMCVVMxEzARBgNVBAgTCldhc2hpbmd0b24xEDAOBgNV
// SIG // BAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1pY3Jvc29mdCBD
// SIG // b3Jwb3JhdGlvbjENMAsGA1UECxMETU9QUjEeMBwGA1UE
// SIG // AxMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMIIBIjANBgkq
// SIG // hkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuqRJbBD7Ipxl
// SIG // ohaYO8thYvp0Ka2NBhnScVgZil5XDWlibjagTv0ieeAd
// SIG // xxphjvr8oxElFsjAWCwxioiuMh6I238+dFf3haQ2U8pB
// SIG // 72m4aZ5tVutu5LImTXPRZHG0H9ZhhIgAIe9oWINbSY+0
// SIG // 39M11svZMJ9T/HprmoQrtyFndNT2eLZhh5iUfCrPZ+kZ
// SIG // vtm6Y+08Tj59Auvzf6/PD7eBfvT76PeRSLuPPYzIB5Mc
// SIG // 87115PxjICmfOfNBVDgeVGRAtISqN67zAIziDfqhsg8i
// SIG // taeprtYXuTDwAiMgEPprWQ/grZ+eYIGTA0wNm2IZs7uW
// SIG // vJFapniGdptszUzsErU4RwIDAQABo4IBDTCCAQkwEwYD
// SIG // VR0lBAwwCgYIKwYBBQUHAwMwHQYDVR0OBBYEFN5R3Bvy
// SIG // HkoFPxIcwbzDs2UskQWYMB8GA1UdIwQYMBaAFMsR6MrS
// SIG // tBZYAck3LjMWFrlMmgofMFYGA1UdHwRPME0wS6BJoEeG
// SIG // RWh0dHA6Ly9jcmwubWljcm9zb2Z0LmNvbS9wa2kvY3Js
// SIG // L3Byb2R1Y3RzL01pY0NvZFNpZ1BDQV8wOC0zMS0yMDEw
// SIG // LmNybDBaBggrBgEFBQcBAQROMEwwSgYIKwYBBQUHMAKG
// SIG // Pmh0dHA6Ly93d3cubWljcm9zb2Z0LmNvbS9wa2kvY2Vy
// SIG // dHMvTWljQ29kU2lnUENBXzA4LTMxLTIwMTAuY3J0MA0G
// SIG // CSqGSIb3DQEBBQUAA4IBAQAqpPfuwMMmeoNiGnicW8X9
// SIG // 7BXEp3gT0RdTKAsMAEI/OA+J3GQZhDV/SLnP63qJoc1P
// SIG // qeC77UcQ/hfah4kQ0UwVoPAR/9qWz2TPgf0zp8N4k+R8
// SIG // 1W2HcdYcYeLMTmS3cz/5eyc09lI/R0PADoFwU8GWAaJL
// SIG // u78qA3d7bvvQRooXKDGlBeMWirjxSmkVXTP533+UPEdF
// SIG // Ha7Ki8f3iB7q/pEMn08HCe0mkm6zlBkB+F+B567aiY9/
// SIG // Wl6EX7W+fEblR6/+WCuRf4fcRh9RlczDYqG1x1/ryWlc
// SIG // cZGpjVYgLDpOk/2bBo+tivhofju6eUKTOUn10F7scI1C
// SIG // dcWCVZAbtVVhMIIEwzCCA6ugAwIBAgITMwAAACs5MkjB
// SIG // sslI8wAAAAAAKzANBgkqhkiG9w0BAQUFADB3MQswCQYD
// SIG // VQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4G
// SIG // A1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0
// SIG // IENvcnBvcmF0aW9uMSEwHwYDVQQDExhNaWNyb3NvZnQg
// SIG // VGltZS1TdGFtcCBQQ0EwHhcNMTIwOTA0MjExMjM0WhcN
// SIG // MTMxMjA0MjExMjM0WjCBszELMAkGA1UEBhMCVVMxEzAR
// SIG // BgNVBAgTCldhc2hpbmd0b24xEDAOBgNVBAcTB1JlZG1v
// SIG // bmQxHjAcBgNVBAoTFU1pY3Jvc29mdCBDb3Jwb3JhdGlv
// SIG // bjENMAsGA1UECxMETU9QUjEnMCUGA1UECxMebkNpcGhl
// SIG // ciBEU0UgRVNOOkMwRjQtMzA4Ni1ERUY4MSUwIwYDVQQD
// SIG // ExxNaWNyb3NvZnQgVGltZS1TdGFtcCBTZXJ2aWNlMIIB
// SIG // IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAprYw
// SIG // DgNlrlBahmuFn0ihHsnA7l5JB4XgcJZ8vrlfYl8GJtOL
// SIG // ObsYIqUukq3YS4g6Gq+bg67IXjmMwjJ7FnjtNzg68WL7
// SIG // aIICaOzru0CKsf6hLDZiYHA5YGIO+8YYOG+wktZADYCm
// SIG // DXiLNmuGiiYXGP+w6026uykT5lxIjnBGNib+NDWrNOH3
// SIG // 2thc6pl9MbdNH1frfNaVDWYMHg4yFz4s1YChzuv3mJEC
// SIG // 3MFf/TiA+Dl/XWTKN1w7UVtdhV/OHhz7NL5f5ShVcFSc
// SIG // uOx8AFVGWyiYKFZM4fG6CRmWgUgqMMj3MyBs52nDs9TD
// SIG // Ts8wHjfUmFLUqSNFsq5cQUlPtGJokwIDAQABo4IBCTCC
// SIG // AQUwHQYDVR0OBBYEFKUYM1M/lWChQxbvjsav0iu6nljQ
// SIG // MB8GA1UdIwQYMBaAFCM0+NlSRnAK7UD7dvuzK7DDNbMP
// SIG // MFQGA1UdHwRNMEswSaBHoEWGQ2h0dHA6Ly9jcmwubWlj
// SIG // cm9zb2Z0LmNvbS9wa2kvY3JsL3Byb2R1Y3RzL01pY3Jv
// SIG // c29mdFRpbWVTdGFtcFBDQS5jcmwwWAYIKwYBBQUHAQEE
// SIG // TDBKMEgGCCsGAQUFBzAChjxodHRwOi8vd3d3Lm1pY3Jv
// SIG // c29mdC5jb20vcGtpL2NlcnRzL01pY3Jvc29mdFRpbWVT
// SIG // dGFtcFBDQS5jcnQwEwYDVR0lBAwwCgYIKwYBBQUHAwgw
// SIG // DQYJKoZIhvcNAQEFBQADggEBAH7MsHvlL77nVrXPc9uq
// SIG // UtEWOca0zfrX/h5ltedI85tGiAVmaiaGXv6HWNzGY444
// SIG // gPQIRnwrc7EOv0Gqy8eqlKQ38GQ54cXV+c4HzqvkJfBp
// SIG // rtRG4v5mMjzXl8UyIfruGiWgXgxCLBEzOoKD/e0ds77O
// SIG // kaSRJXG5q3Kwnq/kzwBiiXCpuEpQjO4vImSlqOZNa5Us
// SIG // HHnsp6Mx2pBgkKRu/pMCDT8sJA3GaiaBUYNKELt1Y0Sq
// SIG // aQjGA+vizwvtVjrs73KnCgz0ANMiuK8icrPnxJwLKKCA
// SIG // yuPh1zlmMOdGFxjn+oL6WQt6vKgN/hz/A4tjsk0SAiNP
// SIG // LbOFhDvioUfozxUwggW8MIIDpKADAgECAgphMyYaAAAA
// SIG // AAAxMA0GCSqGSIb3DQEBBQUAMF8xEzARBgoJkiaJk/Is
// SIG // ZAEZFgNjb20xGTAXBgoJkiaJk/IsZAEZFgltaWNyb3Nv
// SIG // ZnQxLTArBgNVBAMTJE1pY3Jvc29mdCBSb290IENlcnRp
// SIG // ZmljYXRlIEF1dGhvcml0eTAeFw0xMDA4MzEyMjE5MzJa
// SIG // Fw0yMDA4MzEyMjI5MzJaMHkxCzAJBgNVBAYTAlVTMRMw
// SIG // EQYDVQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQHEwdSZWRt
// SIG // b25kMR4wHAYDVQQKExVNaWNyb3NvZnQgQ29ycG9yYXRp
// SIG // b24xIzAhBgNVBAMTGk1pY3Jvc29mdCBDb2RlIFNpZ25p
// SIG // bmcgUENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB
// SIG // CgKCAQEAsnJZXBkwZL8dmmAgIEKZdlNsPhvWb8zL8epr
// SIG // /pcWEODfOnSDGrcvoDLs/97CQk4j1XIA2zVXConKriBJ
// SIG // 9PBorE1LjaW9eUtxm0cH2v0l3511iM+qc0R/14Hb873y
// SIG // NqTJXEXcr6094CholxqnpXJzVvEXlOT9NZRyoNZ2Xx53
// SIG // RYOFOBbQc1sFumdSjaWyaS/aGQv+knQp4nYvVN0UMFn4
// SIG // 0o1i/cvJX0YxULknE+RAMM9yKRAoIsc3Tj2gMj2QzaE4
// SIG // BoVcTlaCKCoFMrdL109j59ItYvFFPeesCAD2RqGe0VuM
// SIG // JlPoeqpK8kbPNzw4nrR3XKUXno3LEY9WPMGsCV8D0wID
// SIG // AQABo4IBXjCCAVowDwYDVR0TAQH/BAUwAwEB/zAdBgNV
// SIG // HQ4EFgQUyxHoytK0FlgByTcuMxYWuUyaCh8wCwYDVR0P
// SIG // BAQDAgGGMBIGCSsGAQQBgjcVAQQFAgMBAAEwIwYJKwYB
// SIG // BAGCNxUCBBYEFP3RMU7TJoqV4ZhgO6gxb6Y8vNgtMBkG
// SIG // CSsGAQQBgjcUAgQMHgoAUwB1AGIAQwBBMB8GA1UdIwQY
// SIG // MBaAFA6sgmBAVieX5SUT/CrhClOVWeSkMFAGA1UdHwRJ
// SIG // MEcwRaBDoEGGP2h0dHA6Ly9jcmwubWljcm9zb2Z0LmNv
// SIG // bS9wa2kvY3JsL3Byb2R1Y3RzL21pY3Jvc29mdHJvb3Rj
// SIG // ZXJ0LmNybDBUBggrBgEFBQcBAQRIMEYwRAYIKwYBBQUH
// SIG // MAKGOGh0dHA6Ly93d3cubWljcm9zb2Z0LmNvbS9wa2kv
// SIG // Y2VydHMvTWljcm9zb2Z0Um9vdENlcnQuY3J0MA0GCSqG
// SIG // SIb3DQEBBQUAA4ICAQBZOT5/Jkav629AsTK1ausOL26o
// SIG // SffrX3XtTDst10OtC/7L6S0xoyPMfFCYgCFdrD0vTLqi
// SIG // qFac43C7uLT4ebVJcvc+6kF/yuEMF2nLpZwgLfoLUMRW
// SIG // zS3jStK8cOeoDaIDpVbguIpLV/KVQpzx8+/u44YfNDy4
// SIG // VprwUyOFKqSCHJPilAcd8uJO+IyhyugTpZFOyBvSj3KV
// SIG // KnFtmxr4HPBT1mfMIv9cHc2ijL0nsnljVkSiUc356aNY
// SIG // Vt2bAkVEL1/02q7UgjJu/KSVE+Traeepoiy+yCsQDmWO
// SIG // mdv1ovoSJgllOJTxeh9Ku9HhVujQeJYYXMk1Fl/dkx1J
// SIG // ji2+rTREHO4QFRoAXd01WyHOmMcJ7oUOjE9tDhNOPXwp
// SIG // SJxy0fNsysHscKNXkld9lI2gG0gDWvfPo2cKdKU27S0v
// SIG // F8jmcjcS9G+xPGeC+VKyjTMWZR4Oit0Q3mT0b85G1NMX
// SIG // 6XnEBLTT+yzfH4qerAr7EydAreT54al/RrsHYEdlYEBO
// SIG // sELsTu2zdnnYCjQJbRyAMR/iDlTd5aH75UcQrWSY/1AW
// SIG // Lny/BSF64pVBJ2nDk4+VyY3YmyGuDVyc8KKuhmiDDGot
// SIG // u3ZrAB2WrfIWe/YWgyS5iM9qqEcxL5rc43E91wB+YkfR
// SIG // zojJuBj6DnKNwaM9rwJAav9pm5biEKgQtDdQCNbDPTCC
// SIG // BgcwggPvoAMCAQICCmEWaDQAAAAAABwwDQYJKoZIhvcN
// SIG // AQEFBQAwXzETMBEGCgmSJomT8ixkARkWA2NvbTEZMBcG
// SIG // CgmSJomT8ixkARkWCW1pY3Jvc29mdDEtMCsGA1UEAxMk
// SIG // TWljcm9zb2Z0IFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9y
// SIG // aXR5MB4XDTA3MDQwMzEyNTMwOVoXDTIxMDQwMzEzMDMw
// SIG // OVowdzELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hp
// SIG // bmd0b24xEDAOBgNVBAcTB1JlZG1vbmQxHjAcBgNVBAoT
// SIG // FU1pY3Jvc29mdCBDb3Jwb3JhdGlvbjEhMB8GA1UEAxMY
// SIG // TWljcm9zb2Z0IFRpbWUtU3RhbXAgUENBMIIBIjANBgkq
// SIG // hkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn6Fssd/bSJIq
// SIG // fGsuGeG94uPFmVEjUK3O3RhOJA/u0afRTK10MCAR6wfV
// SIG // VJUVSZQbQpKumFwwJtoAa+h7veyJBw/3DgSY8InMH8sz
// SIG // JIed8vRnHCz8e+eIHernTqOhwSNTyo36Rc8J0F6v0LBC
// SIG // BKL5pmyTZ9co3EZTsIbQ5ShGLieshk9VUgzkAyz7apCQ
// SIG // MG6H81kwnfp+1pez6CGXfvjSE/MIt1NtUrRFkJ9IAEpH
// SIG // ZhEnKWaol+TTBoFKovmEpxFHFAmCn4TtVXj+AZodUAiF
// SIG // ABAwRu233iNGu8QtVJ+vHnhBMXfMm987g5OhYQK1HQ2x
// SIG // /PebsgHOIktU//kFw8IgCwIDAQABo4IBqzCCAacwDwYD
// SIG // VR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUIzT42VJGcArt
// SIG // QPt2+7MrsMM1sw8wCwYDVR0PBAQDAgGGMBAGCSsGAQQB
// SIG // gjcVAQQDAgEAMIGYBgNVHSMEgZAwgY2AFA6sgmBAVieX
// SIG // 5SUT/CrhClOVWeSkoWOkYTBfMRMwEQYKCZImiZPyLGQB
// SIG // GRYDY29tMRkwFwYKCZImiZPyLGQBGRYJbWljcm9zb2Z0
// SIG // MS0wKwYDVQQDEyRNaWNyb3NvZnQgUm9vdCBDZXJ0aWZp
// SIG // Y2F0ZSBBdXRob3JpdHmCEHmtFqFKoKWtTHNY9AcTLmUw
// SIG // UAYDVR0fBEkwRzBFoEOgQYY/aHR0cDovL2NybC5taWNy
// SIG // b3NvZnQuY29tL3BraS9jcmwvcHJvZHVjdHMvbWljcm9z
// SIG // b2Z0cm9vdGNlcnQuY3JsMFQGCCsGAQUFBwEBBEgwRjBE
// SIG // BggrBgEFBQcwAoY4aHR0cDovL3d3dy5taWNyb3NvZnQu
// SIG // Y29tL3BraS9jZXJ0cy9NaWNyb3NvZnRSb290Q2VydC5j
// SIG // cnQwEwYDVR0lBAwwCgYIKwYBBQUHAwgwDQYJKoZIhvcN
// SIG // AQEFBQADggIBABCXisNcA0Q23em0rXfbznlRTQGxLnRx
// SIG // W20ME6vOvnuPuC7UEqKMbWK4VwLLTiATUJndekDiV7uv
// SIG // WJoc4R0Bhqy7ePKL0Ow7Ae7ivo8KBciNSOLwUxXdT6uS
// SIG // 5OeNatWAweaU8gYvhQPpkSokInD79vzkeJkuDfcH4nC8
// SIG // GE6djmsKcpW4oTmcZy3FUQ7qYlw/FpiLID/iBxoy+cwx
// SIG // SnYxPStyC8jqcD3/hQoT38IKYY7w17gX606Lf8U1K16j
// SIG // v+u8fQtCe9RTciHuMMq7eGVcWwEXChQO0toUmPU8uWZY
// SIG // sy0v5/mFhsxRVuidcJRsrDlM1PZ5v6oYemIp76KbKTQG
// SIG // dxpiyT0ebR+C8AvHLLvPQ7Pl+ex9teOkqHQ1uE7FcSMS
// SIG // JnYLPFKMcVpGQxS8s7OwTWfIn0L/gHkhgJ4VMGboQhJe
// SIG // GsieIiHQQ+kr6bv0SMws1NgygEwmKkgkX1rqVu+m3pmd
// SIG // yjpvvYEndAYR7nYhv5uCwSdUtrFqPYmhdmG0bqETpr+q
// SIG // R/ASb/2KMmyy/t9RyIwjyWa9nR2HEmQCPS2vWY+45CHl
// SIG // tbDKY7R4VAXUQS5QrJSwpXirs6CWdRrZkocTdSIvMqgI
// SIG // bqBbjCW/oO+EyiHW6x5PyZruSeD3AWVviQt9yGnI5m7q
// SIG // p5fOMSn/DsVbXNhNG6HY+i+ePy5VFmvJE6P9MYIEpTCC
// SIG // BKECAQEwgZAweTELMAkGA1UEBhMCVVMxEzARBgNVBAgT
// SIG // Cldhc2hpbmd0b24xEDAOBgNVBAcTB1JlZG1vbmQxHjAc
// SIG // BgNVBAoTFU1pY3Jvc29mdCBDb3Jwb3JhdGlvbjEjMCEG
// SIG // A1UEAxMaTWljcm9zb2Z0IENvZGUgU2lnbmluZyBQQ0EC
// SIG // EzMAAACdHo0nrrjz2DgAAQAAAJ0wCQYFKw4DAhoFAKCB
// SIG // vjAZBgkqhkiG9w0BCQMxDAYKKwYBBAGCNwIBBDAcBgor
// SIG // BgEEAYI3AgELMQ4wDAYKKwYBBAGCNwIBFTAjBgkqhkiG
// SIG // 9w0BCQQxFgQUy6LXa4ZLKzaE7mQA7yQeUZ9lpOowXgYK
// SIG // KwYBBAGCNwIBDDFQME6gJoAkAE0AaQBjAHIAbwBzAG8A
// SIG // ZgB0ACAATABlAGEAcgBuAGkAbgBnoSSAImh0dHA6Ly93
// SIG // d3cubWljcm9zb2Z0LmNvbS9sZWFybmluZyAwDQYJKoZI
// SIG // hvcNAQEBBQAEggEALkchFtYfX/57gjTU6g4FqlPQcHJ0
// SIG // hUMeJIoXztqrAyjjmBJLpmGJ0Aabiz8jyuVVf+KNqzQx
// SIG // XXSCSUJLUVBSa38NLBD/Ytf6WLJNUawLXpl2kZLjqRdE
// SIG // eKk6vgoAnhStIBeakhrC21LQXDtFHtqQRFv4Ma5EEey+
// SIG // u7W5iKutKGwagXpWsk6JulTbWcsMFZfvLbUTf3K4bRyQ
// SIG // +4bNsIlt8p9HZjOOa9GKqsle20wFpbQAqoCvRva3m3JX
// SIG // kRdIGBCTxRaiUox9u1ldiWSCDyRUOwaw0jQK0e80cKD3
// SIG // l158nHR8nUOr4IKMqNmqiEtWk4bYvHoTPTkFmoPt8gyU
// SIG // EbIZ/KGCAigwggIkBgkqhkiG9w0BCQYxggIVMIICEQIB
// SIG // ATCBjjB3MQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2Fz
// SIG // aGluZ3RvbjEQMA4GA1UEBxMHUmVkbW9uZDEeMBwGA1UE
// SIG // ChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMSEwHwYDVQQD
// SIG // ExhNaWNyb3NvZnQgVGltZS1TdGFtcCBQQ0ECEzMAAAAr
// SIG // OTJIwbLJSPMAAAAAACswCQYFKw4DAhoFAKBdMBgGCSqG
// SIG // SIb3DQEJAzELBgkqhkiG9w0BBwEwHAYJKoZIhvcNAQkF
// SIG // MQ8XDTEzMDExOTAwMzE0N1owIwYJKoZIhvcNAQkEMRYE
// SIG // FIyMwMMbs3IgHUniuJzNnozfqV8tMA0GCSqGSIb3DQEB
// SIG // BQUABIIBAHxp2GAmvP98YbUlT9ouL/2Z7VX8QOuWsrKW
// SIG // jXJxYELDPsDIXlXnNihORgnqzU6xvbW7hGKAv2gzMfk6
// SIG // dldtYLr1VA8/5EVSGFFHx6iTSPD6YnhHs5brMtPbe75j
// SIG // Oawvfbx3zZV45ZV6/34kvghbcG2T/N7I+nYL+lKiHwp2
// SIG // Ty9w740xEs4nlnHVHvGvtZgoNo5PIqZJc47/qOqzW2gK
// SIG // jOTBabXXx8QagZijQJVZ1dWWAUMBaaTDg3OWRL1S3on/
// SIG // zUbFPVwJ3P4Os0TaaLMOzucqtVoNbUCfuhT7nau1Q7E4
// SIG // BegCwQHntoyFdIHkBpeXALmdNxJRNT7Xkuda6MnDv6Y=
// SIG // End signature block
| {
"content_hash": "62a9aa444978a8e327d5458b54b38445",
"timestamp": "",
"source": "github",
"line_count": 3651,
"max_line_length": 278,
"avg_line_length": 49.81566694056423,
"alnum_prop": 0.6280838148858844,
"repo_name": "MicrosoftLearning/20487-DevelopingWindowsAzureAndWebServices",
"id": "02053237030de6ea9c1becd2d04b7d1a1e581c6a",
"size": "181877",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Allfiles/20487C/Mod07/DemoFiles/ServiceBusRelay/begin/ServiceBusRelay/ServiceBusRelay.WebClient/Scripts/knockout-2.1.0.debug.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "32247"
},
{
"name": "C#",
"bytes": "8538296"
},
{
"name": "CSS",
"bytes": "629086"
},
{
"name": "HTML",
"bytes": "271909"
},
{
"name": "JavaScript",
"bytes": "2979953"
},
{
"name": "PowerShell",
"bytes": "78421"
},
{
"name": "Smalltalk",
"bytes": "24"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="{{ site.description }}">
<meta property="og:site_name" content="{{ site.title }}" />
<meta property="og:type" content="website" />
<meta property="og:url" content="{{ site.url}}" />
<meta property="og:title" content="{% if page.title == null %}{{ site.title }}{% else %}{{ page.title }}{% endif %}" />
<meta property="og:description" content="{% if page.summary == null %}{{ site.description }}{% else %}{{ page.summary}}{% endif %}" />
<meta property="og:image" content="{{ site.url}}{% if page.social-image == null %}/img/social/og-profile.jpg{% else %}{{ page.social-image}}{% endif %}" />
<meta name="twitter:card" content="summary" />
<meta name="twitter:url" content="{{ site.url }}" />
<meta name="twitter:title" content="{% if page.title == null %}{{ site.title }}{% else %}{{ page.title }}{% endif %}" />
<meta name="twitter:description" content="{% if page.summary == null %}{{ site.description }}{% else %}{{ page.summary}}{% endif %}" />
<meta name="twitter:image" content="{{ site.url}}{% if page.social-image == null %}/img/social/og-profile.jpg{% else %}{{ page.social-image}}{% endif %}" />
<title>{% if page.title %}{{ page.title }}{% else %}{{ site.title }}{% endif %} | {{ site.title }}</title>
<link rel="shortcut icon" href="{{ site.baseurl }}/favicon.ico" type="image/vnd.microsoft.icon" />
<link rel="canonical" href="{{ page.url | replace:'index.html','' | prepend: site.baseurl | prepend: site.url }}">
<script type="text/javascript" src="{{ site.baseurl }}/js/modernizr.js"></script>
<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-WKSV4TS');</script>
<!-- End Google Tag Manager -->
<link rel="stylesheet" href="{{ site.baseurl }}/css/application.css">
{% for stylesheet in site.conditionalstylesheets %}<!--[{{ stylesheet.target }}]><style type="text/css" media="all">@import url("{{ site.baseurl }}{{ stylesheet.path }}");</style><![endif]-->{% endfor %}
</head>
<body>
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-WKSV4TS"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
<header class="navigation" role="banner">
<div class="navigation-wrapper">
<a href="/" class="logo"><h1>{{ site.name }}</h1></a>
<a href="javascript:void(0)" class="navigation-menu-button" id="js-mobile-menu">MENU</a>
<nav role="navigation">
<ul id="js-navigation-menu" class="navigation-menu">
{% for nav in site.data.nav %}
<li class="nav-link{% if nav.subcategories != null %} more{% endif %} {{ nav.title | slugify }} {% if page.url == nav.href %}current{% endif %}"><a href="{% if nav.subcategories != null %}javascript:void(0){% else %}{{ site.baseurl }}{{ nav.href }}{% endif %}">{{ nav.title }}{% if nav.subcategories != null %}<span class="caret"></span>{% endif %}</a>{% if nav.subcategories != null %}<ul class="submenu">{% for subcategory in nav.subcategories %}
<li class="{{ subcategory.subtitle | slugify }}"><a href="{{ site.baseurl }}{{ subcategory.subhref }}">{{ subcategory.subtitle }}</a></li>
{% endfor %}</ul>{% endif %}</li>
{% endfor %}
</ul>
<nav class="social-media-navigation">
<ul>
<li><a class="instagram" href="{{ site.instagram.url }}">Instagram</a></li><li><a class="twitter" href="{{ site.twitter.url }}">Twitter</a></li><li><a class="facebook" href="{{ site.facebook.url }}">Facebook</a></li>
</ul>
</nav>
</div>
</div>
</nav>
</header> | {
"content_hash": "9e1bda38042b5ef9b637d1e1dfcac5f7",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 453,
"avg_line_length": 71.01724137931035,
"alnum_prop": 0.6181111920369021,
"repo_name": "richardmscott/www.rscottillustration.co.uk",
"id": "8ffae96984b2619b44882da21fc278e8f4ea6628",
"size": "4119",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "_includes/header.html",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "81249"
},
{
"name": "HTML",
"bytes": "31118"
},
{
"name": "JavaScript",
"bytes": "7166"
},
{
"name": "Ruby",
"bytes": "4937"
}
],
"symlink_target": ""
} |
package com.jaquadro.minecraft.gardentrees.world.gen;
import java.util.HashMap;
import java.util.Map;
public class OrnamentalTreeRegistry
{
private static Map<String, OrnamentalTreeFactory> registry = new HashMap<String, OrnamentalTreeFactory>();
public static void registerTree (String name, OrnamentalTreeFactory treeFactory) {
registry.put(name, treeFactory);
}
public static OrnamentalTreeFactory getTree (String name) {
return registry.get(name);
}
static {
registerTree("small_oak", WorldGenStandardOrnTree.SmallOakTree.FACTORY);
registerTree("small_spruce", WorldGenStandardOrnTree.SmallSpruceTree.FACTORY);
registerTree("small_jungle", WorldGenStandardOrnTree.SmallJungleTree.FACTORY);
registerTree("small_acacia", WorldGenStandardOrnTree.SmallAcaciaTree.FACTORY);
registerTree("small_palm", WorldGenStandardOrnTree.SmallPalmTree.FACTORY);
registerTree("small_willow", WorldGenStandardOrnTree.SmallWillowTree.FACTORY);
registerTree("small_pine", WorldGenStandardOrnTree.SmallPineTree.FACTORY);
registerTree("small_mahogany", WorldGenStandardOrnTree.SmallMahoganyTree.FACTORY);
registerTree("small_shrub", WorldGenStandardOrnTree.SmallShrubTree.FACTORY);
registerTree("small_canopy", WorldGenStandardOrnTree.SmallCanopyTree.FACTORY);
registerTree("small_cyprus", WorldGenStandardOrnTree.SmallCyprusTree.FACTORY);
registerTree("tall_small_oak", WorldGenStandardOrnTree.TallSmallOakTree.FACTORY);
registerTree("large_oak", WorldGenStandardOrnTree.LargeOakTree.FACTORY);
registerTree("large_spruce", WorldGenStandardOrnTree.LargeSpruceTree.FACTORY);
}
}
| {
"content_hash": "79619e685e92c797cc9e0518146747f8",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 110,
"avg_line_length": 50.55882352941177,
"alnum_prop": 0.7643979057591623,
"repo_name": "jaquadro/GardenCollection",
"id": "e8be85a93b65361dcc9d58708e9c61e1d7ed0841",
"size": "1719",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/com/jaquadro/minecraft/gardentrees/world/gen/OrnamentalTreeRegistry.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "1257570"
}
],
"symlink_target": ""
} |
class Post < ActiveRecord::Base
has_paper_trail class_name: "PostVersion"
end
| {
"content_hash": "089f3cc6c364b0f95ec05f75d2fbf248",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 43,
"avg_line_length": 26.666666666666668,
"alnum_prop": 0.7625,
"repo_name": "devonestes/paper_trail",
"id": "29ea6d19eb39790ed7f467a3beaa286b060a20a5",
"size": "80",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "test/dummy/app/models/post.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "324340"
}
],
"symlink_target": ""
} |
layout: default
description: ":("
header-img: "img/404-bg.jpg"
permalink: /404.html
---
<!-- Page Header -->
<header class="intro-header" style="background-image: url('{{ site.baseurl }}/{% if page.header-img %}{{ page.header-img }}{% else %}{{ site.header-img }}{% endif %}')">
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<div class="site-heading" id="tag-heading">
<h1>404</h1>
<span class="subheading">{{ page.description }}</span>
</div>
</div>
</div>
</div>
</header>
<script>
document.body.classList.add('page-fullscreen');
</script>
| {
"content_hash": "ca89a8bedda36b0fe42e824d43ae5a76",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 169,
"avg_line_length": 26.541666666666668,
"alnum_prop": 0.6169544740973313,
"repo_name": "JasonYangX/blog",
"id": "dc4f66817aa8654995ae3728c352c134558bdaf0",
"size": "641",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "404.html",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "51349"
},
{
"name": "HTML",
"bytes": "48199"
},
{
"name": "JavaScript",
"bytes": "12381"
}
],
"symlink_target": ""
} |
{% extends "tournamentcontrol/competition/admin/match/dates.html" %}
| {
"content_hash": "f582efa150e7793f5c09443531770977",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 68,
"avg_line_length": 69,
"alnum_prop": 0.782608695652174,
"repo_name": "goodtune/vitriolic",
"id": "cef04b809687e163ca1c4e3443b39cd9d21578b5",
"size": "69",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tournamentcontrol/competition/templates/tournamentcontrol/competition/admin/match/weekly/dates.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "307509"
},
{
"name": "HTML",
"bytes": "273967"
},
{
"name": "JavaScript",
"bytes": "626908"
},
{
"name": "Less",
"bytes": "1373"
},
{
"name": "Makefile",
"bytes": "369"
},
{
"name": "Python",
"bytes": "962353"
},
{
"name": "Shell",
"bytes": "1490"
},
{
"name": "XSLT",
"bytes": "3510"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Slide Definition Example - Jssor Slider, Slideshow</title>
</head>
<body>
<!-- it works the same with all jquery version from 1.x to 2.x -->
<script type="text/javascript" src="../js/jquery-1.9.1.min.js"></script>
<!-- use jssor.slider.mini.js (40KB) or jssor.sliderc.mini.js (32KB, with caption, no slideshow) or jssor.sliders.mini.js (28KB, no caption, no slideshow) instead for release -->
<!-- jssor.slider.mini.js = jssor.sliderc.mini.js = jssor.sliders.mini.js = (jssor.js + jssor.slider.js) -->
<script type="text/javascript" src="../js/jssor.js"></script>
<script type="text/javascript" src="../js/jssor.slider.js"></script>
<script>
jQuery(document).ready(function ($) {
var _CaptionTransitions = [];
_CaptionTransitions["L"] = { $Duration: 900, x: 0.6, $Easing: { $Left: $JssorEasing$.$EaseInOutSine }, $Opacity: 2 };
_CaptionTransitions["R"] = { $Duration: 900, x: -0.6, $Easing: { $Left: $JssorEasing$.$EaseInOutSine }, $Opacity: 2 };
_CaptionTransitions["T"] = { $Duration: 900, y: 0.6, $Easing: { $Top: $JssorEasing$.$EaseInOutSine }, $Opacity: 2 };
_CaptionTransitions["B"] = { $Duration: 900, y: -0.6, $Easing: { $Top: $JssorEasing$.$EaseInOutSine }, $Opacity: 2 };
//Reference http://www.jssor.com/development/tool-caption-transition-viewer.html
var options = {
$AutoPlay: true, //[Optional] Whether to auto play, to enable slideshow, this option must be set to true, default value is false
$PlayOrientation: 1, //[Optional] Orientation to play slide (for auto play, navigation), 1 horizental, 2 vertical, 5 horizental reverse, 6 vertical reverse, default value is 1
$DragOrientation: 3, //[Optional] Orientation to drag slide, 0 no drag, 1 horizental, 2 vertical, 3 either, default value is 1 (Note that the $DragOrientation should be the same as $PlayOrientation when $DisplayPieces is greater than 1, or parking position is not 0)
$CaptionSliderOptions: { //[Optional] Options which specifies how to animate caption
$Class: $JssorCaptionSlider$, //[Required] Class to create instance to animate caption
$CaptionTransitions: _CaptionTransitions, //[Required] An array of caption transitions to play caption, see caption transition section at jssor slideshow transition builder
$PlayInMode: 1, //[Optional] 0 None (no play), 1 Chain (goes after main slide), 3 Chain Flatten (goes after main slide and flatten all caption animations), default value is 1
$PlayOutMode: 3 //[Optional] 0 None (no play), 1 Chain (goes before main slide), 3 Chain Flatten (goes before main slide and flatten all caption animations), default value is 1
}
};
var jssor_slider1 = new $JssorSlider$("slider1_container", options);
});
</script>
<!-- Jssor Slider Begin -->
<!-- You can move inline styles to css file or css block. -->
<div id="slider1_container" style="position: relative; width: 600px; height: 300px;">
<!-- Loading Screen -->
<div u="loading" style="position: absolute; top: 0px; left: 0px;">
<div style="filter: alpha(opacity=70); opacity:0.7; position: absolute; display: block;
background-color: #000000; top: 0px; left: 0px;width: 100%;height:100%;">
</div>
<div style="position: absolute; display: block; background: url(../img/loading.gif) no-repeat center center;
top: 0px; left: 0px;width: 100%;height:100%;">
</div>
</div>
<!-- Slides Container -->
<div u="slides" style="cursor: move; position: absolute; left: 0px; top: 0px; width:600px; height:300px; overflow: hidden;">
<div><img u="image" src="../img/landscape/01.jpg" /></div>
<div><a u=image href="
http://www.jssor.com" target="_blank"><img src="../img/landscape/02.jpg"/></a></div>
<div><img u="image" src="../img/landscape/03.jpg"/>
<div style="position: absolute; top: 125px; left: 125px; width: 350px; height: 50px;text-align:center;line-height:50px;background:#fff;">
This is static content, can be any html
</div>
</div>
<div><img u="image" src="../img/landscape/04.jpg"/>
<div u="caption" t="T" style="position: absolute; top: 125px; left: 125px; width: 350px;height: 50px;text-align:center;line-height:50px;background:#fff;">
This is caption, can be any html
</div>
</div>
</div>
<a style="display: none" href="http://www.jssor.com">slideshow</a>
</div>
<!-- Jssor Slider End -->
</body>
</html> | {
"content_hash": "ed66bcdc9f92d396bee41c2fb6d53117",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 313,
"avg_line_length": 70.12162162162163,
"alnum_prop": 0.5845056851031027,
"repo_name": "sharmasusheel/Get-blood",
"id": "98fcabf774bf988805a473e45039a06d501b6290",
"size": "5191",
"binary": false,
"copies": "10",
"ref": "refs/heads/master",
"path": "App_Code/examples-jquery/slide-definition.source.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "165573"
},
{
"name": "Batchfile",
"bytes": "41359"
},
{
"name": "C#",
"bytes": "62277"
},
{
"name": "CSS",
"bytes": "17899"
},
{
"name": "HTML",
"bytes": "2049249"
},
{
"name": "JavaScript",
"bytes": "537984"
}
],
"symlink_target": ""
} |
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.app.util.bin.format.pdb2.pdbreader.symbol;
import ghidra.app.util.bin.format.pdb2.pdbreader.*;
/**
* This class represents various flavors of Constant symbol.
* <P>
* Note: we do not necessarily understand each of these symbol type classes. Refer to the
* base class for more information.
*/
public abstract class AbstractConstantMsSymbol extends AbstractMsSymbol implements NameMsSymbol {
protected RecordNumber typeRecordNumber;
protected Numeric value;
protected String name;
/**
* Constructor for this symbol.
* @param pdb {@link AbstractPdb} to which this symbol belongs.
* @param reader {@link PdbByteReader} from which this symbol is deserialized.
* @param recordNumberSize size of record number to parse.
* @param strType {@link StringParseType} to use.
* @throws PdbException upon error parsing a field.
*/
public AbstractConstantMsSymbol(AbstractPdb pdb, PdbByteReader reader, int recordNumberSize,
StringParseType strType) throws PdbException {
super(pdb, reader);
typeRecordNumber = RecordNumber.parse(pdb, reader, RecordCategory.TYPE, recordNumberSize);
value = new Numeric(reader); //value = reader.parseUnsignedShortVal();
name = reader.parseString(pdb, strType);
}
/**
* Returns the type record number.
* @return Type record number.
*/
public RecordNumber getTypeRecordNumber() {
return typeRecordNumber;
}
/**
* Returns the Numeric value.
* @return Numeric value.
*/
public Numeric getValue() {
return value;
}
/**
* Returns the name.
* @return Name.
*/
@Override
public String getName() {
return name;
}
@Override
public void emit(StringBuilder builder) {
builder.append(getSymbolTypeName());
builder.append(": Type: ");
builder.append(pdb.getTypeRecord(typeRecordNumber).toString());
builder.append(", Value: ");
builder.append(value);
builder.append(", ");
builder.append(name);
}
}
| {
"content_hash": "801b797c1820f7d159ae9f76bdb1c87f",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 97,
"avg_line_length": 29.785714285714285,
"alnum_prop": 0.728617106314948,
"repo_name": "NationalSecurityAgency/ghidra",
"id": "443694ad8b0ce6b352749eb127ecf9a5fe5ce18b",
"size": "2502",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Ghidra/Features/PDB/src/main/java/ghidra/app/util/bin/format/pdb2/pdbreader/symbol/AbstractConstantMsSymbol.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "77536"
},
{
"name": "Batchfile",
"bytes": "21610"
},
{
"name": "C",
"bytes": "1132868"
},
{
"name": "C++",
"bytes": "7334484"
},
{
"name": "CSS",
"bytes": "75788"
},
{
"name": "GAP",
"bytes": "102771"
},
{
"name": "GDB",
"bytes": "3094"
},
{
"name": "HTML",
"bytes": "4121163"
},
{
"name": "Hack",
"bytes": "31483"
},
{
"name": "Haskell",
"bytes": "453"
},
{
"name": "Java",
"bytes": "88669329"
},
{
"name": "JavaScript",
"bytes": "1109"
},
{
"name": "Lex",
"bytes": "22193"
},
{
"name": "Makefile",
"bytes": "15883"
},
{
"name": "Objective-C",
"bytes": "23937"
},
{
"name": "Pawn",
"bytes": "82"
},
{
"name": "Python",
"bytes": "587415"
},
{
"name": "Shell",
"bytes": "234945"
},
{
"name": "TeX",
"bytes": "54049"
},
{
"name": "XSLT",
"bytes": "15056"
},
{
"name": "Xtend",
"bytes": "115955"
},
{
"name": "Yacc",
"bytes": "127754"
}
],
"symlink_target": ""
} |
package pThree;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.ListIterator;
public class Fruit {
private final LinkedList<String> bowl;
public Fruit() {
bowl=new LinkedList<>(Arrays.asList("Apple", "Banana", "Cherry", "Lemon", "Lime", "Orange", "Papaya", "Strawberry", "Watermelon"));
}
public void everyOtherFruit() {
ListIterator<String> iter=bowl.listIterator();
for(int i=0; i<bowl.size(); i++) {
if(i%2==0) System.out.println(iter.next());
else iter.next();
}
}
public static void main(String[] args) {
new Fruit().everyOtherFruit();
}
}
| {
"content_hash": "38d96ee8ffb76d93e18915bf5a1f7f52",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 133,
"avg_line_length": 25.916666666666668,
"alnum_prop": 0.6495176848874598,
"repo_name": "mRabitsky/RIPmrHorn",
"id": "b015aeea43682bdd7ee37c98b03f33796385f793",
"size": "622",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "RIP Mr Horn/src/pThree/Fruit.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "13382"
},
{
"name": "HTML",
"bytes": "111826"
},
{
"name": "Java",
"bytes": "154364"
},
{
"name": "JavaScript",
"bytes": "857"
}
],
"symlink_target": ""
} |
/**
* @license
* (c) 2009-2016 Michael Leibman
* michael{dot}leibman{at}gmail{dot}com
* http://github.com/mleibman/slickgrid
*
* Distributed under MIT license.
* All rights reserved.
*
* SlickGrid v2.4
*
* NOTES:
* Cell/row DOM manipulations are done directly bypassing jQuery's DOM manipulation methods.
* This increases the speed dramatically, but can only be done safely because there are no event handlers
* or data associated with any cell/row DOM nodes. Cell editors must make sure they implement .destroy()
* and do proper cleanup.
*/
// make sure required JavaScript modules are loaded
if (typeof jQuery === "undefined") {
throw new Error("SlickGrid requires jquery module to be loaded");
}
if (!jQuery.fn.drag) {
throw new Error("SlickGrid requires jquery.event.drag module to be loaded");
}
if (typeof Slick === "undefined") {
throw new Error("slick.core.js not loaded");
}
(function ($) {
"use strict";
// Slick.Grid
$.extend(true, window, {
Slick: {
Grid: SlickGrid
}
});
// shared across all grids on the page
var scrollbarDimensions;
var maxSupportedCssHeight; // browser's breaking point
//////////////////////////////////////////////////////////////////////////////////////////////
// SlickGrid class implementation (available as Slick.Grid)
/**
* Creates a new instance of the grid.
* @class SlickGrid
* @constructor
* @param {Node} container Container node to create the grid in.
* @param {Array,Object} data An array of objects for databinding.
* @param {Array} columns An array of column definitions.
* @param {Object} options Grid options.
**/
function SlickGrid(container, data, columns, options) {
// settings
var defaults = {
alwaysShowVerticalScroll: false,
alwaysAllowHorizontalScroll: false,
explicitInitialization: false,
rowHeight: 25,
defaultColumnWidth: 80,
enableAddRow: false,
leaveSpaceForNewRows: false,
editable: false,
autoEdit: true,
suppressActiveCellChangeOnEdit: false,
enableCellNavigation: true,
enableColumnReorder: true,
asyncEditorLoading: false,
asyncEditorLoadDelay: 100,
forceFitColumns: false,
enableAsyncPostRender: false,
asyncPostRenderDelay: 50,
enableAsyncPostRenderCleanup: false,
asyncPostRenderCleanupDelay: 40,
autoHeight: false,
editorLock: Slick.GlobalEditorLock,
showColumnHeader: true,
showHeaderRow: false,
headerRowHeight: 25,
createFooterRow: false,
showFooterRow: false,
footerRowHeight: 25,
createPreHeaderPanel: false,
showPreHeaderPanel: false,
preHeaderPanelHeight: 25,
showTopPanel: false,
topPanelHeight: 25,
formatterFactory: null,
editorFactory: null,
cellFlashingCssClass: "flashing",
selectedCellCssClass: "selected",
multiSelect: true,
enableTextSelectionOnCells: false,
dataItemColumnValueExtractor: null,
frozenBottom: false,
frozenColumn: -1,
frozenRow: -1,
fullWidthRows: false,
multiColumnSort: false,
numberedMultiColumnSort: false,
tristateMultiColumnSort: false,
sortColNumberInSeparateSpan: false,
defaultFormatter: defaultFormatter,
forceSyncScrolling: false,
addNewRowCssClass: "new-row",
preserveCopiedSelectionOnPaste: false,
showCellSelection: true,
viewportClass: null,
minRowBuffer: 3,
emulatePagingWhenScrolling: true, // when scrolling off bottom of viewport, place new row at top of viewport
editorCellNavOnLRKeys: false,
doPaging: true,
autosizeColsMode: Slick.GridAutosizeColsMode.LegacyOff,
autosizeColPaddingPx: 4,
autosizeTextAvgToMWidthRatio: 0.75,
viewportSwitchToScrollModeWidthPercent: undefined,
viewportMinWidthPx: undefined,
viewportMaxWidthPx: undefined
};
var columnDefaults = {
name: "",
resizable: true,
sortable: false,
minWidth: 30,
maxWidth: undefined,
rerenderOnResize: false,
headerCssClass: null,
defaultSortAsc: true,
focusable: true,
selectable: true,
};
var columnAutosizeDefaults = {
ignoreHeaderText: false,
colValueArray: undefined,
allowAddlPercent: undefined,
formatterOverride: undefined,
autosizeMode: Slick.ColAutosizeMode.ContentIntelligent,
rowSelectionModeOnInit: undefined,
rowSelectionMode: Slick.RowSelectionMode.FirstNRows,
rowSelectionCount: 100,
valueFilterMode: Slick.ValueFilterMode.None,
widthEvalMode: Slick.WidthEvalMode.CanvasTextSize,
sizeToRemaining: undefined,
widthPx: undefined,
colDataTypeOf: undefined
};
// scroller
var th; // virtual height
var h; // real scrollable height
var ph; // page height
var n; // number of pages
var cj; // "jumpiness" coefficient
var page = 0; // current page
var offset = 0; // current page offset
var vScrollDir = 1;
// private
var initialized = false;
var $container;
var uid = "slickgrid_" + Math.round(1000000 * Math.random());
var self = this;
var $focusSink, $focusSink2;
var $groupHeaders = $();
var $headerScroller;
var $headers;
var $headerRow, $headerRowScroller, $headerRowSpacerL, $headerRowSpacerR;
var $footerRow, $footerRowScroller, $footerRowSpacerL, $footerRowSpacerR;
var $preHeaderPanel, $preHeaderPanelScroller, $preHeaderPanelSpacer;
var $preHeaderPanelR, $preHeaderPanelScrollerR, $preHeaderPanelSpacerR;
var $topPanelScroller;
var $topPanel;
var $viewport;
var $canvas;
var $style;
var $boundAncestors;
var treeColumns;
var stylesheet, columnCssRulesL, columnCssRulesR;
var viewportH, viewportW;
var canvasWidth, canvasWidthL, canvasWidthR;
var headersWidth, headersWidthL, headersWidthR;
var viewportHasHScroll, viewportHasVScroll;
var headerColumnWidthDiff = 0, headerColumnHeightDiff = 0, // border+padding
cellWidthDiff = 0, cellHeightDiff = 0, jQueryNewWidthBehaviour = false;
var absoluteColumnMinWidth;
var hasFrozenRows = false;
var frozenRowsHeight = 0;
var actualFrozenRow = -1;
var paneTopH = 0;
var paneBottomH = 0;
var viewportTopH = 0;
var viewportBottomH = 0;
var topPanelH = 0;
var headerRowH = 0;
var footerRowH = 0;
var tabbingDirection = 1;
var $activeCanvasNode;
var $activeViewportNode;
var activePosX;
var activeRow, activeCell;
var activeCellNode = null;
var currentEditor = null;
var serializedEditorValue;
var editController;
var rowsCache = {};
var renderedRows = 0;
var numVisibleRows = 0;
var prevScrollTop = 0;
var scrollTop = 0;
var lastRenderedScrollTop = 0;
var lastRenderedScrollLeft = 0;
var prevScrollLeft = 0;
var scrollLeft = 0;
var selectionModel;
var selectedRows = [];
var plugins = [];
var cellCssClasses = {};
var columnsById = {};
var sortColumns = [];
var columnPosLeft = [];
var columnPosRight = [];
var pagingActive = false;
var pagingIsLastPage = false;
var scrollThrottle = ActionThrottle(render, 50);
// async call handles
var h_editorLoader = null;
var h_render = null;
var h_postrender = null;
var h_postrenderCleanup = null;
var postProcessedRows = {};
var postProcessToRow = null;
var postProcessFromRow = null;
var postProcessedCleanupQueue = [];
var postProcessgroupId = 0;
// perf counters
var counter_rows_rendered = 0;
var counter_rows_removed = 0;
// These two variables work around a bug with inertial scrolling in Webkit/Blink on Mac.
// See http://crbug.com/312427.
var rowNodeFromLastMouseWheelEvent; // this node must not be deleted while inertial scrolling
var zombieRowNodeFromLastMouseWheelEvent; // node that was hidden instead of getting deleted
var zombieRowCacheFromLastMouseWheelEvent; // row cache for above node
var zombieRowPostProcessedFromLastMouseWheelEvent; // post processing references for above node
var $paneHeaderL;
var $paneHeaderR;
var $paneTopL;
var $paneTopR;
var $paneBottomL;
var $paneBottomR;
var $headerScrollerL;
var $headerScrollerR;
var $headerL;
var $headerR;
var $groupHeadersL;
var $groupHeadersR;
var $headerRowScrollerL;
var $headerRowScrollerR;
var $footerRowScrollerL;
var $footerRowScrollerR;
var $headerRowL;
var $headerRowR;
var $footerRowL;
var $footerRowR;
var $topPanelScrollerL;
var $topPanelScrollerR;
var $topPanelL;
var $topPanelR;
var $viewportTopL;
var $viewportTopR;
var $viewportBottomL;
var $viewportBottomR;
var $canvasTopL;
var $canvasTopR;
var $canvasBottomL;
var $canvasBottomR;
var $viewportScrollContainerX;
var $viewportScrollContainerY;
var $headerScrollContainer;
var $headerRowScrollContainer;
var $footerRowScrollContainer;
// store css attributes if display:none is active in container or parent
var cssShow = { position: 'absolute', visibility: 'hidden', display: 'block' };
var $hiddenParents;
var oldProps = [];
var columnResizeDragging = false;
//////////////////////////////////////////////////////////////////////////////////////////////
// Initialization
function init() {
if (container instanceof jQuery) {
$container = container;
} else {
$container = $(container);
}
if ($container.length < 1) {
throw new Error("SlickGrid requires a valid container, " + container + " does not exist in the DOM.");
}
cacheCssForHiddenInit();
// calculate these only once and share between grid instances
maxSupportedCssHeight = maxSupportedCssHeight || getMaxSupportedCssHeight();
options = $.extend({}, defaults, options);
validateAndEnforceOptions();
columnDefaults.width = options.defaultColumnWidth;
treeColumns = new Slick.TreeColumns(columns);
columns = treeColumns.extractColumns();
updateColumnProps();
// validate loaded JavaScript modules against requested options
if (options.enableColumnReorder && !$.fn.sortable) {
throw new Error("SlickGrid's 'enableColumnReorder = true' option requires jquery-ui.sortable module to be loaded");
}
editController = {
"commitCurrentEdit": commitCurrentEdit,
"cancelCurrentEdit": cancelCurrentEdit
};
$container
.empty()
.css("overflow", "hidden")
.css("outline", 0)
.addClass(uid)
.addClass("ui-widget");
// set up a positioning container if needed
if (!(/relative|absolute|fixed/).test($container.css("position"))) {
$container.css("position", "relative");
}
$focusSink = $("<div tabIndex='0' hideFocus style='position:fixed;width:0;height:0;top:0;left:0;outline:0;'></div>").appendTo($container);
// Containers used for scrolling frozen columns and rows
$paneHeaderL = $("<div class='slick-pane slick-pane-header slick-pane-left' tabIndex='0' />").appendTo($container);
$paneHeaderR = $("<div class='slick-pane slick-pane-header slick-pane-right' tabIndex='0' />").appendTo($container);
$paneTopL = $("<div class='slick-pane slick-pane-top slick-pane-left' tabIndex='0' />").appendTo($container);
$paneTopR = $("<div class='slick-pane slick-pane-top slick-pane-right' tabIndex='0' />").appendTo($container);
$paneBottomL = $("<div class='slick-pane slick-pane-bottom slick-pane-left' tabIndex='0' />").appendTo($container);
$paneBottomR = $("<div class='slick-pane slick-pane-bottom slick-pane-right' tabIndex='0' />").appendTo($container);
if (options.createPreHeaderPanel) {
$preHeaderPanelScroller = $("<div class='slick-preheader-panel ui-state-default' style='overflow:hidden;position:relative;' />").appendTo($paneHeaderL);
$preHeaderPanel = $("<div />").appendTo($preHeaderPanelScroller);
$preHeaderPanelSpacer = $("<div style='display:block;height:1px;position:absolute;top:0;left:0;'></div>")
.appendTo($preHeaderPanelScroller);
$preHeaderPanelScrollerR = $("<div class='slick-preheader-panel ui-state-default' style='overflow:hidden;position:relative;' />").appendTo($paneHeaderR);
$preHeaderPanelR = $("<div />").appendTo($preHeaderPanelScrollerR);
$preHeaderPanelSpacerR = $("<div style='display:block;height:1px;position:absolute;top:0;left:0;'></div>")
.appendTo($preHeaderPanelScrollerR);
if (!options.showPreHeaderPanel) {
$preHeaderPanelScroller.hide();
$preHeaderPanelScrollerR.hide();
}
}
// Append the header scroller containers
$headerScrollerL = $("<div class='slick-header ui-state-default slick-header-left' />").appendTo($paneHeaderL);
$headerScrollerR = $("<div class='slick-header ui-state-default slick-header-right' />").appendTo($paneHeaderR);
// Cache the header scroller containers
$headerScroller = $().add($headerScrollerL).add($headerScrollerR);
if (treeColumns.hasDepth()) {
$groupHeadersL = [];
$groupHeadersR = [];
for (var index = 0; index < treeColumns.getDepth() - 1; index++) {
$groupHeadersL[index] = $("<div class='slick-group-header-columns slick-group-header-columns-left' style='left:-1000px' />").appendTo($headerScrollerL);
$groupHeadersR[index] = $("<div class='slick-group-header-columns slick-group-header-columns-right' style='left:-1000px' />").appendTo($headerScrollerR);
}
$groupHeaders = $().add($groupHeadersL).add($groupHeadersR);
}
// Append the columnn containers to the headers
$headerL = $("<div class='slick-header-columns slick-header-columns-left' style='left:-1000px' />").appendTo($headerScrollerL);
$headerR = $("<div class='slick-header-columns slick-header-columns-right' style='left:-1000px' />").appendTo($headerScrollerR);
// Cache the header columns
$headers = $().add($headerL).add($headerR);
$headerRowScrollerL = $("<div class='slick-headerrow ui-state-default' />").appendTo($paneTopL);
$headerRowScrollerR = $("<div class='slick-headerrow ui-state-default' />").appendTo($paneTopR);
$headerRowScroller = $().add($headerRowScrollerL).add($headerRowScrollerR);
$headerRowSpacerL = $("<div style='display:block;height:1px;position:absolute;top:0;left:0;'></div>")
.appendTo($headerRowScrollerL);
$headerRowSpacerR = $("<div style='display:block;height:1px;position:absolute;top:0;left:0;'></div>")
.appendTo($headerRowScrollerR);
$headerRowL = $("<div class='slick-headerrow-columns slick-headerrow-columns-left' />").appendTo($headerRowScrollerL);
$headerRowR = $("<div class='slick-headerrow-columns slick-headerrow-columns-right' />").appendTo($headerRowScrollerR);
$headerRow = $().add($headerRowL).add($headerRowR);
// Append the top panel scroller
$topPanelScrollerL = $("<div class='slick-top-panel-scroller ui-state-default' />").appendTo($paneTopL);
$topPanelScrollerR = $("<div class='slick-top-panel-scroller ui-state-default' />").appendTo($paneTopR);
$topPanelScroller = $().add($topPanelScrollerL).add($topPanelScrollerR);
// Append the top panel
$topPanelL = $("<div class='slick-top-panel' style='width:10000px' />").appendTo($topPanelScrollerL);
$topPanelR = $("<div class='slick-top-panel' style='width:10000px' />").appendTo($topPanelScrollerR);
$topPanel = $().add($topPanelL).add($topPanelR);
if (!options.showColumnHeader) {
$headerScroller.hide();
}
if (!options.showTopPanel) {
$topPanelScroller.hide();
}
if (!options.showHeaderRow) {
$headerRowScroller.hide();
}
// Append the viewport containers
$viewportTopL = $("<div class='slick-viewport slick-viewport-top slick-viewport-left' tabIndex='0' hideFocus />").appendTo($paneTopL);
$viewportTopR = $("<div class='slick-viewport slick-viewport-top slick-viewport-right' tabIndex='0' hideFocus />").appendTo($paneTopR);
$viewportBottomL = $("<div class='slick-viewport slick-viewport-bottom slick-viewport-left' tabIndex='0' hideFocus />").appendTo($paneBottomL);
$viewportBottomR = $("<div class='slick-viewport slick-viewport-bottom slick-viewport-right' tabIndex='0' hideFocus />").appendTo($paneBottomR);
// Cache the viewports
$viewport = $().add($viewportTopL).add($viewportTopR).add($viewportBottomL).add($viewportBottomR);
// Default the active viewport to the top left
$activeViewportNode = $viewportTopL;
// Append the canvas containers
$canvasTopL = $("<div class='grid-canvas grid-canvas-top grid-canvas-left' tabIndex='0' hideFocus />").appendTo($viewportTopL);
$canvasTopR = $("<div class='grid-canvas grid-canvas-top grid-canvas-right' tabIndex='0' hideFocus />").appendTo($viewportTopR);
$canvasBottomL = $("<div class='grid-canvas grid-canvas-bottom grid-canvas-left' tabIndex='0' hideFocus />").appendTo($viewportBottomL);
$canvasBottomR = $("<div class='grid-canvas grid-canvas-bottom grid-canvas-right' tabIndex='0' hideFocus />").appendTo($viewportBottomR);
if (options.viewportClass) $viewport.toggleClass(options.viewportClass, true);
// Cache the canvases
$canvas = $().add($canvasTopL).add($canvasTopR).add($canvasBottomL).add($canvasBottomR);
scrollbarDimensions = scrollbarDimensions || measureScrollbar();
// Default the active canvas to the top left
$activeCanvasNode = $canvasTopL;
// pre-header
if ($preHeaderPanelSpacer) $preHeaderPanelSpacer.css("width", getCanvasWidth() + scrollbarDimensions.width + "px");
$headers.width(getHeadersWidth());
$headerRowSpacerL.css("width", getCanvasWidth() + scrollbarDimensions.width + "px");
$headerRowSpacerR.css("width", getCanvasWidth() + scrollbarDimensions.width + "px");
// footer Row
if (options.createFooterRow) {
$footerRowScrollerR = $("<div class='slick-footerrow ui-state-default' />").appendTo($paneTopR);
$footerRowScrollerL = $("<div class='slick-footerrow ui-state-default' />").appendTo($paneTopL);
$footerRowScroller = $().add($footerRowScrollerL).add($footerRowScrollerR);
$footerRowSpacerL = $("<div style='display:block;height:1px;position:absolute;top:0;left:0;'></div>")
.css("width", getCanvasWidth() + scrollbarDimensions.width + "px")
.appendTo($footerRowScrollerL);
$footerRowSpacerR = $("<div style='display:block;height:1px;position:absolute;top:0;left:0;'></div>")
.css("width", getCanvasWidth() + scrollbarDimensions.width + "px")
.appendTo($footerRowScrollerR);
$footerRowL = $("<div class='slick-footerrow-columns slick-footerrow-columns-left' />").appendTo($footerRowScrollerL);
$footerRowR = $("<div class='slick-footerrow-columns slick-footerrow-columns-right' />").appendTo($footerRowScrollerR);
$footerRow = $().add($footerRowL).add($footerRowR);
if (!options.showFooterRow) {
$footerRowScroller.hide();
}
}
$focusSink2 = $focusSink.clone().appendTo($container);
if (!options.explicitInitialization) {
finishInitialization();
}
}
function finishInitialization() {
if (!initialized) {
initialized = true;
getViewportWidth();
getViewportHeight();
// header columns and cells may have different padding/border skewing width calculations (box-sizing, hello?)
// calculate the diff so we can set consistent sizes
measureCellPaddingAndBorder();
// for usability reasons, all text selection in SlickGrid is disabled
// with the exception of input and textarea elements (selection must
// be enabled there so that editors work as expected); note that
// selection in grid cells (grid body) is already unavailable in
// all browsers except IE
disableSelection($headers); // disable all text selection in header (including input and textarea)
if (!options.enableTextSelectionOnCells) {
// disable text selection in grid cells except in input and textarea elements
// (this is IE-specific, because selectstart event will only fire in IE)
$viewport.on("selectstart.ui", function (event) {
return $(event.target).is("input,textarea");
});
}
setFrozenOptions();
setPaneVisibility();
setScroller();
setOverflow();
updateColumnCaches();
createColumnHeaders();
createColumnGroupHeaders();
createColumnFooter();
setupColumnSort();
createCssRules();
resizeCanvas();
bindAncestorScrollEvents();
$container
.on("resize.slickgrid", resizeCanvas);
$viewport
.on("scroll", handleScroll);
if (jQuery.fn.mousewheel) {
$viewport.on("mousewheel", handleMouseWheel);
}
$headerScroller
//.on("scroll", handleHeaderScroll)
.on("contextmenu", handleHeaderContextMenu)
.on("click", handleHeaderClick)
.on("mouseenter", ".slick-header-column", handleHeaderMouseEnter)
.on("mouseleave", ".slick-header-column", handleHeaderMouseLeave);
$headerRowScroller
.on("scroll", handleHeaderRowScroll);
if (options.createFooterRow) {
$footerRow
.on("contextmenu", handleFooterContextMenu)
.on("click", handleFooterClick);
$footerRowScroller
.on("scroll", handleFooterRowScroll);
}
if (options.createPreHeaderPanel) {
$preHeaderPanelScroller
.on("scroll", handlePreHeaderPanelScroll);
}
$focusSink.add($focusSink2)
.on("keydown", handleKeyDown);
$canvas
.on("keydown", handleKeyDown)
.on("click", handleClick)
.on("dblclick", handleDblClick)
.on("contextmenu", handleContextMenu)
.on("draginit", handleDragInit)
.on("dragstart", {distance: 3}, handleDragStart)
.on("drag", handleDrag)
.on("dragend", handleDragEnd)
.on("mouseenter", ".slick-cell", handleMouseEnter)
.on("mouseleave", ".slick-cell", handleMouseLeave);
restoreCssFromHiddenInit();
}
}
function cacheCssForHiddenInit() {
// handle display:none on container or container parents
$hiddenParents = $container.parents().addBack().not(':visible');
$hiddenParents.each(function() {
var old = {};
for ( var name in cssShow ) {
old[ name ] = this.style[ name ];
this.style[ name ] = cssShow[ name ];
}
oldProps.push(old);
});
}
function restoreCssFromHiddenInit() {
// finish handle display:none on container or container parents
// - put values back the way they were
$hiddenParents.each(function(i) {
var old = oldProps[i];
for ( var name in cssShow ) {
this.style[ name ] = old[ name ];
}
});
}
function hasFrozenColumns() {
return options.frozenColumn > -1;
}
function registerPlugin(plugin) {
plugins.unshift(plugin);
plugin.init(self);
}
function unregisterPlugin(plugin) {
for (var i = plugins.length; i >= 0; i--) {
if (plugins[i] === plugin) {
if (plugins[i].destroy) {
plugins[i].destroy();
}
plugins.splice(i, 1);
break;
}
}
}
function getPluginByName(name) {
for (var i = plugins.length-1; i >= 0; i--) {
if (plugins[i].pluginName === name) {
return plugins[i];
}
}
return undefined;
}
function setSelectionModel(model) {
if (selectionModel) {
selectionModel.onSelectedRangesChanged.unsubscribe(handleSelectedRangesChanged);
if (selectionModel.destroy) {
selectionModel.destroy();
}
}
selectionModel = model;
if (selectionModel) {
selectionModel.init(self);
selectionModel.onSelectedRangesChanged.subscribe(handleSelectedRangesChanged);
}
}
function getSelectionModel() {
return selectionModel;
}
function getCanvasNode(columnIdOrIdx, rowIndex) {
if (!columnIdOrIdx) { columnIdOrIdx = 0; }
if (!rowIndex) { rowIndex = 0; }
var idx = (typeof columnIdOrIdx === "number" ? columnIdOrIdx : getColumnIndex(columnIdOrIdx));
return (hasFrozenRows && rowIndex >= actualFrozenRow + (options.frozenBottom ? 0 : 1) )
? ((hasFrozenColumns() && idx > options.frozenColumn) ? $canvasBottomR[0] : $canvasBottomL[0])
: ((hasFrozenColumns() && idx > options.frozenColumn) ? $canvasTopR[0] : $canvasTopL[0])
;
}
function getActiveCanvasNode(element) {
setActiveCanvasNode(element);
return $activeCanvasNode[0];
}
function getCanvases() {
return $canvas;
}
function setActiveCanvasNode(element) {
if (element) {
$activeCanvasNode = $(element.target).closest('.grid-canvas');
}
}
function getViewportNode() {
return $viewport[0];
}
function getActiveViewportNode(element) {
setActiveViewPortNode(element);
return $activeViewportNode[0];
}
function setActiveViewportNode(element) {
if (element) {
$activeViewportNode = $(element.target).closest('.slick-viewport');
}
}
function measureScrollbar() {
var $outerdiv = $('<div class="' + $viewport.className + '" style="position:absolute; top:-10000px; left:-10000px; overflow:auto; width:100px; height:100px;"></div>').appendTo('body');
var $innerdiv = $('<div style="width:200px; height:200px; overflow:auto;"></div>').appendTo($outerdiv);
var dim = {
width: $outerdiv[0].offsetWidth - $outerdiv[0].clientWidth,
height: $outerdiv[0].offsetHeight - $outerdiv[0].clientHeight
};
$innerdiv.remove();
$outerdiv.remove();
return dim;
}
function getHeadersWidth() {
headersWidth = headersWidthL = headersWidthR = 0;
var includeScrollbar = !options.autoHeight;
for (var i = 0, ii = columns.length; i < ii; i++) {
var width = columns[ i ].width;
if (( options.frozenColumn ) > -1 && ( i > options.frozenColumn )) {
headersWidthR += width;
} else {
headersWidthL += width;
}
}
if (includeScrollbar) {
if (( options.frozenColumn ) > -1 && ( i > options.frozenColumn )) {
headersWidthR += scrollbarDimensions.width;
} else {
headersWidthL += scrollbarDimensions.width;
}
}
if (hasFrozenColumns()) {
headersWidthL = headersWidthL + 1000;
headersWidthR = Math.max(headersWidthR, viewportW) + headersWidthL;
headersWidthR += scrollbarDimensions.width;
} else {
headersWidthL += scrollbarDimensions.width;
headersWidthL = Math.max(headersWidthL, viewportW) + 1000;
}
headersWidth = headersWidthL + headersWidthR;
return Math.max(headersWidth, viewportW) + 1000;
}
function getHeadersWidthL() {
headersWidthL =0;
columns.forEach(function(column, i) {
if (!(( options.frozenColumn ) > -1 && ( i > options.frozenColumn )))
headersWidthL += column.width;
});
if (hasFrozenColumns()) {
headersWidthL += 1000;
} else {
headersWidthL += scrollbarDimensions.width;
headersWidthL = Math.max(headersWidthL, viewportW) + 1000;
}
return headersWidthL;
}
function getHeadersWidthR() {
headersWidthR =0;
columns.forEach(function(column, i) {
if (( options.frozenColumn ) > -1 && ( i > options.frozenColumn ))
headersWidthR += column.width;
});
if (hasFrozenColumns()) {
headersWidthR = Math.max(headersWidthR, viewportW) + getHeadersWidthL();
headersWidthR += scrollbarDimensions.width;
}
return headersWidthR;
}
function getCanvasWidth() {
var availableWidth = viewportHasVScroll ? viewportW - scrollbarDimensions.width : viewportW;
var i = columns.length;
canvasWidthL = canvasWidthR = 0;
while (i--) {
if (hasFrozenColumns() && (i > options.frozenColumn)) {
canvasWidthR += columns[i].width;
} else {
canvasWidthL += columns[i].width;
}
}
var totalRowWidth = canvasWidthL + canvasWidthR;
return options.fullWidthRows ? Math.max(totalRowWidth, availableWidth) : totalRowWidth;
}
function updateCanvasWidth(forceColumnWidthsUpdate) {
var oldCanvasWidth = canvasWidth;
var oldCanvasWidthL = canvasWidthL;
var oldCanvasWidthR = canvasWidthR;
var widthChanged;
canvasWidth = getCanvasWidth();
widthChanged = canvasWidth !== oldCanvasWidth || canvasWidthL !== oldCanvasWidthL || canvasWidthR !== oldCanvasWidthR;
if (widthChanged || hasFrozenColumns() || hasFrozenRows) {
$canvasTopL.width(canvasWidthL);
getHeadersWidth();
$headerL.width(headersWidthL);
$headerR.width(headersWidthR);
if (hasFrozenColumns()) {
$canvasTopR.width(canvasWidthR);
$paneHeaderL.width(canvasWidthL);
$paneHeaderR.css('left', canvasWidthL);
$paneHeaderR.css('width', viewportW - canvasWidthL);
$paneTopL.width(canvasWidthL);
$paneTopR.css('left', canvasWidthL);
$paneTopR.css('width', viewportW - canvasWidthL);
$headerRowScrollerL.width(canvasWidthL);
$headerRowScrollerR.width(viewportW - canvasWidthL);
$headerRowL.width(canvasWidthL);
$headerRowR.width(canvasWidthR);
if (options.createFooterRow) {
$footerRowScrollerL.width(canvasWidthL);
$footerRowScrollerR.width(viewportW - canvasWidthL);
$footerRowL.width(canvasWidthL);
$footerRowR.width(canvasWidthR);
}
if (options.createPreHeaderPanel) {
$preHeaderPanel.width(canvasWidth);
}
$viewportTopL.width(canvasWidthL);
$viewportTopR.width(viewportW - canvasWidthL);
if (hasFrozenRows) {
$paneBottomL.width(canvasWidthL);
$paneBottomR.css('left', canvasWidthL);
$viewportBottomL.width(canvasWidthL);
$viewportBottomR.width(viewportW - canvasWidthL);
$canvasBottomL.width(canvasWidthL);
$canvasBottomR.width(canvasWidthR);
}
} else {
$paneHeaderL.width('100%');
$paneTopL.width('100%');
$headerRowScrollerL.width('100%');
$headerRowL.width(canvasWidth);
if (options.createFooterRow) {
$footerRowScrollerL.width('100%');
$footerRowL.width(canvasWidth);
}
if (options.createPreHeaderPanel) {
$preHeaderPanel.width('100%');
$preHeaderPanel.width(canvasWidth);
}
$viewportTopL.width('100%');
if (hasFrozenRows) {
$viewportBottomL.width('100%');
$canvasBottomL.width(canvasWidthL);
}
}
viewportHasHScroll = (canvasWidth > viewportW - scrollbarDimensions.width);
}
$headerRowSpacerL.width(canvasWidth + (viewportHasVScroll ? scrollbarDimensions.width : 0));
$headerRowSpacerR.width(canvasWidth + (viewportHasVScroll ? scrollbarDimensions.width : 0));
if (options.createFooterRow) {
$footerRowSpacerL.width(canvasWidth + (viewportHasVScroll ? scrollbarDimensions.width : 0));
$footerRowSpacerR.width(canvasWidth + (viewportHasVScroll ? scrollbarDimensions.width : 0));
}
if (widthChanged || forceColumnWidthsUpdate) {
applyColumnWidths();
}
}
function disableSelection($target) {
if ($target && $target.jquery) {
$target
.attr("unselectable", "on")
.css("MozUserSelect", "none")
.on("selectstart.ui", function () {
return false;
}); // from jquery:ui.core.js 1.7.2
}
}
function getMaxSupportedCssHeight() {
var supportedHeight = 1000000;
// FF reports the height back but still renders blank after ~6M px
var testUpTo = navigator.userAgent.toLowerCase().match(/firefox/) ? 6000000 : 1000000000;
var div = $("<div style='display:none' />").appendTo(document.body);
while (true) {
var test = supportedHeight * 2;
div.css("height", test);
if (test > testUpTo || div.height() !== test) {
break;
} else {
supportedHeight = test;
}
}
div.remove();
return supportedHeight;
}
function getUID() {
return uid;
}
function getHeaderColumnWidthDiff() {
return headerColumnWidthDiff;
}
function getScrollbarDimensions() {
return scrollbarDimensions;
}
// TODO: this is static. need to handle page mutation.
function bindAncestorScrollEvents() {
var elem = (hasFrozenRows && !options.frozenBottom) ? $canvasBottomL[0] : $canvasTopL[0];
while ((elem = elem.parentNode) != document.body && elem != null) {
// bind to scroll containers only
if (elem == $viewportTopL[0] || elem.scrollWidth != elem.clientWidth || elem.scrollHeight != elem.clientHeight) {
var $elem = $(elem);
if (!$boundAncestors) {
$boundAncestors = $elem;
} else {
$boundAncestors = $boundAncestors.add($elem);
}
$elem.on("scroll." + uid, handleActiveCellPositionChange);
}
}
}
function unbindAncestorScrollEvents() {
if (!$boundAncestors) {
return;
}
$boundAncestors.off("scroll." + uid);
$boundAncestors = null;
}
function updateColumnHeader(columnId, title, toolTip) {
if (!initialized) { return; }
var idx = getColumnIndex(columnId);
if (idx == null) {
return;
}
var columnDef = columns[idx];
var $header = $headers.children().eq(idx);
if ($header) {
if (title !== undefined) {
columns[idx].name = title;
}
if (toolTip !== undefined) {
columns[idx].toolTip = toolTip;
}
trigger(self.onBeforeHeaderCellDestroy, {
"node": $header[0],
"column": columnDef,
"grid": self
});
$header
.attr("title", toolTip || "")
.children().eq(0).html(title);
trigger(self.onHeaderCellRendered, {
"node": $header[0],
"column": columnDef,
"grid": self
});
}
}
function getHeader(columnDef) {
if (!columnDef) {
return hasFrozenColumns() ? $headers : $headerL;
}
var idx = getColumnIndex(columnDef.id);
return hasFrozenColumns() ? ((idx <= options.frozenColumn) ? $headerL : $headerR) : $headerL;
}
function getHeaderColumn(columnIdOrIdx) {
var idx = (typeof columnIdOrIdx === "number" ? columnIdOrIdx : getColumnIndex(columnIdOrIdx));
var targetHeader = hasFrozenColumns() ? ((idx <= options.frozenColumn) ? $headerL : $headerR) : $headerL;
var targetIndex = hasFrozenColumns() ? ((idx <= options.frozenColumn) ? idx : idx - options.frozenColumn - 1) : idx;
var $rtn = targetHeader.children().eq(targetIndex);
return $rtn && $rtn[0];
}
function getHeaderRow() {
return hasFrozenColumns() ? $headerRow : $headerRow[0];
}
function getFooterRow() {
return hasFrozenColumns() ? $footerRow : $footerRow[0];
}
function getPreHeaderPanel() {
return $preHeaderPanel[0];
}
function getPreHeaderPanelRight() {
return $preHeaderPanelR[0];
}
function getHeaderRowColumn(columnIdOrIdx) {
var idx = (typeof columnIdOrIdx === "number" ? columnIdOrIdx : getColumnIndex(columnIdOrIdx));
var $headerRowTarget;
if (hasFrozenColumns()) {
if (idx <= options.frozenColumn) {
$headerRowTarget = $headerRowL;
} else {
$headerRowTarget = $headerRowR;
idx -= options.frozenColumn + 1;
}
} else {
$headerRowTarget = $headerRowL;
}
var $header = $headerRowTarget.children().eq(idx);
return $header && $header[0];
}
function getFooterRowColumn(columnIdOrIdx) {
var idx = (typeof columnIdOrIdx === "number" ? columnIdOrIdx : getColumnIndex(columnIdOrIdx));
var $footerRowTarget;
if (hasFrozenColumns()) {
if (idx <= options.frozenColumn) {
$footerRowTarget = $footerRowL;
} else {
$footerRowTarget = $footerRowR;
idx -= options.frozenColumn + 1;
}
} else {
$footerRowTarget = $footerRowL;
}
var $footer = $footerRowTarget && $footerRowTarget.children().eq(idx);
return $footer && $footer[0];
}
function createColumnFooter() {
if (options.createFooterRow) {
$footerRow.find(".slick-footerrow-column")
.each(function () {
var columnDef = $(this).data("column");
if (columnDef) {
trigger(self.onBeforeFooterRowCellDestroy, {
"node": this,
"column": columnDef,
"grid": self
});
}
});
$footerRowL.empty();
$footerRowR.empty();
for (var i = 0; i < columns.length; i++) {
var m = columns[i];
var footerRowCell = $("<div class='ui-state-default slick-footerrow-column l" + i + " r" + i + "'></div>")
.data("column", m)
.addClass(hasFrozenColumns() && i <= options.frozenColumn? 'frozen': '')
.appendTo(hasFrozenColumns() && (i > options.frozenColumn)? $footerRowR: $footerRowL);
trigger(self.onFooterRowCellRendered, {
"node": footerRowCell[0],
"column": m,
"grid": self
});
}
}
}
function createColumnGroupHeaders() {
var columnsLength = 0;
var frozenColumnsValid = false;
if (!treeColumns.hasDepth())
return;
for (var index = 0; index < $groupHeadersL.length; index++) {
$groupHeadersL[index].empty();
$groupHeadersR[index].empty();
var groupColumns = treeColumns.getColumnsInDepth(index);
for (var indexGroup in groupColumns) {
var m = groupColumns[indexGroup];
columnsLength += m.extractColumns().length;
if (hasFrozenColumns() && index === 0 && (columnsLength-1) === options.frozenColumn)
frozenColumnsValid = true;
$("<div class='ui-state-default slick-group-header-column' />")
.html("<span class='slick-column-name'>" + m.name + "</span>")
.attr("id", "" + uid + m.id)
.attr("title", m.toolTip || "")
.data("column", m)
.addClass(m.headerCssClass || "")
.addClass(hasFrozenColumns() && (columnsLength - 1) > options.frozenColumn? 'frozen': '')
.appendTo(hasFrozenColumns() && (columnsLength - 1) > options.frozenColumn? $groupHeadersR[index]: $groupHeadersL[index]);
}
if (hasFrozenColumns() && index === 0 && !frozenColumnsValid) {
$groupHeadersL[index].empty();
$groupHeadersR[index].empty();
alert("All columns of group should to be grouped!");
break;
}
}
applyColumnGroupHeaderWidths();
}
function createColumnHeaders() {
function onMouseEnter() {
$(this).addClass("ui-state-hover");
}
function onMouseLeave() {
$(this).removeClass("ui-state-hover");
}
$headers.find(".slick-header-column")
.each(function() {
var columnDef = $(this).data("column");
if (columnDef) {
trigger(self.onBeforeHeaderCellDestroy, {
"node": this,
"column": columnDef,
"grid": self
});
}
});
$headerL.empty();
$headerR.empty();
getHeadersWidth();
$headerL.width(headersWidthL);
$headerR.width(headersWidthR);
$headerRow.find(".slick-headerrow-column")
.each(function() {
var columnDef = $(this).data("column");
if (columnDef) {
trigger(self.onBeforeHeaderRowCellDestroy, {
"node": this,
"column": columnDef,
"grid": self
});
}
});
$headerRowL.empty();
$headerRowR.empty();
if (options.createFooterRow) {
$footerRowL.find(".slick-footerrow-column")
.each(function() {
var columnDef = $(this).data("column");
if (columnDef) {
trigger(self.onBeforeFooterRowCellDestroy, {
"node": this,
"column": columnDef,
"grid": self
});
}
});
$footerRowL.empty();
if (hasFrozenColumns()) {
$footerRowR.find(".slick-footerrow-column")
.each(function() {
var columnDef = $(this).data("column");
if (columnDef) {
trigger(self.onBeforeFooterRowCellDestroy, {
"node": this,
"column": columnDef,
"grid": self
});
}
});
$footerRowR.empty();
}
}
for (var i = 0; i < columns.length; i++) {
var m = columns[i];
var $headerTarget = hasFrozenColumns() ? ((i <= options.frozenColumn) ? $headerL : $headerR) : $headerL;
var $headerRowTarget = hasFrozenColumns() ? ((i <= options.frozenColumn) ? $headerRowL : $headerRowR) : $headerRowL;
var header = $("<div class='ui-state-default slick-header-column' />")
.html("<span class='slick-column-name'>" + m.name + "</span>")
.width(m.width - headerColumnWidthDiff)
.attr("id", "" + uid + m.id)
.attr("title", m.toolTip || "")
.data("column", m)
.addClass(m.headerCssClass || "")
.addClass(hasFrozenColumns() && i <= options.frozenColumn? 'frozen': '')
.appendTo($headerTarget);
if (options.enableColumnReorder || m.sortable) {
header
.on('mouseenter', onMouseEnter)
.on('mouseleave', onMouseLeave);
}
if(m.hasOwnProperty('headerCellAttrs') && m.headerCellAttrs instanceof Object) {
for (var key in m.headerCellAttrs) {
if (m.headerCellAttrs.hasOwnProperty(key)) {
header.attr(key, m.headerCellAttrs[key]);
}
}
}
if (m.sortable) {
header.addClass("slick-header-sortable");
header.append("<span class='slick-sort-indicator"
+ (options.numberedMultiColumnSort && !options.sortColNumberInSeparateSpan ? " slick-sort-indicator-numbered" : "" ) + "' />");
if (options.numberedMultiColumnSort && options.sortColNumberInSeparateSpan) { header.append("<span class='slick-sort-indicator-numbered' />"); }
}
trigger(self.onHeaderCellRendered, {
"node": header[0],
"column": m,
"grid": self
});
if (options.showHeaderRow) {
var headerRowCell = $("<div class='ui-state-default slick-headerrow-column l" + i + " r" + i + "'></div>")
.data("column", m)
.addClass(hasFrozenColumns() && i <= options.frozenColumn? 'frozen': '')
.appendTo($headerRowTarget);
trigger(self.onHeaderRowCellRendered, {
"node": headerRowCell[0],
"column": m,
"grid": self
});
}
if (options.createFooterRow && options.showFooterRow) {
var footerRowCell = $("<div class='ui-state-default slick-footerrow-column l" + i + " r" + i + "'></div>")
.data("column", m)
.appendTo($footerRow);
trigger(self.onFooterRowCellRendered, {
"node": footerRowCell[0],
"column": m,
"grid": self
});
}
}
setSortColumns(sortColumns);
setupColumnResize();
if (options.enableColumnReorder) {
if (typeof options.enableColumnReorder == 'function') {
options.enableColumnReorder(self, $headers, headerColumnWidthDiff, setColumns, setupColumnResize, columns, getColumnIndex, uid, trigger);
} else {
setupColumnReorder();
}
}
}
function setupColumnSort() {
$headers.click(function (e) {
if (columnResizeDragging) return;
// temporary workaround for a bug in jQuery 1.7.1 (http://bugs.jquery.com/ticket/11328)
e.metaKey = e.metaKey || e.ctrlKey;
if ($(e.target).hasClass("slick-resizable-handle")) {
return;
}
var $col = $(e.target).closest(".slick-header-column");
if (!$col.length) {
return;
}
var column = $col.data("column");
if (column.sortable) {
if (!getEditorLock().commitCurrentEdit()) {
return;
}
var sortColumn = null;
var i = 0;
for (; i < sortColumns.length; i++) {
if (sortColumns[i].columnId == column.id) {
sortColumn = sortColumns[i];
sortColumn.sortAsc = !sortColumn.sortAsc;
break;
}
}
var hadSortCol = !!sortColumn;
if (options.tristateMultiColumnSort) {
if (!sortColumn) {
sortColumn = { columnId: column.id, sortAsc: column.defaultSortAsc };
}
if (hadSortCol && sortColumn.sortAsc) {
// three state: remove sort rather than go back to ASC
sortColumns.splice(i, 1);
sortColumn = null;
}
if (!options.multiColumnSort) { sortColumns = []; }
if (sortColumn && (!hadSortCol || !options.multiColumnSort)) {
sortColumns.push(sortColumn);
}
} else {
// legacy behaviour
if (e.metaKey && options.multiColumnSort) {
if (sortColumn) {
sortColumns.splice(i, 1);
}
}
else {
if ((!e.shiftKey && !e.metaKey) || !options.multiColumnSort) {
sortColumns = [];
}
if (!sortColumn) {
sortColumn = { columnId: column.id, sortAsc: column.defaultSortAsc };
sortColumns.push(sortColumn);
} else if (sortColumns.length === 0) {
sortColumns.push(sortColumn);
}
}
}
setSortColumns(sortColumns);
if (!options.multiColumnSort) {
trigger(self.onSort, {
multiColumnSort: false,
columnId: (sortColumns.length > 0 ? column.id : null),
sortCol: (sortColumns.length > 0 ? column : null),
sortAsc: (sortColumns.length > 0 ? sortColumns[0].sortAsc : true)
}, e);
} else {
trigger(self.onSort, {
multiColumnSort: true,
sortCols: $.map(sortColumns, function(col) {
return {columnId: columns[getColumnIndex(col.columnId)].id, sortCol: columns[getColumnIndex(col.columnId)], sortAsc: col.sortAsc };
})
}, e);
}
}
});
}
function currentPositionInHeader(id) {
var currentPosition = 0;
$headers.find('.slick-header-column').each(function (i) {
if (this.id == id) {
currentPosition = i;
return false;
}
});
return currentPosition;
}
function limitPositionInGroup(idColumn) {
var groupColumnOfPreviousPosition,
startLimit = 0,
endLimit = 0;
treeColumns
.getColumnsInDepth($groupHeadersL.length - 1)
.some(function (groupColumn) {
startLimit = endLimit;
endLimit += groupColumn.columns.length;
groupColumn.columns.some(function (column) {
if (column.id === idColumn)
groupColumnOfPreviousPosition = groupColumn;
return groupColumnOfPreviousPosition;
});
return groupColumnOfPreviousPosition;
});
endLimit--;
return {
start: startLimit,
end: endLimit,
group: groupColumnOfPreviousPosition
};
}
function remove(arr, elem) {
var index = arr.lastIndexOf(elem);
if(index > -1) {
arr.splice(index, 1);
remove(arr, elem);
}
}
function columnPositionValidInGroup($item) {
var currentPosition = currentPositionInHeader($item[0].id);
var limit = limitPositionInGroup($item.data('column').id);
var positionValid = limit.start <= currentPosition && currentPosition <= limit.end;
return {
limit: limit,
valid: positionValid,
message: positionValid? '': 'Column "'.concat($item.text(), '" can be reordered only within the "', limit.group.name, '" group!')
};
}
function setupColumnReorder() {
$headers.filter(":ui-sortable").sortable("destroy");
var columnScrollTimer = null;
function scrollColumnsRight() {
$viewportScrollContainerX[0].scrollLeft = $viewportScrollContainerX[0].scrollLeft + 10;
}
function scrollColumnsLeft() {
$viewportScrollContainerX[0].scrollLeft = $viewportScrollContainerX[0].scrollLeft - 10;
}
var canDragScroll;
$headers.sortable({
containment: "parent",
distance: 3,
axis: "x",
cursor: "default",
tolerance: "intersection",
helper: "clone",
placeholder: "slick-sortable-placeholder ui-state-default slick-header-column",
start: function (e, ui) {
ui.placeholder.width(ui.helper.outerWidth() - headerColumnWidthDiff);
canDragScroll = !hasFrozenColumns() ||
(ui.placeholder.offset().left + ui.placeholder.width()) > $viewportScrollContainerX.offset().left;
$(ui.helper).addClass("slick-header-column-active");
},
beforeStop: function (e, ui) {
$(ui.helper).removeClass("slick-header-column-active");
},
sort: function (e, ui) {
if (canDragScroll && e.originalEvent.pageX > $container[0].clientWidth) {
if (!(columnScrollTimer)) {
columnScrollTimer = setInterval(
scrollColumnsRight, 100);
}
} else if (canDragScroll && e.originalEvent.pageX < $viewportScrollContainerX.offset().left) {
if (!(columnScrollTimer)) {
columnScrollTimer = setInterval(
scrollColumnsLeft, 100);
}
} else {
clearInterval(columnScrollTimer);
columnScrollTimer = null;
}
},
stop: function (e, ui) {
var cancel = false;
clearInterval(columnScrollTimer);
columnScrollTimer = null;
var limit = null;
if (treeColumns.hasDepth()) {
var validPositionInGroup = columnPositionValidInGroup(ui.item);
limit = validPositionInGroup.limit;
cancel = !validPositionInGroup.valid;
if (cancel)
alert(validPositionInGroup.message);
}
if (cancel || !getEditorLock().commitCurrentEdit()) {
$(this).sortable("cancel");
return;
}
var reorderedIds = $headerL.sortable("toArray");
reorderedIds = reorderedIds.concat($headerR.sortable("toArray"));
var reorderedColumns = [];
for (var i = 0; i < reorderedIds.length; i++) {
reorderedColumns.push(columns[getColumnIndex(reorderedIds[i].replace(uid, ""))]);
}
setColumns(reorderedColumns);
trigger(self.onColumnsReordered, { impactedColumns : getImpactedColumns( limit ) });
e.stopPropagation();
setupColumnResize();
}
});
}
function getImpactedColumns( limit ) {
var impactedColumns = [];
if( limit ) {
for( var i = limit.start; i <= limit.end; i++ ) {
impactedColumns.push( columns[i] );
}
}
else {
impactedColumns = columns;
}
return impactedColumns;
}
function setupColumnResize() {
var $col, j, k, c, pageX, columnElements, minPageX, maxPageX, firstResizable, lastResizable;
columnElements = $headers.children();
columnElements.find(".slick-resizable-handle").remove();
columnElements.each(function (i, e) {
if (i >= columns.length) { return; }
if (columns[i].resizable) {
if (firstResizable === undefined) {
firstResizable = i;
}
lastResizable = i;
}
});
if (firstResizable === undefined) {
return;
}
columnElements.each(function (i, e) {
if (i >= columns.length) { return; }
if (i < firstResizable || (options.forceFitColumns && i >= lastResizable)) {
return;
}
$col = $(e);
$("<div class='slick-resizable-handle' />")
.appendTo(e)
.on("dragstart", function (e, dd) {
if (!getEditorLock().commitCurrentEdit()) {
return false;
}
pageX = e.pageX;
$(this).parent().addClass("slick-header-column-active");
var shrinkLeewayOnRight = null, stretchLeewayOnRight = null;
// lock each column's width option to current width
columnElements.each(function (i, e) {
if (i >= columns.length) { return; }
columns[i].previousWidth = $(e).outerWidth();
});
if (options.forceFitColumns) {
shrinkLeewayOnRight = 0;
stretchLeewayOnRight = 0;
// colums on right affect maxPageX/minPageX
for (j = i + 1; j < columns.length; j++) {
c = columns[j];
if (c.resizable) {
if (stretchLeewayOnRight !== null) {
if (c.maxWidth) {
stretchLeewayOnRight += c.maxWidth - c.previousWidth;
} else {
stretchLeewayOnRight = null;
}
}
shrinkLeewayOnRight += c.previousWidth - Math.max(c.minWidth || 0, absoluteColumnMinWidth);
}
}
}
var shrinkLeewayOnLeft = 0, stretchLeewayOnLeft = 0;
for (j = 0; j <= i; j++) {
// columns on left only affect minPageX
c = columns[j];
if (c.resizable) {
if (stretchLeewayOnLeft !== null) {
if (c.maxWidth) {
stretchLeewayOnLeft += c.maxWidth - c.previousWidth;
} else {
stretchLeewayOnLeft = null;
}
}
shrinkLeewayOnLeft += c.previousWidth - Math.max(c.minWidth || 0, absoluteColumnMinWidth);
}
}
if (shrinkLeewayOnRight === null) {
shrinkLeewayOnRight = 100000;
}
if (shrinkLeewayOnLeft === null) {
shrinkLeewayOnLeft = 100000;
}
if (stretchLeewayOnRight === null) {
stretchLeewayOnRight = 100000;
}
if (stretchLeewayOnLeft === null) {
stretchLeewayOnLeft = 100000;
}
maxPageX = pageX + Math.min(shrinkLeewayOnRight, stretchLeewayOnLeft);
minPageX = pageX - Math.min(shrinkLeewayOnLeft, stretchLeewayOnRight);
})
.on("drag", function (e, dd) {
columnResizeDragging = true;
var actualMinWidth, d = Math.min(maxPageX, Math.max(minPageX, e.pageX)) - pageX, x;
var newCanvasWidthL = 0, newCanvasWidthR = 0;
if (d < 0) { // shrink column
x = d;
for (j = i; j >= 0; j--) {
c = columns[j];
if (c.resizable) {
actualMinWidth = Math.max(c.minWidth || 0, absoluteColumnMinWidth);
if (x && c.previousWidth + x < actualMinWidth) {
x += c.previousWidth - actualMinWidth;
c.width = actualMinWidth;
} else {
c.width = c.previousWidth + x;
x = 0;
}
}
}
for (k = 0; k <= i; k++) {
c = columns[k];
if (hasFrozenColumns() && (k > options.frozenColumn)) {
newCanvasWidthR += c.width;
} else {
newCanvasWidthL += c.width;
}
}
if (options.forceFitColumns) {
x = -d;
for (j = i + 1; j < columns.length; j++) {
c = columns[j];
if (c.resizable) {
if (x && c.maxWidth && (c.maxWidth - c.previousWidth < x)) {
x -= c.maxWidth - c.previousWidth;
c.width = c.maxWidth;
} else {
c.width = c.previousWidth + x;
x = 0;
}
if (hasFrozenColumns() && (j > options.frozenColumn)) {
newCanvasWidthR += c.width;
} else {
newCanvasWidthL += c.width;
}
}
}
} else {
for (j = i + 1; j < columns.length; j++) {
c = columns[j];
if (hasFrozenColumns() && (j > options.frozenColumn)) {
newCanvasWidthR += c.width;
} else {
newCanvasWidthL += c.width;
}
}
}
if (options.forceFitColumns) {
x = -d;
for (j = i + 1; j < columns.length; j++) {
c = columns[j];
if (c.resizable) {
if (x && c.maxWidth && (c.maxWidth - c.previousWidth < x)) {
x -= c.maxWidth - c.previousWidth;
c.width = c.maxWidth;
} else {
c.width = c.previousWidth + x;
x = 0;
}
}
}
}
} else { // stretch column
x = d;
newCanvasWidthL = 0;
newCanvasWidthR = 0;
for (j = i; j >= 0; j--) {
c = columns[j];
if (c.resizable) {
if (x && c.maxWidth && (c.maxWidth - c.previousWidth < x)) {
x -= c.maxWidth - c.previousWidth;
c.width = c.maxWidth;
} else {
c.width = c.previousWidth + x;
x = 0;
}
}
}
for (k = 0; k <= i; k++) {
c = columns[k];
if (hasFrozenColumns() && (k > options.frozenColumn)) {
newCanvasWidthR += c.width;
} else {
newCanvasWidthL += c.width;
}
}
if (options.forceFitColumns) {
x = -d;
for (j = i + 1; j < columns.length; j++) {
c = columns[j];
if (c.resizable) {
actualMinWidth = Math.max(c.minWidth || 0, absoluteColumnMinWidth);
if (x && c.previousWidth + x < actualMinWidth) {
x += c.previousWidth - actualMinWidth;
c.width = actualMinWidth;
} else {
c.width = c.previousWidth + x;
x = 0;
}
if (hasFrozenColumns() && (j > options.frozenColumn)) {
newCanvasWidthR += c.width;
} else {
newCanvasWidthL += c.width;
}
}
}
} else {
for (j = i + 1; j < columns.length; j++) {
c = columns[j];
if (hasFrozenColumns() && (j > options.frozenColumn)) {
newCanvasWidthR += c.width;
} else {
newCanvasWidthL += c.width;
}
}
}
}
if (hasFrozenColumns() && newCanvasWidthL != canvasWidthL) {
$headerL.width(newCanvasWidthL + 1000);
$paneHeaderR.css('left', newCanvasWidthL);
}
applyColumnHeaderWidths();
applyColumnGroupHeaderWidths();
if (options.syncColumnCellResize) {
applyColumnWidths();
}
trigger(self.onColumnsDrag, {
triggeredByColumn: $(this).parent().attr("id").replace(uid, ""),
resizeHandle: $(this)
});
})
.on("dragend", function (e, dd) {
$(this).parent().removeClass("slick-header-column-active");
var triggeredByColumn = $(this).parent().attr("id").replace(uid, "");
if (trigger(self.onBeforeColumnsResize, { triggeredByColumn: triggeredByColumn }) === true) {
applyColumnHeaderWidths();
applyColumnGroupHeaderWidths();
}
var newWidth;
for (j = 0; j < columns.length; j++) {
c = columns[j];
newWidth = $(columnElements[j]).outerWidth();
if (c.previousWidth !== newWidth && c.rerenderOnResize) {
invalidateAllRows();
}
}
updateCanvasWidth(true);
render();
trigger(self.onColumnsResized, { triggeredByColumn: triggeredByColumn });
setTimeout(function () { columnResizeDragging = false; }, 300);
});
});
}
function getVBoxDelta($el) {
var p = ["borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom"];
var delta = 0;
if ($el && typeof $el.css === 'function') {
$.each(p, function (n, val) {
delta += parseFloat($el.css(val)) || 0;
});
}
return delta;
}
function setFrozenOptions() {
options.frozenColumn = (options.frozenColumn >= 0 && options.frozenColumn < columns.length)
? parseInt(options.frozenColumn)
: -1;
if (options.frozenRow > -1) {
hasFrozenRows = true;
frozenRowsHeight = ( options.frozenRow ) * options.rowHeight;
var dataLength = getDataLength();
actualFrozenRow = ( options.frozenBottom )
? ( dataLength - options.frozenRow )
: options.frozenRow;
} else {
hasFrozenRows = false;
}
}
function setPaneVisibility() {
if (hasFrozenColumns()) {
$paneHeaderR.show();
$paneTopR.show();
if (hasFrozenRows) {
$paneBottomL.show();
$paneBottomR.show();
} else {
$paneBottomR.hide();
$paneBottomL.hide();
}
} else {
$paneHeaderR.hide();
$paneTopR.hide();
$paneBottomR.hide();
if (hasFrozenRows) {
$paneBottomL.show();
} else {
$paneBottomR.hide();
$paneBottomL.hide();
}
}
}
function setOverflow() {
$viewportTopL.css({
'overflow-x': ( hasFrozenColumns() ) ? ( hasFrozenRows && !options.alwaysAllowHorizontalScroll ? 'hidden' : 'scroll' ) : ( hasFrozenRows && !options.alwaysAllowHorizontalScroll ? 'hidden' : 'auto' ),
'overflow-y': options.alwaysShowVerticalScroll ? "scroll" : (( hasFrozenColumns() ) ? ( hasFrozenRows ? 'hidden' : 'hidden' ) : ( hasFrozenRows ? 'scroll' : 'auto' ))
});
$viewportTopR.css({
'overflow-x': ( hasFrozenColumns() ) ? ( hasFrozenRows && !options.alwaysAllowHorizontalScroll ? 'hidden' : 'scroll' ) : ( hasFrozenRows && !options.alwaysAllowHorizontalScroll ? 'hidden' : 'auto' ),
'overflow-y': options.alwaysShowVerticalScroll ? "scroll" : (( hasFrozenColumns() ) ? ( hasFrozenRows ? 'scroll' : 'auto' ) : ( hasFrozenRows ? 'scroll' : 'auto' ))
});
$viewportBottomL.css({
'overflow-x': ( hasFrozenColumns() ) ? ( hasFrozenRows && !options.alwaysAllowHorizontalScroll ? 'scroll' : 'auto' ): ( hasFrozenRows && !options.alwaysAllowHorizontalScroll ? 'auto' : 'auto' ),
'overflow-y': options.alwaysShowVerticalScroll ? "scroll" : (( hasFrozenColumns() ) ? ( hasFrozenRows ? 'hidden' : 'hidden' ): ( hasFrozenRows ? 'scroll' : 'auto' ))
});
$viewportBottomR.css({
'overflow-x': ( hasFrozenColumns() ) ? ( hasFrozenRows && !options.alwaysAllowHorizontalScroll ? 'scroll' : 'auto' ) : ( hasFrozenRows && !options.alwaysAllowHorizontalScroll ? 'auto' : 'auto' ),
'overflow-y': options.alwaysShowVerticalScroll ? "scroll" : (( hasFrozenColumns() ) ? ( hasFrozenRows ? 'auto' : 'auto' ) : ( hasFrozenRows ? 'auto' : 'auto' ))
});
if (options.viewportClass) {
$viewportTopL.toggleClass(options.viewportClass, true);
$viewportTopR.toggleClass(options.viewportClass, true);
$viewportBottomL.toggleClass(options.viewportClass, true);
$viewportBottomR.toggleClass(options.viewportClass, true);
}
}
function setScroller() {
if (hasFrozenColumns()) {
$headerScrollContainer = $headerScrollerR;
$headerRowScrollContainer = $headerRowScrollerR;
$footerRowScrollContainer = $footerRowScrollerR;
if (hasFrozenRows) {
if (options.frozenBottom) {
$viewportScrollContainerX = $viewportBottomR;
$viewportScrollContainerY = $viewportTopR;
} else {
$viewportScrollContainerX = $viewportScrollContainerY = $viewportBottomR;
}
} else {
$viewportScrollContainerX = $viewportScrollContainerY = $viewportTopR;
}
} else {
$headerScrollContainer = $headerScrollerL;
$headerRowScrollContainer = $headerRowScrollerL;
$footerRowScrollContainer = $footerRowScrollerL;
if (hasFrozenRows) {
if (options.frozenBottom) {
$viewportScrollContainerX = $viewportBottomL;
$viewportScrollContainerY = $viewportTopL;
} else {
$viewportScrollContainerX = $viewportScrollContainerY = $viewportBottomL;
}
} else {
$viewportScrollContainerX = $viewportScrollContainerY = $viewportTopL;
}
}
}
function measureCellPaddingAndBorder() {
var el;
var h = ["borderLeftWidth", "borderRightWidth", "paddingLeft", "paddingRight"];
var v = ["borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom"];
// jquery prior to version 1.8 handles .width setter/getter as a direct css write/read
// jquery 1.8 changed .width to read the true inner element width if box-sizing is set to border-box, and introduced a setter for .outerWidth
// so for equivalent functionality, prior to 1.8 use .width, and after use .outerWidth
var verArray = $.fn.jquery.split('.');
jQueryNewWidthBehaviour = (verArray[0]==1 && verArray[1]>=8) || verArray[0] >=2;
el = $("<div class='ui-state-default slick-header-column' style='visibility:hidden'>-</div>").appendTo($headers);
headerColumnWidthDiff = headerColumnHeightDiff = 0;
if (el.css("box-sizing") != "border-box" && el.css("-moz-box-sizing") != "border-box" && el.css("-webkit-box-sizing") != "border-box") {
$.each(h, function (n, val) {
headerColumnWidthDiff += parseFloat(el.css(val)) || 0;
});
$.each(v, function (n, val) {
headerColumnHeightDiff += parseFloat(el.css(val)) || 0;
});
}
el.remove();
var r = $("<div class='slick-row' />").appendTo($canvas);
el = $("<div class='slick-cell' id='' style='visibility:hidden'>-</div>").appendTo(r);
cellWidthDiff = cellHeightDiff = 0;
if (el.css("box-sizing") != "border-box" && el.css("-moz-box-sizing") != "border-box" && el.css("-webkit-box-sizing") != "border-box") {
$.each(h, function (n, val) {
cellWidthDiff += parseFloat(el.css(val)) || 0;
});
$.each(v, function (n, val) {
cellHeightDiff += parseFloat(el.css(val)) || 0;
});
}
r.remove();
absoluteColumnMinWidth = Math.max(headerColumnWidthDiff, cellWidthDiff);
}
function createCssRules() {
$style = $("<style type='text/css' rel='stylesheet' />").appendTo($("head"));
var rowHeight = (options.rowHeight - cellHeightDiff);
var rules = [
"." + uid + " .slick-group-header-column { left: 1000px; }",
"." + uid + " .slick-header-column { left: 1000px; }",
"." + uid + " .slick-top-panel { height:" + options.topPanelHeight + "px; }",
"." + uid + " .slick-preheader-panel { height:" + options.preHeaderPanelHeight + "px; }",
"." + uid + " .slick-headerrow-columns { height:" + options.headerRowHeight + "px; }",
"." + uid + " .slick-footerrow-columns { height:" + options.footerRowHeight + "px; }",
"." + uid + " .slick-cell { height:" + rowHeight + "px; }",
"." + uid + " .slick-row { height:" + options.rowHeight + "px; }"
];
for (var i = 0; i < columns.length; i++) {
rules.push("." + uid + " .l" + i + " { }");
rules.push("." + uid + " .r" + i + " { }");
}
if ($style[0].styleSheet) { // IE
$style[0].styleSheet.cssText = rules.join(" ");
} else {
$style[0].appendChild(document.createTextNode(rules.join(" ")));
}
}
function getColumnCssRules(idx) {
var i;
if (!stylesheet) {
var sheets = document.styleSheets;
for (i = 0; i < sheets.length; i++) {
if ((sheets[i].ownerNode || sheets[i].owningElement) == $style[0]) {
stylesheet = sheets[i];
break;
}
}
if (!stylesheet) {
throw new Error("Cannot find stylesheet.");
}
// find and cache column CSS rules
columnCssRulesL = [];
columnCssRulesR = [];
var cssRules = (stylesheet.cssRules || stylesheet.rules);
var matches, columnIdx;
for (i = 0; i < cssRules.length; i++) {
var selector = cssRules[i].selectorText;
if (matches = /\.l\d+/.exec(selector)) {
columnIdx = parseInt(matches[0].substr(2, matches[0].length - 2), 10);
columnCssRulesL[columnIdx] = cssRules[i];
} else if (matches = /\.r\d+/.exec(selector)) {
columnIdx = parseInt(matches[0].substr(2, matches[0].length - 2), 10);
columnCssRulesR[columnIdx] = cssRules[i];
}
}
}
return {
"left": columnCssRulesL[idx],
"right": columnCssRulesR[idx]
};
}
function removeCssRules() {
$style.remove();
stylesheet = null;
}
function destroy() {
getEditorLock().cancelCurrentEdit();
trigger(self.onBeforeDestroy, {});
var i = plugins.length;
while(i--) {
unregisterPlugin(plugins[i]);
}
if (options.enableColumnReorder) {
$headers.filter(":ui-sortable").sortable("destroy");
}
unbindAncestorScrollEvents();
$container.off(".slickgrid");
removeCssRules();
$canvas.off("draginit dragstart dragend drag");
$container.empty().removeClass(uid);
}
//////////////////////////////////////////////////////////////////////////////////////////////
// Column Autosizing
//////////////////////////////////////////////////////////////////////////////////////////////
var canvas = null;
var canvas_context = null;
function autosizeColumn(columnOrIndexOrId, isInit) {
var c = columnOrIndexOrId;
if (typeof columnOrIndexOrId === 'number') {
c = columns[columnOrIndexOrId];
}
else if (typeof columnOrIndexOrId === 'string') {
for (var i = 0; i < columns.length; i++) {
if (columns[i].Id === columnOrIndexOrId) { c = columns[i]; }
}
}
var $gridCanvas = $(getCanvasNode(0, 0));
getColAutosizeWidth(c, $gridCanvas, isInit);
}
function autosizeColumns(autosizeMode, isInit) {
//LogColWidths();
autosizeMode = autosizeMode || options.autosizeColsMode;
if (autosizeMode === Slick.GridAutosizeColsMode.LegacyForceFit
|| autosizeMode === Slick.GridAutosizeColsMode.LegacyOff) {
legacyAutosizeColumns();
return;
}
if (autosizeMode === Slick.GridAutosizeColsMode.None) {
return;
}
// test for brower canvas support, canvas_context!=null if supported
canvas = document.createElement("canvas");
if (canvas && canvas.getContext) { canvas_context = canvas.getContext("2d"); }
// pass in the grid canvas
var $gridCanvas = $(getCanvasNode(0, 0));
var viewportWidth = viewportHasVScroll ? viewportW - scrollbarDimensions.width : viewportW;
// iterate columns to get autosizes
var i, c, colWidth, reRender, totalWidth = 0, totalWidthLessSTR = 0, strColsMinWidth = 0, totalMinWidth = 0, totalLockedColWidth = 0;
for (i = 0; i < columns.length; i++) {
c = columns[i];
getColAutosizeWidth(c, $gridCanvas, isInit);
totalLockedColWidth += (c.autoSize.autosizeMode === Slick.ColAutosizeMode.Locked ? c.width : 0);
totalMinWidth += (c.autoSize.autosizeMode === Slick.ColAutosizeMode.Locked ? c.width : c.minWidth);
totalWidth += c.autoSize.widthPx;
totalWidthLessSTR += (c.autoSize.sizeToRemaining ? 0 : c.autoSize.widthPx);
strColsMinWidth += (c.autoSize.sizeToRemaining ? c.minWidth || 0 : 0);
}
var strColTotalGuideWidth = totalWidth - totalWidthLessSTR;
if (autosizeMode === Slick.GridAutosizeColsMode.FitViewportToCols) {
// - if viewport with is outside MinViewportWidthPx and MaxViewportWidthPx, then the viewport is set to
// MinViewportWidthPx or MaxViewportWidthPx and the FitColsToViewport algorithm is used
// - viewport is resized to fit columns
var setWidth = totalWidth + scrollbarDimensions.width;
autosizeMode = Slick.GridAutosizeColsMode.IgnoreViewport;
if (options.viewportMaxWidthPx && setWidth > options.viewportMaxWidthPx) {
setWidth = options.viewportMaxWidthPx;
autosizeMode = Slick.GridAutosizeColsMode.FitColsToViewport;
} else if (options.viewportMinWidthPx && setWidth < options.viewportMinWidthPx) {
setWidth = options.viewportMinWidthPx;
autosizeMode = Slick.GridAutosizeColsMode.FitColsToViewport;
} else {
// falling back to IgnoreViewport will size the columns as-is, with render checking
//for (i = 0; i < columns.length; i++) { columns[i].width = columns[i].autoSize.widthPx; }
}
$container.width(setWidth);
}
if (autosizeMode === Slick.GridAutosizeColsMode.FitColsToViewport) {
if (strColTotalGuideWidth > 0 && totalWidthLessSTR < viewportWidth - strColsMinWidth) {
// if addl space remains in the viewport and there are SizeToRemaining cols, just the SizeToRemaining cols expand proportionally to fill viewport
for (i = 0; i < columns.length; i++) {
c = columns[i];
var totalSTRViewportWidth = viewportWidth - totalWidthLessSTR;
if (c.autoSize.sizeToRemaining) {
colWidth = totalSTRViewportWidth * c.autoSize.widthPx / strColTotalGuideWidth;
} else {
colWidth = c.autoSize.widthPx;
}
if (c.rerenderOnResize && c.width != colWidth) { reRender = true; }
c.width = colWidth;
}
} else if ((options.viewportSwitchToScrollModeWidthPercent && totalWidthLessSTR + strColsMinWidth > viewportWidth * options.viewportSwitchToScrollModeWidthPercent / 100)
|| (totalMinWidth > viewportWidth)) {
// if the total columns width is wider than the viewport by switchToScrollModeWidthPercent, switch to IgnoreViewport mode
autosizeMode = Slick.GridAutosizeColsMode.IgnoreViewport;
} else {
// otherwise (ie. no SizeToRemaining cols or viewport smaller than columns) all cols other than 'Locked' scale in proportion to fill viewport
// and SizeToRemaining get minWidth
var unallocatedColWidth = totalWidthLessSTR - totalLockedColWidth;
var unallocatedViewportWidth = viewportWidth - totalLockedColWidth - strColsMinWidth;
for (i = 0; i < columns.length; i++) {
c = columns[i];
colWidth = c.width;
if (c.autoSize.autosizeMode !== Slick.ColAutosizeMode.Locked) {
if (c.autoSize.sizeToRemaining) {
colWidth = c.minWidth;
} else {
// size width proportionally to free space (we know we have enough room due to the earlier calculations)
colWidth = unallocatedViewportWidth / unallocatedColWidth * c.autoSize.widthPx;
if (colWidth < c.minWidth) { colWidth = c.minWidth; }
// remove the just allocated widths from the allocation pool
unallocatedColWidth -= c.autoSize.widthPx;
unallocatedViewportWidth -= colWidth;
}
}
if (c.rerenderOnResize && c.width != colWidth) { reRender = true; }
c.width = colWidth;
}
}
}
if (autosizeMode === Slick.GridAutosizeColsMode.IgnoreViewport) {
// just size columns as-is
for (i = 0; i < columns.length; i++) {
colWidth = columns[i].autoSize.widthPx;
if (columns[i].rerenderOnResize && columns[i].width != colWidth) {
reRender = true;
}
columns[i].width = colWidth;
}
}
//LogColWidths();
reRenderColumns(reRender);
}
function LogColWidths () {
var s = "Col Widths:";
for (var i = 0; i < columns.length; i++) { s += ' ' + columns[i].width; }
console.log(s);
}
function getColAutosizeWidth(columnDef, $gridCanvas, isInit) {
var autoSize = columnDef.autoSize;
// set to width as default
autoSize.widthPx = columnDef.width;
if (autoSize.autosizeMode === Slick.ColAutosizeMode.Locked
|| autoSize.autosizeMode === Slick.ColAutosizeMode.Guide) {
return;
}
var dl = getDataLength(); //getDataItem();
// ContentIntelligent takes settings from column data type
if (autoSize.autosizeMode === Slick.ColAutosizeMode.ContentIntelligent) {
// default to column colDataTypeOf (can be used if initially there are no data rows)
var colDataTypeOf = autoSize.colDataTypeOf;
var colDataItem;
if (dl > 0) {
var tempRow = getDataItem(0);
if (tempRow) {
colDataItem = tempRow[columnDef.field];
colDataTypeOf = typeof colDataItem;
if (colDataTypeOf === 'object') {
if (colDataItem instanceof Date) { colDataTypeOf = "date"; }
if (typeof moment!=='undefined' && colDataItem instanceof moment) { colDataTypeOf = "moment"; }
}
}
}
if (colDataTypeOf === 'boolean') {
autoSize.colValueArray = [ true, false ];
}
if (colDataTypeOf === 'number') {
autoSize.valueFilterMode = Slick.ValueFilterMode.GetGreatestAndSub;
autoSize.rowSelectionMode = Slick.RowSelectionMode.AllRows;
}
if (colDataTypeOf === 'string') {
autoSize.valueFilterMode = Slick.ValueFilterMode.GetLongestText;
autoSize.rowSelectionMode = Slick.RowSelectionMode.AllRows;
autoSize.allowAddlPercent = 5;
}
if (colDataTypeOf === 'date') {
autoSize.colValueArray = [ new Date(2009, 8, 30, 12, 20, 20) ]; // Sep 30th 2009, 12:20:20 AM
}
if (colDataTypeOf === 'moment' && typeof moment!=='undefined') {
autoSize.colValueArray = [ moment([2009, 8, 30, 12, 20, 20]) ]; // Sep 30th 2009, 12:20:20 AM
}
}
// at this point, the autosizeMode is effectively 'Content', so proceed to get size
var colWidth = getColContentSize(columnDef, $gridCanvas, isInit);
var addlPercentMultiplier = (autoSize.allowAddlPercent ? (1 + autoSize.allowAddlPercent/100) : 1);
colWidth = colWidth * addlPercentMultiplier + options.autosizeColPaddingPx;
if (columnDef.minWidth && colWidth < columnDef.minWidth) { colWidth = columnDef.minWidth; }
if (columnDef.maxWidth && colWidth > columnDef.maxWidth) { colWidth = columnDef.maxWidth; }
autoSize.widthPx = colWidth;
}
function getColContentSize(columnDef, $gridCanvas, isInit) {
var autoSize = columnDef.autoSize;
var widthAdjustRatio = 1;
// at this point, the autosizeMode is effectively 'Content', so proceed to get size
// get header width, if we are taking notice of it
var i, ii;
var maxColWidth = 0;
var headerWidth = 0;
if (!autoSize.ignoreHeaderText) {
headerWidth = getColHeaderWidth(columnDef);
}
if (autoSize.colValueArray) {
// if an array of values are specified, just pass them in instead of data
maxColWidth = getColWidth(columnDef, $gridCanvas, autoSize.colValueArray);
return Math.max(headerWidth, maxColWidth);
}
// select rows to evaluate using rowSelectionMode and rowSelectionCount
var rows = getData();
if (rows.getItems) { rows = rows.getItems(); }
var rowSelectionMode = (isInit ? autoSize.rowSelectionModeOnInit : undefined) || autoSize.rowSelectionMode;
if (rowSelectionMode === Slick.RowSelectionMode.FirstRow) { rows = rows.slice(0,1); }
if (rowSelectionMode === Slick.RowSelectionMode.LastRow) { rows = rows.slice(rows.length -1, rows.length); }
if (rowSelectionMode === Slick.RowSelectionMode.FirstNRows) { rows = rows.slice(0, autoSize.rowSelectionCount); }
// now use valueFilterMode to further filter selected rows
if (autoSize.valueFilterMode === Slick.ValueFilterMode.DeDuplicate) {
var rowsDict = {};
for (i = 0, ii = rows.length; i < ii; i++) {
rowsDict[rows[i][columnDef.field]] = true;
}
if (Object.keys) {
rows = Object.keys(rowsDict);
} else {
rows = [];
for (var i in rowsDict) rows.push(i);
}
}
if (autoSize.valueFilterMode === Slick.ValueFilterMode.GetGreatestAndSub) {
// get greatest abs value in data
var tempVal, maxVal, maxAbsVal = 0;
for (i = 0, ii = rows.length; i < ii; i++) {
tempVal = rows[i][columnDef.field];
if (Math.abs(tempVal) > maxAbsVal) { maxVal = tempVal; maxAbsVal = Math.abs(tempVal); }
}
// now substitute a '9' for all characters (to get widest width) and convert back to a number
maxVal = '' + maxVal;
maxVal = Array(maxVal.length + 1).join("9");
maxVal = +maxVal;
rows = [ maxVal ];
}
if (autoSize.valueFilterMode === Slick.ValueFilterMode.GetLongestTextAndSub) {
// get greatest abs value in data
var tempVal, maxLen = 0;
for (i = 0, ii = rows.length; i < ii; i++) {
tempVal = rows[i][columnDef.field];
if ((tempVal || '').length > maxLen) { maxLen = tempVal.length; }
}
// now substitute a 'c' for all characters
tempVal = Array(maxLen + 1).join("m");
widthAdjustRatio = options.autosizeTextAvgToMWidthRatio;
rows = [ tempVal ];
}
if (autoSize.valueFilterMode === Slick.ValueFilterMode.GetLongestText) {
// get greatest abs value in data
var tempVal, maxLen = 0, maxIndex = 0;
for (i = 0, ii = rows.length; i < ii; i++) {
tempVal = rows[i][columnDef.field];
if ((tempVal || '').length > maxLen) { maxLen = tempVal.length; maxIndex = i; }
}
// now substitute a 'c' for all characters
tempVal = rows[maxIndex][columnDef.field];
rows = [ tempVal ];
}
maxColWidth = getColWidth(columnDef, $gridCanvas, rows) * widthAdjustRatio;
return Math.max(headerWidth, maxColWidth);
}
function getColWidth(columnDef, $gridCanvas, data) {
var colIndex = getColumnIndex(columnDef.id);
var $rowEl = $('<div class="slick-row ui-widget-content"></div>');
var $cellEl = $('<div class="slick-cell"></div>');
$cellEl.css({
"position": "absolute",
"visibility": "hidden",
"text-overflow": "initial",
"white-space": "nowrap"
});
$rowEl.append($cellEl);
$gridCanvas.append($rowEl);
var len, max = 0, text, maxText, formatterResult, maxWidth = 0, val;
// use canvas - very fast, but text-only
if (canvas_context && columnDef.autoSize.widthEvalMode === Slick.WidthEvalMode.CanvasTextSize) {
canvas_context.font = $cellEl.css("font-size") + " " + $cellEl.css("font-family");
$(data).each(function (index, row) {
// row is either an array or values or a single value
val = (Array.isArray(row) ? row[columnDef.field] : row);
text = '' + val;
len = text ? canvas_context.measureText(text).width : 0;
if (len > max) { max = len; maxText = text; }
});
$cellEl.html(maxText);
len = $cellEl.outerWidth();
$rowEl.remove();
return len;
}
$(data).each(function (index, row) {
val = (Array.isArray(row) ? row[columnDef.field] : row);
if (columnDef.formatterOverride) {
// use formatterOverride as first preference
formatterResult = columnDef.formatterOverride(index, colIndex, val, columnDef, row);
} else if (columnDef.formatter) {
// otherwise, use formatter
formatterResult = columnDef.formatter(index, colIndex, val, columnDef, row);
} else {
// otherwise, use plain text
formatterResult = '' + val;
}
applyFormatResultToCellNode(formatterResult, $cellEl[0]);
len = $cellEl.outerWidth();
if (len > max) { max = len; }
});
$rowEl.remove();
return max;
}
function getColHeaderWidth(columnDef) {
var width = 0;
//if (columnDef && (!columnDef.resizable || columnDef._autoCalcWidth === true)) return;
var headerColElId = getUID() + columnDef.id;
var headerColEl = document.getElementById(headerColElId);
var dummyHeaderColElId = headerColElId + "_";
if (headerColEl) {
// headers have been created, use clone technique
var clone = headerColEl.cloneNode(true);
clone.id = dummyHeaderColElId;
clone.style.cssText = 'position: absolute; visibility: hidden;right: auto;text-overflow: initial;white-space: nowrap;';
headerColEl.parentNode.insertBefore(clone, headerColEl);
width = clone.offsetWidth;
clone.parentNode.removeChild(clone);
} else {
// headers have not yet been created, create a new node
var header = getHeader(columnDef);
headerColEl = $("<div class='ui-state-default slick-header-column' />")
.html("<span class='slick-column-name'>" + columnDef.name + "</span>")
.attr("id", dummyHeaderColElId)
.css({ "position": "absolute", "visibility": "hidden", "right": "auto", "text-overflow:": "initial", "white-space": "nowrap" })
.addClass(columnDef.headerCssClass || "")
.appendTo(header);
width = headerColEl[0].offsetWidth;
header[0].removeChild(headerColEl[0]);
}
return width;
}
function legacyAutosizeColumns() {
var i, c,
widths = [],
shrinkLeeway = 0,
total = 0,
prevTotal,
availWidth = viewportHasVScroll ? viewportW - scrollbarDimensions.width : viewportW;
for (i = 0; i < columns.length; i++) {
c = columns[i];
widths.push(c.width);
total += c.width;
if (c.resizable) {
shrinkLeeway += c.width - Math.max(c.minWidth, absoluteColumnMinWidth);
}
}
// shrink
prevTotal = total;
while (total > availWidth && shrinkLeeway) {
var shrinkProportion = (total - availWidth) / shrinkLeeway;
for (i = 0; i < columns.length && total > availWidth; i++) {
c = columns[i];
var width = widths[i];
if (!c.resizable || width <= c.minWidth || width <= absoluteColumnMinWidth) {
continue;
}
var absMinWidth = Math.max(c.minWidth, absoluteColumnMinWidth);
var shrinkSize = Math.floor(shrinkProportion * (width - absMinWidth)) || 1;
shrinkSize = Math.min(shrinkSize, width - absMinWidth);
total -= shrinkSize;
shrinkLeeway -= shrinkSize;
widths[i] -= shrinkSize;
}
if (prevTotal <= total) { // avoid infinite loop
break;
}
prevTotal = total;
}
// grow
prevTotal = total;
while (total < availWidth) {
var growProportion = availWidth / total;
for (i = 0; i < columns.length && total < availWidth; i++) {
c = columns[i];
var currentWidth = widths[i];
var growSize;
if (!c.resizable || c.maxWidth <= currentWidth) {
growSize = 0;
} else {
growSize = Math.min(Math.floor(growProportion * currentWidth) - currentWidth, (c.maxWidth - currentWidth) || 1000000) || 1;
}
total += growSize;
widths[i] += (total <= availWidth ? growSize : 0);
}
if (prevTotal >= total) { // avoid infinite loop
break;
}
prevTotal = total;
}
var reRender = false;
for (i = 0; i < columns.length; i++) {
if (columns[i].rerenderOnResize && columns[i].width != widths[i]) {
reRender = true;
}
columns[i].width = widths[i];
}
reRenderColumns(reRender);
}
function reRenderColumns(reRender) {
applyColumnHeaderWidths();
applyColumnGroupHeaderWidths();
updateCanvasWidth(true);
trigger(self.onAutosizeColumns, { "columns": columns});
if (reRender) {
invalidateAllRows();
render();
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
// General
//////////////////////////////////////////////////////////////////////////////////////////////
function trigger(evt, args, e) {
e = e || new Slick.EventData();
args = args || {};
args.grid = self;
return evt.notify(args, e, self);
}
function getEditorLock() {
return options.editorLock;
}
function getEditController() {
return editController;
}
function getColumnIndex(id) {
return columnsById[id];
}
function applyColumnGroupHeaderWidths() {
if (!treeColumns.hasDepth())
return;
for (var depth = $groupHeadersL.length - 1; depth >= 0; depth--) {
var groupColumns = treeColumns.getColumnsInDepth(depth);
$().add($groupHeadersL[depth]).add($groupHeadersR[depth]).each(function(i) {
var $groupHeader = $(this),
currentColumnIndex = 0;
$groupHeader.width(i === 0? getHeadersWidthL(): getHeadersWidthR());
$groupHeader.children().each(function() {
var $groupHeaderColumn = $(this);
var m = $(this).data('column');
m.width = 0;
m.columns.forEach(function() {
var $headerColumn = $groupHeader.next().children(':eq(' + (currentColumnIndex++) + ')');
m.width += $headerColumn.outerWidth();
});
$groupHeaderColumn.width(m.width - headerColumnWidthDiff);
});
});
}
}
function applyColumnHeaderWidths() {
if (!initialized) { return; }
var h;
for (var i = 0, headers = $headers.children(), ii = columns.length; i < ii; i++) {
h = $(headers[i]);
if (jQueryNewWidthBehaviour) {
if (h.outerWidth() !== columns[i].width) {
h.outerWidth(columns[i].width);
}
} else {
if (h.width() !== columns[i].width - headerColumnWidthDiff) {
h.width(columns[i].width - headerColumnWidthDiff);
}
}
}
updateColumnCaches();
}
function applyColumnWidths() {
var x = 0, w, rule;
for (var i = 0; i < columns.length; i++) {
w = columns[i].width;
rule = getColumnCssRules(i);
rule.left.style.left = x + "px";
rule.right.style.right = (((options.frozenColumn != -1 && i > options.frozenColumn) ? canvasWidthR : canvasWidthL) - x - w) + "px";
// If this column is frozen, reset the css left value since the
// column starts in a new viewport.
if (options.frozenColumn == i) {
x = 0;
} else {
x += columns[i].width;
}
}
}
function setSortColumn(columnId, ascending) {
setSortColumns([{ columnId: columnId, sortAsc: ascending}]);
}
function setSortColumns(cols) {
sortColumns = cols;
var numberCols = options.numberedMultiColumnSort && sortColumns.length > 1;
var headerColumnEls = $headers.children();
headerColumnEls
.removeClass("slick-header-column-sorted")
.find(".slick-sort-indicator")
.removeClass("slick-sort-indicator-asc slick-sort-indicator-desc");
headerColumnEls
.find(".slick-sort-indicator-numbered")
.text('');
$.each(sortColumns, function(i, col) {
if (col.sortAsc == null) {
col.sortAsc = true;
}
var columnIndex = getColumnIndex(col.columnId);
if (columnIndex != null) {
headerColumnEls.eq(columnIndex)
.addClass("slick-header-column-sorted")
.find(".slick-sort-indicator")
.addClass(col.sortAsc ? "slick-sort-indicator-asc" : "slick-sort-indicator-desc");
if (numberCols) {
headerColumnEls.eq(columnIndex)
.find(".slick-sort-indicator-numbered")
.text(i+1);
}
}
});
}
function getSortColumns() {
return sortColumns;
}
function handleSelectedRangesChanged(e, ranges) {
var previousSelectedRows = selectedRows.slice(0); // shallow copy previously selected rows for later comparison
selectedRows = [];
var hash = {};
for (var i = 0; i < ranges.length; i++) {
for (var j = ranges[i].fromRow; j <= ranges[i].toRow; j++) {
if (!hash[j]) { // prevent duplicates
selectedRows.push(j);
hash[j] = {};
}
for (var k = ranges[i].fromCell; k <= ranges[i].toCell; k++) {
if (canCellBeSelected(j, k)) {
hash[j][columns[k].id] = options.selectedCellCssClass;
}
}
}
}
setCellCssStyles(options.selectedCellCssClass, hash);
if (simpleArrayEquals(previousSelectedRows, selectedRows)) {
trigger(self.onSelectedRowsChanged, {rows: getSelectedRows(), previousSelectedRows: previousSelectedRows}, e);
}
}
// compare 2 simple arrays (integers or strings only, do not use to compare object arrays)
function simpleArrayEquals(arr1, arr2) {
return Array.isArray(arr1) && Array.isArray(arr2) && arr2.sort().toString() !== arr1.sort().toString();
}
function getColumns() {
return columns;
}
function updateColumnCaches() {
// Pre-calculate cell boundaries.
columnPosLeft = [];
columnPosRight = [];
var x = 0;
for (var i = 0, ii = columns.length; i < ii; i++) {
columnPosLeft[i] = x;
columnPosRight[i] = x + columns[i].width;
if (options.frozenColumn == i) {
x = 0;
} else {
x += columns[i].width;
}
}
}
function updateColumnProps() {
columnsById = {};
for (var i = 0; i < columns.length; i++) {
if (columns[i].width) { columns[i].widthRequest = columns[i].width; }
var m = columns[i] = $.extend({}, columnDefaults, columns[i]);
m.autoSize = $.extend({}, columnAutosizeDefaults, m.autoSize);
columnsById[m.id] = i;
if (m.minWidth && m.width < m.minWidth) {
m.width = m.minWidth;
}
if (m.maxWidth && m.width > m.maxWidth) {
m.width = m.maxWidth;
}
if (!m.resizable) {
// there is difference between user resizable and autoWidth resizable
//m.autoSize.autosizeMode = Slick.ColAutosizeMode.Locked;
}
}
}
function setColumns(columnDefinitions) {
var _treeColumns = new Slick.TreeColumns(columnDefinitions);
if (_treeColumns.hasDepth()) {
treeColumns = _treeColumns;
columns = treeColumns.extractColumns();
} else {
columns = columnDefinitions;
}
updateColumnProps();
updateColumnCaches();
if (initialized) {
setPaneVisibility();
setOverflow();
invalidateAllRows();
createColumnHeaders();
createColumnGroupHeaders();
createColumnFooter();
removeCssRules();
createCssRules();
resizeCanvas();
updateCanvasWidth();
applyColumnHeaderWidths();
applyColumnWidths();
handleScroll();
}
}
function getOptions() {
return options;
}
function setOptions(args, suppressRender, suppressColumnSet) {
if (!getEditorLock().commitCurrentEdit()) {
return;
}
makeActiveCellNormal();
if (args.showColumnHeader !== undefined) {
setColumnHeaderVisibility(args.showColumnHeader);
}
if (options.enableAddRow !== args.enableAddRow) {
invalidateRow(getDataLength());
}
var originalOptions = $.extend(true, {}, options);
options = $.extend(options, args);
trigger(self.onSetOptions, { "optionsBefore": originalOptions, "optionsAfter": options });
validateAndEnforceOptions();
$viewport.css("overflow-y", options.autoHeight ? "hidden" : "auto");
if (!suppressRender) {
render();
}
setFrozenOptions();
setScroller();
zombieRowNodeFromLastMouseWheelEvent = null;
if (!suppressColumnSet) {
setColumns(treeColumns.extractColumns());
}
}
function validateAndEnforceOptions() {
if (options.autoHeight) {
options.leaveSpaceForNewRows = false;
}
if (options.forceFitColumns) {
options.autosizeColsMode = Slick.GridAutosizeColsMode.LegacyForceFit;
console.log("forceFitColumns option is deprecated - use autosizeColsMode");
}
}
function setData(newData, scrollToTop) {
data = newData;
invalidateAllRows();
updateRowCount();
if (scrollToTop) {
scrollTo(0);
}
}
function getData() {
return data;
}
function getDataLength() {
if (data.getLength) {
return data.getLength();
} else {
return data && data.length || 0;
}
}
function getDataLengthIncludingAddNew() {
return getDataLength() + (!options.enableAddRow ? 0
: (!pagingActive || pagingIsLastPage ? 1 : 0)
);
}
function getDataItem(i) {
if (data.getItem) {
return data.getItem(i);
} else {
return data[i];
}
}
function getTopPanel() {
return $topPanel[0];
}
function setTopPanelVisibility(visible, animate) {
var animated = (animate === false) ? false : true;
if (options.showTopPanel != visible) {
options.showTopPanel = visible;
if (visible) {
if (animated) {
$topPanelScroller.slideDown("fast", resizeCanvas);
} else {
$topPanelScroller.show();
resizeCanvas();
}
} else {
if (animated) {
$topPanelScroller.slideUp("fast", resizeCanvas);
} else {
$topPanelScroller.hide();
resizeCanvas();
}
}
}
}
function setHeaderRowVisibility(visible, animate) {
var animated = (animate === false) ? false : true;
if (options.showHeaderRow != visible) {
options.showHeaderRow = visible;
if (visible) {
if (animated) {
$headerRowScroller.slideDown("fast", resizeCanvas);
} else {
$headerRowScroller.show();
resizeCanvas();
}
} else {
if (animated) {
$headerRowScroller.slideUp("fast", resizeCanvas);
} else {
$headerRowScroller.hide();
resizeCanvas();
}
}
}
}
function setColumnHeaderVisibility(visible, animate) {
if (options.showColumnHeader != visible) {
options.showColumnHeader = visible;
if (visible) {
if (animate) {
$headerScroller.slideDown("fast", resizeCanvas);
} else {
$headerScroller.show();
resizeCanvas();
}
} else {
if (animate) {
$headerScroller.slideUp("fast", resizeCanvas);
} else {
$headerScroller.hide();
resizeCanvas();
}
}
}
}
function setFooterRowVisibility(visible, animate) {
var animated = (animate === false) ? false : true;
if (options.showFooterRow != visible) {
options.showFooterRow = visible;
if (visible) {
if (animated) {
$footerRowScroller.slideDown("fast", resizeCanvas);
} else {
$footerRowScroller.show();
resizeCanvas();
}
} else {
if (animated) {
$footerRowScroller.slideUp("fast", resizeCanvas);
} else {
$footerRowScroller.hide();
resizeCanvas();
}
}
}
}
function setPreHeaderPanelVisibility(visible, animate) {
var animated = (animate === false) ? false : true;
if (options.showPreHeaderPanel != visible) {
options.showPreHeaderPanel = visible;
if (visible) {
if (animated) {
$preHeaderPanelScroller.slideDown("fast", resizeCanvas);
} else {
$preHeaderPanelScroller.show();
resizeCanvas();
}
} else {
if (animated) {
$preHeaderPanelScroller.slideUp("fast", resizeCanvas);
} else {
$preHeaderPanelScroller.hide();
resizeCanvas();
}
}
}
}
function getContainerNode() {
return $container.get(0);
}
//////////////////////////////////////////////////////////////////////////////////////////////
// Rendering / Scrolling
function getRowTop(row) {
return options.rowHeight * row - offset;
}
function getRowFromPosition(y) {
return Math.floor((y + offset) / options.rowHeight);
}
function scrollTo(y) {
y = Math.max(y, 0);
y = Math.min(y, th - $viewportScrollContainerY.height() + ((viewportHasHScroll || hasFrozenColumns()) ? scrollbarDimensions.height : 0));
var oldOffset = offset;
page = Math.min(n - 1, Math.floor(y / ph));
offset = Math.round(page * cj);
var newScrollTop = y - offset;
if (offset != oldOffset) {
var range = getVisibleRange(newScrollTop);
cleanupRows(range);
updateRowPositions();
}
if (prevScrollTop != newScrollTop) {
vScrollDir = (prevScrollTop + oldOffset < newScrollTop + offset) ? 1 : -1;
lastRenderedScrollTop = ( scrollTop = prevScrollTop = newScrollTop );
if (hasFrozenColumns()) {
$viewportTopL[0].scrollTop = newScrollTop;
}
if (hasFrozenRows) {
$viewportBottomL[0].scrollTop = $viewportBottomR[0].scrollTop = newScrollTop;
}
$viewportScrollContainerY[0].scrollTop = newScrollTop;
trigger(self.onViewportChanged, {});
}
}
function defaultFormatter(row, cell, value, columnDef, dataContext, grid) {
if (value == null) {
return "";
} else {
return (value + "").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">");
}
}
function getFormatter(row, column) {
var rowMetadata = data.getItemMetadata && data.getItemMetadata(row);
// look up by id, then index
var columnOverrides = rowMetadata &&
rowMetadata.columns &&
(rowMetadata.columns[column.id] || rowMetadata.columns[getColumnIndex(column.id)]);
return (columnOverrides && columnOverrides.formatter) ||
(rowMetadata && rowMetadata.formatter) ||
column.formatter ||
(options.formatterFactory && options.formatterFactory.getFormatter(column)) ||
options.defaultFormatter;
}
function callFormatter( row, cell, value, m, item, grid ) {
var result;
// pass metadata to formatter
var metadata = data.getItemMetadata && data.getItemMetadata(row);
metadata = metadata && metadata.columns;
if( metadata ) {
var columnData = metadata[m.id] || metadata[cell];
result = getFormatter(row, m)(row, cell, value, m, item, columnData );
}
else {
result = getFormatter(row, m)(row, cell, value, m, item);
}
return result;
}
function getEditor(row, cell) {
var column = columns[cell];
var rowMetadata = data.getItemMetadata && data.getItemMetadata(row);
var columnMetadata = rowMetadata && rowMetadata.columns;
if (columnMetadata && columnMetadata[column.id] && columnMetadata[column.id].editor !== undefined) {
return columnMetadata[column.id].editor;
}
if (columnMetadata && columnMetadata[cell] && columnMetadata[cell].editor !== undefined) {
return columnMetadata[cell].editor;
}
return column.editor || (options.editorFactory && options.editorFactory.getEditor(column));
}
function getDataItemValueForColumn(item, columnDef) {
if (options.dataItemColumnValueExtractor) {
return options.dataItemColumnValueExtractor(item, columnDef);
}
return item[columnDef.field];
}
function appendRowHtml(stringArrayL, stringArrayR, row, range, dataLength) {
var d = getDataItem(row);
var dataLoading = row < dataLength && !d;
var rowCss = "slick-row" +
(hasFrozenRows && row <= options.frozenRow? ' frozen': '') +
(dataLoading ? " loading" : "") +
(row === activeRow && options.showCellSelection ? " active" : "") +
(row % 2 == 1 ? " odd" : " even");
if (!d) {
rowCss += " " + options.addNewRowCssClass;
}
var metadata = data.getItemMetadata && data.getItemMetadata(row);
if (metadata && metadata.cssClasses) {
rowCss += " " + metadata.cssClasses;
}
var frozenRowOffset = getFrozenRowOffset(row);
var rowHtml = "<div class='ui-widget-content " + rowCss + "' style='top:"
+ (getRowTop(row) - frozenRowOffset )
+ "px'>";
stringArrayL.push(rowHtml);
if (hasFrozenColumns()) {
stringArrayR.push(rowHtml);
}
var colspan, m;
for (var i = 0, ii = columns.length; i < ii; i++) {
m = columns[i];
colspan = 1;
if (metadata && metadata.columns) {
var columnData = metadata.columns[m.id] || metadata.columns[i];
colspan = (columnData && columnData.colspan) || 1;
if (colspan === "*") {
colspan = ii - i;
}
}
// Do not render cells outside of the viewport.
if (columnPosRight[Math.min(ii - 1, i + colspan - 1)] > range.leftPx) {
if (!m.alwaysRenderColumn && columnPosLeft[i] > range.rightPx) {
// All columns to the right are outside the range.
break;
}
if (hasFrozenColumns() && ( i > options.frozenColumn )) {
appendCellHtml(stringArrayR, row, i, colspan, d);
} else {
appendCellHtml(stringArrayL, row, i, colspan, d);
}
} else if (m.alwaysRenderColumn || (hasFrozenColumns() && i <= options.frozenColumn)) {
appendCellHtml(stringArrayL, row, i, colspan, d);
}
if (colspan > 1) {
i += (colspan - 1);
}
}
stringArrayL.push("</div>");
if (hasFrozenColumns()) {
stringArrayR.push("</div>");
}
}
function appendCellHtml(stringArray, row, cell, colspan, item) {
// stringArray: stringBuilder containing the HTML parts
// row, cell: row and column index
// colspan: HTML colspan
// item: grid data for row
var m = columns[cell];
var cellCss = "slick-cell l" + cell + " r" + Math.min(columns.length - 1, cell + colspan - 1) +
(m.cssClass ? " " + m.cssClass : "");
if (hasFrozenColumns() && cell <= options.frozenColumn) {
cellCss += (" frozen");
}
if (row === activeRow && cell === activeCell && options.showCellSelection) {
cellCss += (" active");
}
// TODO: merge them together in the setter
for (var key in cellCssClasses) {
if (cellCssClasses[key][row] && cellCssClasses[key][row][m.id]) {
cellCss += (" " + cellCssClasses[key][row][m.id]);
}
}
var value = null, formatterResult = '';
if (item) {
value = getDataItemValueForColumn(item, m);
formatterResult = getFormatter(row, m)(row, cell, value, m, item, self);
if (formatterResult === null || formatterResult === undefined) { formatterResult = ''; }
}
// get addl css class names from object type formatter return and from string type return of onBeforeAppendCell
var addlCssClasses = trigger(self.onBeforeAppendCell, { row: row, cell: cell, value: value, dataContext: item }) || '';
addlCssClasses += (formatterResult && formatterResult.addClasses ? (addlCssClasses ? ' ' : '') + formatterResult.addClasses : '');
var toolTip = formatterResult && formatterResult.toolTip ? "title='" + formatterResult.toolTip + "'" : '';
var customAttrStr = '';
if(m.hasOwnProperty('cellAttrs') && m.cellAttrs instanceof Object) {
for (var key in m.cellAttrs) {
if (m.cellAttrs.hasOwnProperty(key)) {
customAttrStr += ' ' + key + '="' + m.cellAttrs[key] + '" ';
}
}
}
stringArray.push("<div class='" + cellCss + (addlCssClasses ? ' ' + addlCssClasses : '') + "' " + toolTip + customAttrStr + ">");
// if there is a corresponding row (if not, this is the Add New row or this data hasn't been loaded yet)
if (item) {
stringArray.push(Object.prototype.toString.call(formatterResult) !== '[object Object]' ? formatterResult : formatterResult.text);
}
stringArray.push("</div>");
rowsCache[row].cellRenderQueue.push(cell);
rowsCache[row].cellColSpans[cell] = colspan;
}
function cleanupRows(rangeToKeep) {
for (var i in rowsCache) {
var removeFrozenRow = true;
if (hasFrozenRows
&& ( ( options.frozenBottom && i >= actualFrozenRow ) // Frozen bottom rows
|| ( !options.frozenBottom && i <= actualFrozenRow ) // Frozen top rows
)
) {
removeFrozenRow = false;
}
if (( ( i = parseInt(i, 10)) !== activeRow )
&& ( i < rangeToKeep.top || i > rangeToKeep.bottom )
&& ( removeFrozenRow )
) {
removeRowFromCache(i);
}
}
if (options.enableAsyncPostRenderCleanup) { startPostProcessingCleanup(); }
}
function invalidate() {
updateRowCount();
invalidateAllRows();
render();
}
function invalidateAllRows() {
if (currentEditor) {
makeActiveCellNormal();
}
for (var row in rowsCache) {
removeRowFromCache(row);
}
if (options.enableAsyncPostRenderCleanup) { startPostProcessingCleanup(); }
}
function queuePostProcessedRowForCleanup(cacheEntry, postProcessedRow, rowIdx) {
postProcessgroupId++;
// store and detach node for later async cleanup
for (var columnIdx in postProcessedRow) {
if (postProcessedRow.hasOwnProperty(columnIdx)) {
postProcessedCleanupQueue.push({
actionType: 'C',
groupId: postProcessgroupId,
node: cacheEntry.cellNodesByColumnIdx[ columnIdx | 0],
columnIdx: columnIdx | 0,
rowIdx: rowIdx
});
}
}
postProcessedCleanupQueue.push({
actionType: 'R',
groupId: postProcessgroupId,
node: cacheEntry.rowNode
});
$(cacheEntry.rowNode).detach();
}
function queuePostProcessedCellForCleanup(cellnode, columnIdx, rowIdx) {
postProcessedCleanupQueue.push({
actionType: 'C',
groupId: postProcessgroupId,
node: cellnode,
columnIdx: columnIdx,
rowIdx: rowIdx
});
$(cellnode).detach();
}
function removeRowFromCache(row) {
var cacheEntry = rowsCache[row];
if (!cacheEntry) {
return;
}
if (rowNodeFromLastMouseWheelEvent == cacheEntry.rowNode[0]
|| (hasFrozenColumns() && rowNodeFromLastMouseWheelEvent == cacheEntry.rowNode[1])) {
cacheEntry.rowNode.hide();
zombieRowNodeFromLastMouseWheelEvent = cacheEntry.rowNode;
} else {
cacheEntry.rowNode.each(function() {
this.parentElement.removeChild(this);
});
}
delete rowsCache[row];
delete postProcessedRows[row];
renderedRows--;
counter_rows_removed++;
}
function invalidateRows(rows) {
var i, rl;
if (!rows || !rows.length) {
return;
}
vScrollDir = 0;
rl = rows.length;
for (i = 0; i < rl; i++) {
if (currentEditor && activeRow === rows[i]) {
makeActiveCellNormal();
}
if (rowsCache[rows[i]]) {
removeRowFromCache(rows[i]);
}
}
if (options.enableAsyncPostRenderCleanup) { startPostProcessingCleanup(); }
}
function invalidateRow(row) {
if (!row && row !== 0) { return; }
invalidateRows([row]);
}
function applyFormatResultToCellNode(formatterResult, cellNode, suppressRemove) {
if (formatterResult === null || formatterResult === undefined) { formatterResult = ''; }
if (Object.prototype.toString.call(formatterResult) !== '[object Object]') {
cellNode.innerHTML = formatterResult;
return;
}
cellNode.innerHTML = formatterResult.text;
if (formatterResult.removeClasses && !suppressRemove) {
$(cellNode).removeClass(formatterResult.removeClasses);
}
if (formatterResult.addClasses) {
$(cellNode).addClass(formatterResult.addClasses);
}
if (formatterResult.toolTip) {
$(cellNode).attr("title", formatterResult.toolTip);
}
}
function updateCell(row, cell) {
var cellNode = getCellNode(row, cell);
if (!cellNode) {
return;
}
var m = columns[cell], d = getDataItem(row);
if (currentEditor && activeRow === row && activeCell === cell) {
currentEditor.loadValue(d);
} else {
var formatterResult = d ? getFormatter(row, m)(row, cell, getDataItemValueForColumn(d, m), m, d, self) : "";
applyFormatResultToCellNode(formatterResult, cellNode);
invalidatePostProcessingResults(row);
}
}
function updateRow(row) {
var cacheEntry = rowsCache[row];
if (!cacheEntry) {
return;
}
ensureCellNodesInRowsCache(row);
var formatterResult, d = getDataItem(row);
for (var columnIdx in cacheEntry.cellNodesByColumnIdx) {
if (!cacheEntry.cellNodesByColumnIdx.hasOwnProperty(columnIdx)) {
continue;
}
columnIdx = columnIdx | 0;
var m = columns[columnIdx],
node = cacheEntry.cellNodesByColumnIdx[columnIdx][0];
if (row === activeRow && columnIdx === activeCell && currentEditor) {
currentEditor.loadValue(d);
} else if (d) {
formatterResult = getFormatter(row, m)(row, columnIdx, getDataItemValueForColumn(d, m), m, d, self);
applyFormatResultToCellNode(formatterResult, node);
} else {
node.innerHTML = "";
}
}
invalidatePostProcessingResults(row);
}
function getViewportHeight() {
if (!options.autoHeight || options.frozenColumn != -1) {
topPanelH = ( options.showTopPanel ) ? options.topPanelHeight + getVBoxDelta($topPanelScroller) : 0;
headerRowH = ( options.showHeaderRow ) ? options.headerRowHeight + getVBoxDelta($headerRowScroller) : 0;
footerRowH = ( options.showFooterRow ) ? options.footerRowHeight + getVBoxDelta($footerRowScroller) : 0;
}
if (options.autoHeight) {
var fullHeight = $paneHeaderL.outerHeight();
fullHeight += ( options.showHeaderRow ) ? options.headerRowHeight + getVBoxDelta($headerRowScroller) : 0;
fullHeight += ( options.showFooterRow ) ? options.footerRowHeight + getVBoxDelta($footerRowScroller) : 0;
fullHeight += (getCanvasWidth() > viewportW) ? scrollbarDimensions.height : 0;
viewportH = options.rowHeight
* getDataLengthIncludingAddNew()
+ ( ( options.frozenColumn == -1 ) ? fullHeight : 0 );
} else {
var columnNamesH = ( options.showColumnHeader ) ? parseFloat($.css($headerScroller[0], "height"))
+ getVBoxDelta($headerScroller) : 0;
var preHeaderH = (options.createPreHeaderPanel && options.showPreHeaderPanel) ? options.preHeaderPanelHeight + getVBoxDelta($preHeaderPanelScroller) : 0;
viewportH = parseFloat($.css($container[0], "height", true))
- parseFloat($.css($container[0], "paddingTop", true))
- parseFloat($.css($container[0], "paddingBottom", true))
- columnNamesH
- topPanelH
- headerRowH
- footerRowH
- preHeaderH;
}
numVisibleRows = Math.ceil(viewportH / options.rowHeight);
return viewportH;
}
function getViewportWidth() {
viewportW = parseFloat($container.width());
}
function resizeCanvas() {
if (!initialized) { return; }
paneTopH = 0;
paneBottomH = 0;
viewportTopH = 0;
viewportBottomH = 0;
getViewportWidth();
getViewportHeight();
// Account for Frozen Rows
if (hasFrozenRows) {
if (options.frozenBottom) {
paneTopH = viewportH - frozenRowsHeight - scrollbarDimensions.height;
paneBottomH = frozenRowsHeight + scrollbarDimensions.height;
} else {
paneTopH = frozenRowsHeight;
paneBottomH = viewportH - frozenRowsHeight;
}
} else {
paneTopH = viewportH;
}
// The top pane includes the top panel and the header row
paneTopH += topPanelH + headerRowH + footerRowH;
if (hasFrozenColumns() && options.autoHeight) {
paneTopH += scrollbarDimensions.height;
}
// The top viewport does not contain the top panel or header row
viewportTopH = paneTopH - topPanelH - headerRowH - footerRowH;
if (options.autoHeight) {
if (hasFrozenColumns()) {
$container.height(
paneTopH
+ parseFloat($.css($headerScrollerL[0], "height"))
);
}
$paneTopL.css('position', 'relative');
}
$paneTopL.css({
'top': $paneHeaderL.height(), 'height': paneTopH
});
var paneBottomTop = $paneTopL.position().top
+ paneTopH;
if (!options.autoHeight) {
$viewportTopL.height(viewportTopH);
}
if (hasFrozenColumns()) {
$paneTopR.css({
'top': $paneHeaderL.height(), 'height': paneTopH
});
$viewportTopR.height(viewportTopH);
if (hasFrozenRows) {
$paneBottomL.css({
'top': paneBottomTop, 'height': paneBottomH
});
$paneBottomR.css({
'top': paneBottomTop, 'height': paneBottomH
});
$viewportBottomR.height(paneBottomH);
}
} else {
if (hasFrozenRows) {
$paneBottomL.css({
'width': '100%', 'height': paneBottomH
});
$paneBottomL.css('top', paneBottomTop);
}
}
if (hasFrozenRows) {
$viewportBottomL.height(paneBottomH);
if (options.frozenBottom) {
$canvasBottomL.height(frozenRowsHeight);
if (hasFrozenColumns()) {
$canvasBottomR.height(frozenRowsHeight);
}
} else {
$canvasTopL.height(frozenRowsHeight);
if (hasFrozenColumns()) {
$canvasTopR.height(frozenRowsHeight);
}
}
} else {
$viewportTopR.height(viewportTopH);
}
if (!scrollbarDimensions || !scrollbarDimensions.width) {
scrollbarDimensions = measureScrollbar();
}
if (options.autosizeColsMode === Slick.GridAutosizeColsMode.LegacyForceFit) {
autosizeColumns();
}
updateRowCount();
handleScroll();
// Since the width has changed, force the render() to reevaluate virtually rendered cells.
lastRenderedScrollLeft = -1;
render();
}
function updatePagingStatusFromView( pagingInfo ) {
pagingActive = (pagingInfo.pageSize !== 0);
pagingIsLastPage = (pagingInfo.pageNum == pagingInfo.totalPages - 1);
}
function updateRowCount() {
if (!initialized) { return; }
var dataLength = getDataLength();
var dataLengthIncludingAddNew = getDataLengthIncludingAddNew();
var numberOfRows = 0;
var oldH = ( hasFrozenRows && !options.frozenBottom ) ? $canvasBottomL.height() : $canvasTopL.height();
if (hasFrozenRows ) {
var numberOfRows = getDataLength() - options.frozenRow;
} else {
var numberOfRows = dataLengthIncludingAddNew + (options.leaveSpaceForNewRows ? numVisibleRows - 1 : 0);
}
var tempViewportH = $viewportScrollContainerY.height();
var oldViewportHasVScroll = viewportHasVScroll;
// with autoHeight, we do not need to accommodate the vertical scroll bar
viewportHasVScroll = options.alwaysShowVerticalScroll || !options.autoHeight && (numberOfRows * options.rowHeight > tempViewportH);
makeActiveCellNormal();
// remove the rows that are now outside of the data range
// this helps avoid redundant calls to .removeRow() when the size of the data decreased by thousands of rows
var r1 = dataLength - 1;
for (var i in rowsCache) {
if (i > r1) {
removeRowFromCache(i);
}
}
if (options.enableAsyncPostRenderCleanup) { startPostProcessingCleanup(); }
if (activeCellNode && activeRow > r1) {
resetActiveCell();
}
var oldH = h;
if (options.autoHeight) {
h = options.rowHeight * numberOfRows;
} else {
th = Math.max(options.rowHeight * numberOfRows, tempViewportH - scrollbarDimensions.height);
if (th < maxSupportedCssHeight) {
// just one page
h = ph = th;
n = 1;
cj = 0;
} else {
// break into pages
h = maxSupportedCssHeight;
ph = h / 100;
n = Math.floor(th / ph);
cj = (th - h) / (n - 1);
}
}
if (h !== oldH) {
if (hasFrozenRows && !options.frozenBottom) {
$canvasBottomL.css("height", h);
if (hasFrozenColumns()) {
$canvasBottomR.css("height", h);
}
} else {
$canvasTopL.css("height", h);
$canvasTopR.css("height", h);
}
scrollTop = $viewportScrollContainerY[0].scrollTop;
}
var oldScrollTopInRange = (scrollTop + offset <= th - tempViewportH);
if (th == 0 || scrollTop == 0) {
page = offset = 0;
} else if (oldScrollTopInRange) {
// maintain virtual position
scrollTo(scrollTop + offset);
} else {
// scroll to bottom
scrollTo(th - tempViewportH);
}
if (h != oldH && options.autoHeight) {
resizeCanvas();
}
if (options.autosizeColsMode === Slick.GridAutosizeColsMode.LegacyForceFit && oldViewportHasVScroll != viewportHasVScroll) {
autosizeColumns();
}
updateCanvasWidth(false);
}
function getVisibleRange(viewportTop, viewportLeft) {
if (viewportTop == null) {
viewportTop = scrollTop;
}
if (viewportLeft == null) {
viewportLeft = scrollLeft;
}
return {
top: getRowFromPosition(viewportTop),
bottom: getRowFromPosition(viewportTop + viewportH) + 1,
leftPx: viewportLeft,
rightPx: viewportLeft + viewportW
};
}
function getRenderedRange(viewportTop, viewportLeft) {
var range = getVisibleRange(viewportTop, viewportLeft);
var buffer = Math.round(viewportH / options.rowHeight);
var minBuffer = options.minRowBuffer;
if (vScrollDir == -1) {
range.top -= buffer;
range.bottom += minBuffer;
} else if (vScrollDir == 1) {
range.top -= minBuffer;
range.bottom += buffer;
} else {
range.top -= minBuffer;
range.bottom += minBuffer;
}
range.top = Math.max(0, range.top);
range.bottom = Math.min(getDataLengthIncludingAddNew() - 1, range.bottom);
range.leftPx -= viewportW;
range.rightPx += viewportW;
range.leftPx = Math.max(0, range.leftPx);
range.rightPx = Math.min(canvasWidth, range.rightPx);
return range;
}
function ensureCellNodesInRowsCache(row) {
var cacheEntry = rowsCache[row];
if (cacheEntry) {
if (cacheEntry.cellRenderQueue.length) {
var $lastNode = cacheEntry.rowNode.children().last();
while (cacheEntry.cellRenderQueue.length) {
var columnIdx = cacheEntry.cellRenderQueue.pop();
cacheEntry.cellNodesByColumnIdx[columnIdx] = $lastNode;
$lastNode = $lastNode.prev();
// Hack to retrieve the frozen columns because
if ($lastNode.length === 0) {
$lastNode = $(cacheEntry.rowNode[0]).children().last();
}
}
}
}
}
function cleanUpCells(range, row) {
// Ignore frozen rows
if (hasFrozenRows
&& ( ( options.frozenBottom && row > actualFrozenRow ) // Frozen bottom rows
|| ( row <= actualFrozenRow ) // Frozen top rows
)
) {
return;
}
var totalCellsRemoved = 0;
var cacheEntry = rowsCache[row];
// Remove cells outside the range.
var cellsToRemove = [];
for (var i in cacheEntry.cellNodesByColumnIdx) {
// I really hate it when people mess with Array.prototype.
if (!cacheEntry.cellNodesByColumnIdx.hasOwnProperty(i)) {
continue;
}
// This is a string, so it needs to be cast back to a number.
i = i | 0;
// Ignore frozen columns
if (i <= options.frozenColumn) {
continue;
}
// Ignore alwaysRenderedColumns
if (Array.isArray(columns) && columns[i] && columns[i].alwaysRenderColumn){
continue;
}
var colspan = cacheEntry.cellColSpans[i];
if (columnPosLeft[i] > range.rightPx ||
columnPosRight[Math.min(columns.length - 1, i + colspan - 1)] < range.leftPx) {
if (!(row == activeRow && i == activeCell)) {
cellsToRemove.push(i);
}
}
}
var cellToRemove;
while ((cellToRemove = cellsToRemove.pop()) != null) {
cacheEntry.cellNodesByColumnIdx[cellToRemove][0].parentElement.removeChild(cacheEntry.cellNodesByColumnIdx[cellToRemove][0]);
delete cacheEntry.cellColSpans[cellToRemove];
delete cacheEntry.cellNodesByColumnIdx[cellToRemove];
if (postProcessedRows[row]) {
delete postProcessedRows[row][cellToRemove];
}
totalCellsRemoved++;
}
}
function cleanUpAndRenderCells(range) {
var cacheEntry;
var stringArray = [];
var processedRows = [];
var cellsAdded;
var totalCellsAdded = 0;
var colspan;
for (var row = range.top, btm = range.bottom; row <= btm; row++) {
cacheEntry = rowsCache[row];
if (!cacheEntry) {
continue;
}
// cellRenderQueue populated in renderRows() needs to be cleared first
ensureCellNodesInRowsCache(row);
cleanUpCells(range, row);
// Render missing cells.
cellsAdded = 0;
var metadata = data.getItemMetadata && data.getItemMetadata(row);
metadata = metadata && metadata.columns;
var d = getDataItem(row);
// TODO: shorten this loop (index? heuristics? binary search?)
for (var i = 0, ii = columns.length; i < ii; i++) {
// Cells to the right are outside the range.
if (columnPosLeft[i] > range.rightPx) {
break;
}
// Already rendered.
if ((colspan = cacheEntry.cellColSpans[i]) != null) {
i += (colspan > 1 ? colspan - 1 : 0);
continue;
}
colspan = 1;
if (metadata) {
var columnData = metadata[columns[i].id] || metadata[i];
colspan = (columnData && columnData.colspan) || 1;
if (colspan === "*") {
colspan = ii - i;
}
}
if (columnPosRight[Math.min(ii - 1, i + colspan - 1)] > range.leftPx) {
appendCellHtml(stringArray, row, i, colspan, d);
cellsAdded++;
}
i += (colspan > 1 ? colspan - 1 : 0);
}
if (cellsAdded) {
totalCellsAdded += cellsAdded;
processedRows.push(row);
}
}
if (!stringArray.length) {
return;
}
var x = document.createElement("div");
x.innerHTML = stringArray.join("");
var processedRow;
var node;
while ((processedRow = processedRows.pop()) != null) {
cacheEntry = rowsCache[processedRow];
var columnIdx;
while ((columnIdx = cacheEntry.cellRenderQueue.pop()) != null) {
node = x.lastChild;
if (hasFrozenColumns() && (columnIdx > options.frozenColumn)) {
cacheEntry.rowNode[1].appendChild(node);
} else {
cacheEntry.rowNode[0].appendChild(node);
}
cacheEntry.cellNodesByColumnIdx[columnIdx] = $(node);
}
}
}
function renderRows(range) {
var stringArrayL = [],
stringArrayR = [],
rows = [],
needToReselectCell = false,
dataLength = getDataLength();
for (var i = range.top, ii = range.bottom; i <= ii; i++) {
if (rowsCache[i] || ( hasFrozenRows && options.frozenBottom && i == getDataLength() )) {
continue;
}
renderedRows++;
rows.push(i);
// Create an entry right away so that appendRowHtml() can
// start populatating it.
rowsCache[i] = {
"rowNode": null,
// ColSpans of rendered cells (by column idx).
// Can also be used for checking whether a cell has been rendered.
"cellColSpans": [],
// Cell nodes (by column idx). Lazy-populated by ensureCellNodesInRowsCache().
"cellNodesByColumnIdx": [],
// Column indices of cell nodes that have been rendered, but not yet indexed in
// cellNodesByColumnIdx. These are in the same order as cell nodes added at the
// end of the row.
"cellRenderQueue": []
};
appendRowHtml(stringArrayL, stringArrayR, i, range, dataLength);
if (activeCellNode && activeRow === i) {
needToReselectCell = true;
}
counter_rows_rendered++;
}
if (!rows.length) { return; }
var x = document.createElement("div"),
xRight = document.createElement("div");
x.innerHTML = stringArrayL.join("");
xRight.innerHTML = stringArrayR.join("");
for (var i = 0, ii = rows.length; i < ii; i++) {
if (( hasFrozenRows ) && ( rows[i] >= actualFrozenRow )) {
if (hasFrozenColumns()) {
rowsCache[rows[i]].rowNode = $()
.add($(x.firstChild).appendTo($canvasBottomL))
.add($(xRight.firstChild).appendTo($canvasBottomR));
} else {
rowsCache[rows[i]].rowNode = $()
.add($(x.firstChild).appendTo($canvasBottomL));
}
} else if (hasFrozenColumns()) {
rowsCache[rows[i]].rowNode = $()
.add($(x.firstChild).appendTo($canvasTopL))
.add($(xRight.firstChild).appendTo($canvasTopR));
} else {
rowsCache[rows[i]].rowNode = $()
.add($(x.firstChild).appendTo($canvasTopL));
}
}
if (needToReselectCell) {
activeCellNode = getCellNode(activeRow, activeCell);
}
}
function startPostProcessing() {
if (!options.enableAsyncPostRender) {
return;
}
clearTimeout(h_postrender);
h_postrender = setTimeout(asyncPostProcessRows, options.asyncPostRenderDelay);
}
function startPostProcessingCleanup() {
if (!options.enableAsyncPostRenderCleanup) {
return;
}
clearTimeout(h_postrenderCleanup);
h_postrenderCleanup = setTimeout(asyncPostProcessCleanupRows, options.asyncPostRenderCleanupDelay);
}
function invalidatePostProcessingResults(row) {
// change status of columns to be re-rendered
for (var columnIdx in postProcessedRows[row]) {
if (postProcessedRows[row].hasOwnProperty(columnIdx)) {
postProcessedRows[row][columnIdx] = 'C';
}
}
postProcessFromRow = Math.min(postProcessFromRow, row);
postProcessToRow = Math.max(postProcessToRow, row);
startPostProcessing();
}
function updateRowPositions() {
for (var row in rowsCache) {
var rowNumber = row ? parseInt(row) : 0;
rowsCache[rowNumber].rowNode[0].style.top = getRowTop(rowNumber) + "px";
}
}
function render() {
if (!initialized) { return; }
scrollThrottle.dequeue();
var visible = getVisibleRange();
var rendered = getRenderedRange();
// remove rows no longer in the viewport
cleanupRows(rendered);
// add new rows & missing cells in existing rows
if (lastRenderedScrollLeft != scrollLeft) {
if ( hasFrozenRows ) {
var renderedFrozenRows = jQuery.extend(true, {}, rendered);
if (options.frozenBottom) {
renderedFrozenRows.top=actualFrozenRow;
renderedFrozenRows.bottom=getDataLength();
}
else {
renderedFrozenRows.top=0;
renderedFrozenRows.bottom=options.frozenRow;
}
cleanUpAndRenderCells(renderedFrozenRows);
}
cleanUpAndRenderCells(rendered);
}
// render missing rows
renderRows(rendered);
// Render frozen rows
if (hasFrozenRows) {
if (options.frozenBottom) {
renderRows({
top: actualFrozenRow, bottom: getDataLength() - 1, leftPx: rendered.leftPx, rightPx: rendered.rightPx
});
}
else {
renderRows({
top: 0, bottom: options.frozenRow - 1, leftPx: rendered.leftPx, rightPx: rendered.rightPx
});
}
}
postProcessFromRow = visible.top;
postProcessToRow = Math.min(getDataLengthIncludingAddNew() - 1, visible.bottom);
startPostProcessing();
lastRenderedScrollTop = scrollTop;
lastRenderedScrollLeft = scrollLeft;
h_render = null;
trigger(self.onRendered, { startRow: visible.top, endRow: visible.bottom, grid: self });
}
function handleHeaderScroll() {
handleElementScroll($headerScrollContainer[0]);
}
function handleHeaderRowScroll() {
var scrollLeft = $headerRowScrollContainer[0].scrollLeft;
if (scrollLeft != $viewportScrollContainerX[0].scrollLeft) {
$viewportScrollContainerX[0].scrollLeft = scrollLeft;
}
}
function handleFooterRowScroll() {
var scrollLeft = $footerRowScrollContainer[0].scrollLeft;
if (scrollLeft != $viewportScrollContainerX[0].scrollLeft) {
$viewportScrollContainerX[0].scrollLeft = scrollLeft;
}
}
function handlePreHeaderPanelScroll() {
handleElementScroll($preHeaderPanelScroller[0]);
}
function handleElementScroll(element) {
var scrollLeft = element.scrollLeft;
if (scrollLeft != $viewportScrollContainerX[0].scrollLeft) {
$viewportScrollContainerX[0].scrollLeft = scrollLeft;
}
}
function handleScroll() {
scrollTop = $viewportScrollContainerY[0].scrollTop;
scrollLeft = $viewportScrollContainerX[0].scrollLeft;
return _handleScroll(false);
}
function _handleScroll(isMouseWheel) {
var maxScrollDistanceY = $viewportScrollContainerY[0].scrollHeight - $viewportScrollContainerY[0].clientHeight;
var maxScrollDistanceX = $viewportScrollContainerY[0].scrollWidth - $viewportScrollContainerY[0].clientWidth;
// Protect against erroneous clientHeight/Width greater than scrollHeight/Width.
// Sometimes seen in Chrome.
maxScrollDistanceY = Math.max(0, maxScrollDistanceY);
maxScrollDistanceX = Math.max(0, maxScrollDistanceX);
// Ceiling the max scroll values
if (scrollTop > maxScrollDistanceY) {
scrollTop = maxScrollDistanceY;
}
if (scrollLeft > maxScrollDistanceX) {
scrollLeft = maxScrollDistanceX;
}
var vScrollDist = Math.abs(scrollTop - prevScrollTop);
var hScrollDist = Math.abs(scrollLeft - prevScrollLeft);
if (hScrollDist) {
prevScrollLeft = scrollLeft;
$viewportScrollContainerX[0].scrollLeft = scrollLeft;
$headerScrollContainer[0].scrollLeft = scrollLeft;
$topPanelScroller[0].scrollLeft = scrollLeft;
$headerRowScrollContainer[0].scrollLeft = scrollLeft;
if (options.createFooterRow) {
$footerRowScrollContainer[0].scrollLeft = scrollLeft;
}
if (options.createPreHeaderPanel) {
if (hasFrozenColumns()) {
$preHeaderPanelScrollerR[0].scrollLeft = scrollLeft;
} else {
$preHeaderPanelScroller[0].scrollLeft = scrollLeft;
}
}
if (hasFrozenColumns()) {
if (hasFrozenRows) {
$viewportTopR[0].scrollLeft = scrollLeft;
}
} else {
if (hasFrozenRows) {
$viewportTopL[0].scrollLeft = scrollLeft;
}
}
}
if (vScrollDist) {
vScrollDir = prevScrollTop < scrollTop ? 1 : -1;
prevScrollTop = scrollTop;
if (isMouseWheel) {
$viewportScrollContainerY[0].scrollTop = scrollTop;
}
if (hasFrozenColumns()) {
if (hasFrozenRows && !options.frozenBottom) {
$viewportBottomL[0].scrollTop = scrollTop;
} else {
$viewportTopL[0].scrollTop = scrollTop;
}
}
// switch virtual pages if needed
if (vScrollDist < viewportH) {
scrollTo(scrollTop + offset);
} else {
var oldOffset = offset;
if (h == viewportH) {
page = 0;
} else {
page = Math.min(n - 1, Math.floor(scrollTop * ((th - viewportH) / (h - viewportH)) * (1 / ph)));
}
offset = Math.round(page * cj);
if (oldOffset != offset) {
invalidateAllRows();
}
}
}
if (hScrollDist || vScrollDist) {
var dx = Math.abs(lastRenderedScrollLeft - scrollLeft);
var dy = Math.abs(lastRenderedScrollTop - scrollTop);
if (dx > 20 || dy > 20) {
// if rendering is forced or scrolling is small enough to be "easy", just render
if (options.forceSyncScrolling || (dy < viewportH && dx < viewportW)) {
render();
} else {
// otherwise, perform "difficult" renders at a capped frequency
scrollThrottle.enqueue();
}
trigger(self.onViewportChanged, {});
}
}
trigger(self.onScroll, {scrollLeft: scrollLeft, scrollTop: scrollTop});
if (hScrollDist || vScrollDist) return true;
return false;
}
/*
limits the frequency at which the provided action is executed.
call enqueue to execute the action - it will execute either immediately or, if it was executed less than minPeriod_ms in the past, as soon as minPeriod_ms has expired.
call dequeue to cancel any pending action.
*/
function ActionThrottle(action, minPeriod_ms) {
var blocked = false;
var queued = false;
function enqueue() {
if (!blocked) {
blockAndExecute();
} else {
queued = true;
}
}
function dequeue() {
queued = false;
}
function blockAndExecute() {
blocked = true;
setTimeout(unblock, minPeriod_ms);
action();
}
function unblock() {
if (queued) {
dequeue();
blockAndExecute();
} else {
blocked = false;
}
}
return {
enqueue: enqueue,
dequeue: dequeue
};
}
function asyncPostProcessRows() {
var dataLength = getDataLength();
while (postProcessFromRow <= postProcessToRow) {
var row = (vScrollDir >= 0) ? postProcessFromRow++ : postProcessToRow--;
var cacheEntry = rowsCache[row];
if (!cacheEntry || row >= dataLength) {
continue;
}
if (!postProcessedRows[row]) {
postProcessedRows[row] = {};
}
ensureCellNodesInRowsCache(row);
for (var columnIdx in cacheEntry.cellNodesByColumnIdx) {
if (!cacheEntry.cellNodesByColumnIdx.hasOwnProperty(columnIdx)) {
continue;
}
columnIdx = columnIdx | 0;
var m = columns[columnIdx];
var processedStatus = postProcessedRows[row][columnIdx]; // C=cleanup and re-render, R=rendered
if (m.asyncPostRender && processedStatus !== 'R') {
var node = cacheEntry.cellNodesByColumnIdx[columnIdx];
if (node) {
m.asyncPostRender(node, row, getDataItem(row), m, (processedStatus === 'C'));
}
postProcessedRows[row][columnIdx] = 'R';
}
}
h_postrender = setTimeout(asyncPostProcessRows, options.asyncPostRenderDelay);
return;
}
}
function asyncPostProcessCleanupRows() {
if (postProcessedCleanupQueue.length > 0) {
var groupId = postProcessedCleanupQueue[0].groupId;
// loop through all queue members with this groupID
while (postProcessedCleanupQueue.length > 0 && postProcessedCleanupQueue[0].groupId == groupId) {
var entry = postProcessedCleanupQueue.shift();
if (entry.actionType == 'R') {
$(entry.node).remove();
}
if (entry.actionType == 'C') {
var column = columns[entry.columnIdx];
if (column.asyncPostRenderCleanup && entry.node) {
// cleanup must also remove element
column.asyncPostRenderCleanup(entry.node, entry.rowIdx, column);
}
}
}
// call this function again after the specified delay
h_postrenderCleanup = setTimeout(asyncPostProcessCleanupRows, options.asyncPostRenderCleanupDelay);
}
}
function updateCellCssStylesOnRenderedRows(addedHash, removedHash) {
var node, columnId, addedRowHash, removedRowHash;
for (var row in rowsCache) {
removedRowHash = removedHash && removedHash[row];
addedRowHash = addedHash && addedHash[row];
if (removedRowHash) {
for (columnId in removedRowHash) {
if (!addedRowHash || removedRowHash[columnId] != addedRowHash[columnId]) {
node = getCellNode(row, getColumnIndex(columnId));
if (node) {
$(node).removeClass(removedRowHash[columnId]);
}
}
}
}
if (addedRowHash) {
for (columnId in addedRowHash) {
if (!removedRowHash || removedRowHash[columnId] != addedRowHash[columnId]) {
node = getCellNode(row, getColumnIndex(columnId));
if (node) {
$(node).addClass(addedRowHash[columnId]);
}
}
}
}
}
}
function addCellCssStyles(key, hash) {
if (cellCssClasses[key]) {
throw new Error("addCellCssStyles: cell CSS hash with key '" + key + "' already exists.");
}
cellCssClasses[key] = hash;
updateCellCssStylesOnRenderedRows(hash, null);
trigger(self.onCellCssStylesChanged, { "key": key, "hash": hash, "grid": self });
}
function removeCellCssStyles(key) {
if (!cellCssClasses[key]) {
return;
}
updateCellCssStylesOnRenderedRows(null, cellCssClasses[key]);
delete cellCssClasses[key];
trigger(self.onCellCssStylesChanged, { "key": key, "hash": null, "grid": self });
}
function setCellCssStyles(key, hash) {
var prevHash = cellCssClasses[key];
cellCssClasses[key] = hash;
updateCellCssStylesOnRenderedRows(hash, prevHash);
trigger(self.onCellCssStylesChanged, { "key": key, "hash": hash, "grid": self });
}
function getCellCssStyles(key) {
return cellCssClasses[key];
}
function flashCell(row, cell, speed) {
speed = speed || 100;
function toggleCellClass($cell, times) {
if (!times) {
return;
}
setTimeout(function () {
$cell.queue(function () {
$cell.toggleClass(options.cellFlashingCssClass).dequeue();
toggleCellClass($cell, times - 1);
});
}, speed);
}
if (rowsCache[row]) {
var $cell = $(getCellNode(row, cell));
toggleCellClass($cell, 4);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
// Interactivity
function handleMouseWheel(e, delta, deltaX, deltaY) {
var $rowNode = $(e.target).closest(".slick-row");
var rowNode = $rowNode[0];
if (rowNode != rowNodeFromLastMouseWheelEvent) {
var $gridCanvas = $rowNode.parents('.grid-canvas');
var left = $gridCanvas.hasClass('grid-canvas-left');
if (zombieRowNodeFromLastMouseWheelEvent && zombieRowNodeFromLastMouseWheelEvent[left? 0:1] != rowNode) {
var zombieRow = zombieRowNodeFromLastMouseWheelEvent[left || zombieRowNodeFromLastMouseWheelEvent.length == 1? 0:1];
zombieRow.parentElement.removeChild(zombieRow);
zombieRowNodeFromLastMouseWheelEvent = null;
}
rowNodeFromLastMouseWheelEvent = rowNode;
}
scrollTop = Math.max(0, $viewportScrollContainerY[0].scrollTop - (deltaY * options.rowHeight));
scrollLeft = $viewportScrollContainerX[0].scrollLeft + (deltaX * 10);
var handled = _handleScroll(true);
if (handled) e.preventDefault();
}
function handleDragInit(e, dd) {
var cell = getCellFromEvent(e);
if (!cell || !cellExists(cell.row, cell.cell)) {
return false;
}
var retval = trigger(self.onDragInit, dd, e);
if (e.isImmediatePropagationStopped()) {
return retval;
}
// if nobody claims to be handling drag'n'drop by stopping immediate propagation,
// cancel out of it
return false;
}
function handleDragStart(e, dd) {
var cell = getCellFromEvent(e);
if (!cell || !cellExists(cell.row, cell.cell)) {
return false;
}
var retval = trigger(self.onDragStart, dd, e);
if (e.isImmediatePropagationStopped()) {
return retval;
}
return false;
}
function handleDrag(e, dd) {
return trigger(self.onDrag, dd, e);
}
function handleDragEnd(e, dd) {
trigger(self.onDragEnd, dd, e);
}
function handleKeyDown(e) {
trigger(self.onKeyDown, {row: activeRow, cell: activeCell}, e);
var handled = e.isImmediatePropagationStopped();
var keyCode = Slick.keyCode;
if (!handled) {
if (!e.shiftKey && !e.altKey) {
if (options.editable && currentEditor && currentEditor.keyCaptureList) {
if (currentEditor.keyCaptureList.indexOf(e.which) > -1) {
return;
}
}
if (e.which == keyCode.HOME) {
handled = (e.ctrlKey) ? navigateTop() : navigateRowStart();
} else if (e.which == keyCode.END) {
handled = (e.ctrlKey) ? navigateBottom() : navigateRowEnd();
}
}
}
if (!handled) {
if (!e.shiftKey && !e.altKey && !e.ctrlKey) {
// editor may specify an array of keys to bubble
if (options.editable && currentEditor && currentEditor.keyCaptureList) {
if (currentEditor.keyCaptureList.indexOf( e.which ) > -1) {
return;
}
}
if (e.which == keyCode.ESCAPE) {
if (!getEditorLock().isActive()) {
return; // no editing mode to cancel, allow bubbling and default processing (exit without cancelling the event)
}
cancelEditAndSetFocus();
} else if (e.which == keyCode.PAGE_DOWN) {
navigatePageDown();
handled = true;
} else if (e.which == keyCode.PAGE_UP) {
navigatePageUp();
handled = true;
} else if (e.which == keyCode.LEFT) {
handled = navigateLeft();
} else if (e.which == keyCode.RIGHT) {
handled = navigateRight();
} else if (e.which == keyCode.UP) {
handled = navigateUp();
} else if (e.which == keyCode.DOWN) {
handled = navigateDown();
} else if (e.which == keyCode.TAB) {
handled = navigateNext();
} else if (e.which == keyCode.ENTER) {
if (options.editable) {
if (currentEditor) {
// adding new row
if (activeRow === getDataLength()) {
navigateDown();
} else {
commitEditAndSetFocus();
}
} else {
if (getEditorLock().commitCurrentEdit()) {
makeActiveCellEditable(undefined, undefined, e);
}
}
}
handled = true;
}
} else if (e.which == keyCode.TAB && e.shiftKey && !e.ctrlKey && !e.altKey) {
handled = navigatePrev();
}
}
if (handled) {
// the event has been handled so don't let parent element (bubbling/propagation) or browser (default) handle it
e.stopPropagation();
e.preventDefault();
try {
e.originalEvent.keyCode = 0; // prevent default behaviour for special keys in IE browsers (F3, F5, etc.)
}
// ignore exceptions - setting the original event's keycode throws access denied exception for "Ctrl"
// (hitting control key only, nothing else), "Shift" (maybe others)
catch (error) {
}
}
}
function handleClick(e) {
if (!currentEditor) {
// if this click resulted in some cell child node getting focus,
// don't steal it back - keyboard events will still bubble up
// IE9+ seems to default DIVs to tabIndex=0 instead of -1, so check for cell clicks directly.
if (e.target != document.activeElement || $(e.target).hasClass("slick-cell")) {
setFocus();
}
}
var cell = getCellFromEvent(e);
if (!cell || (currentEditor !== null && activeRow == cell.row && activeCell == cell.cell)) {
return;
}
trigger(self.onClick, {row: cell.row, cell: cell.cell}, e);
if (e.isImmediatePropagationStopped()) {
return;
}
// this optimisation causes trouble - MLeibman #329
//if ((activeCell != cell.cell || activeRow != cell.row) && canCellBeActive(cell.row, cell.cell)) {
if (canCellBeActive(cell.row, cell.cell)) {
if (!getEditorLock().isActive() || getEditorLock().commitCurrentEdit()) {
scrollRowIntoView(cell.row, false);
var preClickModeOn = (e.target && e.target.className === Slick.preClickClassName);
var column = columns[cell.cell];
var suppressActiveCellChangedEvent = !!(options.editable && column && column.editor && options.suppressActiveCellChangeOnEdit);
setActiveCellInternal(getCellNode(cell.row, cell.cell), null, preClickModeOn, suppressActiveCellChangedEvent, e);
}
}
}
function handleContextMenu(e) {
var $cell = $(e.target).closest(".slick-cell", $canvas);
if ($cell.length === 0) {
return;
}
// are we editing this cell?
if (activeCellNode === $cell[0] && currentEditor !== null) {
return;
}
trigger(self.onContextMenu, {}, e);
}
function handleDblClick(e) {
var cell = getCellFromEvent(e);
if (!cell || (currentEditor !== null && activeRow == cell.row && activeCell == cell.cell)) {
return;
}
trigger(self.onDblClick, {row: cell.row, cell: cell.cell}, e);
if (e.isImmediatePropagationStopped()) {
return;
}
if (options.editable) {
gotoCell(cell.row, cell.cell, true, e);
}
}
function handleHeaderMouseEnter(e) {
trigger(self.onHeaderMouseEnter, {
"column": $(this).data("column"),
"grid": self
}, e);
}
function handleHeaderMouseLeave(e) {
trigger(self.onHeaderMouseLeave, {
"column": $(this).data("column"),
"grid": self
}, e);
}
function handleHeaderContextMenu(e) {
var $header = $(e.target).closest(".slick-header-column", ".slick-header-columns");
var column = $header && $header.data("column");
trigger(self.onHeaderContextMenu, {column: column}, e);
}
function handleHeaderClick(e) {
if (columnResizeDragging) return;
var $header = $(e.target).closest(".slick-header-column", ".slick-header-columns");
var column = $header && $header.data("column");
if (column) {
trigger(self.onHeaderClick, {column: column}, e);
}
}
function handleFooterContextMenu(e) {
var $footer = $(e.target).closest(".slick-footerrow-column", ".slick-footerrow-columns");
var column = $footer && $footer.data("column");
trigger(self.onFooterContextMenu, {column: column}, e);
}
function handleFooterClick(e) {
var $footer = $(e.target).closest(".slick-footerrow-column", ".slick-footerrow-columns");
var column = $footer && $footer.data("column");
trigger(self.onFooterClick, {column: column}, e);
}
function handleMouseEnter(e) {
trigger(self.onMouseEnter, {}, e);
}
function handleMouseLeave(e) {
trigger(self.onMouseLeave, {}, e);
}
function cellExists(row, cell) {
return !(row < 0 || row >= getDataLength() || cell < 0 || cell >= columns.length);
}
function getCellFromPoint(x, y) {
var row = getRowFromPosition(y);
var cell = 0;
var w = 0;
for (var i = 0; i < columns.length && w < x; i++) {
w += columns[i].width;
cell++;
}
if (cell < 0) {
cell = 0;
}
return {row: row, cell: cell - 1};
}
function getCellFromNode(cellNode) {
// read column number from .l<columnNumber> CSS class
var cls = /l\d+/.exec(cellNode.className);
if (!cls) {
throw new Error("getCellFromNode: cannot get cell - " + cellNode.className);
}
return parseInt(cls[0].substr(1, cls[0].length - 1), 10);
}
function getRowFromNode(rowNode) {
for (var row in rowsCache) {
for (var i in rowsCache[row].rowNode) {
if (rowsCache[row].rowNode[i] === rowNode)
return (row ? parseInt(row) : 0);
}
}
return null;
}
function getFrozenRowOffset(row) {
var offset =
( hasFrozenRows )
? ( options.frozenBottom )
? ( row >= actualFrozenRow )
? ( h < viewportTopH )
? ( actualFrozenRow * options.rowHeight )
: h
: 0
: ( row >= actualFrozenRow )
? frozenRowsHeight
: 0
: 0;
return offset;
}
function getCellFromEvent(e) {
var row, cell;
var $cell = $(e.target).closest(".slick-cell", $canvas);
if (!$cell.length) {
return null;
}
row = getRowFromNode($cell[0].parentNode);
if (hasFrozenRows) {
var c = $cell.parents('.grid-canvas').offset();
var rowOffset = 0;
var isBottom = $cell.parents('.grid-canvas-bottom').length;
if (isBottom) {
rowOffset = ( options.frozenBottom ) ? $canvasTopL.height() : frozenRowsHeight;
}
row = getCellFromPoint(e.clientX - c.left, e.clientY - c.top + rowOffset + $(document).scrollTop()).row;
}
cell = getCellFromNode($cell[0]);
if (row == null || cell == null) {
return null;
} else {
return {
"row": row,
"cell": cell
};
}
}
function getCellNodeBox(row, cell) {
if (!cellExists(row, cell)) {
return null;
}
var frozenRowOffset = getFrozenRowOffset(row);
var y1 = getRowTop(row) - frozenRowOffset;
var y2 = y1 + options.rowHeight - 1;
var x1 = 0;
for (var i = 0; i < cell; i++) {
x1 += columns[i].width;
if (options.frozenColumn == i) {
x1 = 0;
}
}
var x2 = x1 + columns[cell].width;
return {
top: y1,
left: x1,
bottom: y2,
right: x2
};
}
//////////////////////////////////////////////////////////////////////////////////////////////
// Cell switching
function resetActiveCell() {
setActiveCellInternal(null, false);
}
function setFocus() {
if (tabbingDirection == -1) {
$focusSink[0].focus();
} else {
$focusSink2[0].focus();
}
}
function scrollCellIntoView(row, cell, doPaging) {
scrollRowIntoView(row, doPaging);
if (cell <= options.frozenColumn) {
return;
}
var colspan = getColspan(row, cell);
internalScrollColumnIntoView(columnPosLeft[cell], columnPosRight[cell + (colspan > 1 ? colspan - 1 : 0)]);
}
function internalScrollColumnIntoView(left, right) {
var scrollRight = scrollLeft + $viewportScrollContainerX.width();
if (left < scrollLeft) {
$viewportScrollContainerX.scrollLeft(left);
handleScroll();
render();
} else if (right > scrollRight) {
$viewportScrollContainerX.scrollLeft(Math.min(left, right - $viewportScrollContainerX[0].clientWidth));
handleScroll();
render();
}
}
function scrollColumnIntoView(cell) {
internalScrollColumnIntoView(columnPosLeft[cell], columnPosRight[cell]);
}
function setActiveCellInternal(newCell, opt_editMode, preClickModeOn, suppressActiveCellChangedEvent, e) {
if (activeCellNode !== null) {
makeActiveCellNormal();
$(activeCellNode).removeClass("active");
if (rowsCache[activeRow]) {
$(rowsCache[activeRow].rowNode).removeClass("active");
}
}
var activeCellChanged = (activeCellNode !== newCell);
activeCellNode = newCell;
if (activeCellNode != null) {
var $activeCellNode = $(activeCellNode);
var $activeCellOffset = $activeCellNode.offset();
var rowOffset = Math.floor($activeCellNode.parents('.grid-canvas').offset().top);
var isBottom = $activeCellNode.parents('.grid-canvas-bottom').length;
if (hasFrozenRows && isBottom) {
rowOffset -= ( options.frozenBottom )
? $canvasTopL.height()
: frozenRowsHeight;
}
var cell = getCellFromPoint($activeCellOffset.left, Math.ceil($activeCellOffset.top) - rowOffset);
activeRow = cell.row;
activeCell = activePosX = activeCell = activePosX = getCellFromNode(activeCellNode);
if (opt_editMode == null) {
opt_editMode = (activeRow == getDataLength()) || options.autoEdit;
}
if (options.showCellSelection) {
$activeCellNode.addClass("active");
if (rowsCache[activeRow]) {
$(rowsCache[activeRow].rowNode).addClass("active");
}
}
if (options.editable && opt_editMode && isCellPotentiallyEditable(activeRow, activeCell)) {
clearTimeout(h_editorLoader);
if (options.asyncEditorLoading) {
h_editorLoader = setTimeout(function () {
makeActiveCellEditable(undefined, preClickModeOn, e);
}, options.asyncEditorLoadDelay);
} else {
makeActiveCellEditable(undefined, preClickModeOn, e);
}
}
} else {
activeRow = activeCell = null;
}
// this optimisation causes trouble - MLeibman #329
//if (activeCellChanged) {
if (!suppressActiveCellChangedEvent) { trigger(self.onActiveCellChanged, getActiveCell()); }
//}
}
function clearTextSelection() {
if (document.selection && document.selection.empty) {
try {
//IE fails here if selected element is not in dom
document.selection.empty();
} catch (e) { }
} else if (window.getSelection) {
var sel = window.getSelection();
if (sel && sel.removeAllRanges) {
sel.removeAllRanges();
}
}
}
function isCellPotentiallyEditable(row, cell) {
var dataLength = getDataLength();
// is the data for this row loaded?
if (row < dataLength && !getDataItem(row)) {
return false;
}
// are we in the Add New row? can we create new from this cell?
if (columns[cell].cannotTriggerInsert && row >= dataLength) {
return false;
}
// does this cell have an editor?
if (!getEditor(row, cell)) {
return false;
}
return true;
}
function makeActiveCellNormal() {
if (!currentEditor) {
return;
}
trigger(self.onBeforeCellEditorDestroy, {editor: currentEditor});
currentEditor.destroy();
currentEditor = null;
if (activeCellNode) {
var d = getDataItem(activeRow);
$(activeCellNode).removeClass("editable invalid");
if (d) {
var column = columns[activeCell];
var formatter = getFormatter(activeRow, column);
var formatterResult = formatter(activeRow, activeCell, getDataItemValueForColumn(d, column), column, d, self);
applyFormatResultToCellNode(formatterResult, activeCellNode);
invalidatePostProcessingResults(activeRow);
}
}
// if there previously was text selected on a page (such as selected text in the edit cell just removed),
// IE can't set focus to anything else correctly
if (navigator.userAgent.toLowerCase().match(/msie/)) {
clearTextSelection();
}
getEditorLock().deactivate(editController);
}
function makeActiveCellEditable(editor, preClickModeOn, e) {
if (!activeCellNode) {
return;
}
if (!options.editable) {
throw new Error("Grid : makeActiveCellEditable : should never get called when options.editable is false");
}
// cancel pending async call if there is one
clearTimeout(h_editorLoader);
if (!isCellPotentiallyEditable(activeRow, activeCell)) {
return;
}
var columnDef = columns[activeCell];
var item = getDataItem(activeRow);
if (trigger(self.onBeforeEditCell, {row: activeRow, cell: activeCell, item: item, column: columnDef}) === false) {
setFocus();
return;
}
getEditorLock().activate(editController);
$(activeCellNode).addClass("editable");
var useEditor = editor || getEditor(activeRow, activeCell);
// don't clear the cell if a custom editor is passed through
if (!editor && !useEditor.suppressClearOnEdit) {
activeCellNode.innerHTML = "";
}
var metadata = data.getItemMetadata && data.getItemMetadata(activeRow);
metadata = metadata && metadata.columns;
var columnMetaData = metadata && ( metadata[columnDef.id] || metadata[activeCell] );
currentEditor = new useEditor({
grid: self,
gridPosition: absBox($container[0]),
position: absBox(activeCellNode),
container: activeCellNode,
column: columnDef,
columnMetaData: columnMetaData,
item: item || {},
event: e,
commitChanges: commitEditAndSetFocus,
cancelChanges: cancelEditAndSetFocus
});
if (item) {
currentEditor.loadValue(item);
if (preClickModeOn && currentEditor.preClick) {
currentEditor.preClick();
}
}
serializedEditorValue = currentEditor.serializeValue();
if (currentEditor.position) {
handleActiveCellPositionChange();
}
}
function commitEditAndSetFocus() {
// if the commit fails, it would do so due to a validation error
// if so, do not steal the focus from the editor
if (getEditorLock().commitCurrentEdit()) {
setFocus();
if (options.autoEdit) {
navigateDown();
}
}
}
function cancelEditAndSetFocus() {
if (getEditorLock().cancelCurrentEdit()) {
setFocus();
}
}
function absBox(elem) {
var box = {
top: elem.offsetTop,
left: elem.offsetLeft,
bottom: 0,
right: 0,
width: $(elem).outerWidth(),
height: $(elem).outerHeight(),
visible: true
};
box.bottom = box.top + box.height;
box.right = box.left + box.width;
// walk up the tree
var offsetParent = elem.offsetParent;
while ((elem = elem.parentNode) != document.body) {
if (elem == null) break;
if (box.visible && elem.scrollHeight != elem.offsetHeight && $(elem).css("overflowY") != "visible") {
box.visible = box.bottom > elem.scrollTop && box.top < elem.scrollTop + elem.clientHeight;
}
if (box.visible && elem.scrollWidth != elem.offsetWidth && $(elem).css("overflowX") != "visible") {
box.visible = box.right > elem.scrollLeft && box.left < elem.scrollLeft + elem.clientWidth;
}
box.left -= elem.scrollLeft;
box.top -= elem.scrollTop;
if (elem === offsetParent) {
box.left += elem.offsetLeft;
box.top += elem.offsetTop;
offsetParent = elem.offsetParent;
}
box.bottom = box.top + box.height;
box.right = box.left + box.width;
}
return box;
}
function getActiveCellPosition() {
return absBox(activeCellNode);
}
function getGridPosition() {
return absBox($container[0]);
}
function handleActiveCellPositionChange() {
if (!activeCellNode) {
return;
}
trigger(self.onActiveCellPositionChanged, {});
if (currentEditor) {
var cellBox = getActiveCellPosition();
if (currentEditor.show && currentEditor.hide) {
if (!cellBox.visible) {
currentEditor.hide();
} else {
currentEditor.show();
}
}
if (currentEditor.position) {
currentEditor.position(cellBox);
}
}
}
function getCellEditor() {
return currentEditor;
}
function getActiveCell() {
if (!activeCellNode) {
return null;
} else {
return {row: activeRow, cell: activeCell};
}
}
function getActiveCellNode() {
return activeCellNode;
}
function scrollRowIntoView(row, doPaging) {
if (!hasFrozenRows ||
( !options.frozenBottom && row > actualFrozenRow - 1 ) ||
( options.frozenBottom && row < actualFrozenRow - 1 ) ) {
var viewportScrollH = $viewportScrollContainerY.height();
// if frozen row on top
// subtract number of frozen row
var rowNumber = ( hasFrozenRows && !options.frozenBottom ? row - options.frozenRow : row );
var rowAtTop = rowNumber * options.rowHeight;
var rowAtBottom = (rowNumber + 1) * options.rowHeight
- viewportScrollH
+ (viewportHasHScroll ? scrollbarDimensions.height : 0);
// need to page down?
if ((rowNumber + 1) * options.rowHeight > scrollTop + viewportScrollH + offset) {
scrollTo(doPaging ? rowAtTop : rowAtBottom);
render();
}
// or page up?
else if (rowNumber * options.rowHeight < scrollTop + offset) {
scrollTo(doPaging ? rowAtBottom : rowAtTop);
render();
}
}
}
function scrollRowToTop(row) {
scrollTo(row * options.rowHeight);
render();
}
function scrollPage(dir) {
var deltaRows = dir * numVisibleRows;
/// First fully visible row crosses the line with
/// y == bottomOfTopmostFullyVisibleRow
var bottomOfTopmostFullyVisibleRow = scrollTop + options.rowHeight - 1;
scrollTo((getRowFromPosition(bottomOfTopmostFullyVisibleRow) + deltaRows) * options.rowHeight);
render();
if (options.enableCellNavigation && activeRow != null) {
var row = activeRow + deltaRows;
var dataLengthIncludingAddNew = getDataLengthIncludingAddNew();
if (row >= dataLengthIncludingAddNew) {
row = dataLengthIncludingAddNew - 1;
}
if (row < 0) {
row = 0;
}
var cell = 0, prevCell = null;
var prevActivePosX = activePosX;
while (cell <= activePosX) {
if (canCellBeActive(row, cell)) {
prevCell = cell;
}
cell += getColspan(row, cell);
}
if (prevCell !== null) {
setActiveCellInternal(getCellNode(row, prevCell));
activePosX = prevActivePosX;
} else {
resetActiveCell();
}
}
}
function navigatePageDown() {
scrollPage(1);
}
function navigatePageUp() {
scrollPage(-1);
}
function navigateTop() {
navigateToRow(0);
}
function navigateBottom() {
navigateToRow(getDataLength()-1);
}
function navigateToRow(row) {
var num_rows = getDataLength();
if (!num_rows) return true;
if (row < 0) row = 0;
else if (row >= num_rows) row = num_rows - 1;
scrollCellIntoView(row, 0, true);
if (options.enableCellNavigation && activeRow != null) {
var cell = 0, prevCell = null;
var prevActivePosX = activePosX;
while (cell <= activePosX) {
if (canCellBeActive(row, cell)) {
prevCell = cell;
}
cell += getColspan(row, cell);
}
if (prevCell !== null) {
setActiveCellInternal(getCellNode(row, prevCell));
activePosX = prevActivePosX;
} else {
resetActiveCell();
}
}
return true;
}
function getColspan(row, cell) {
var metadata = data.getItemMetadata && data.getItemMetadata(row);
if (!metadata || !metadata.columns) {
return 1;
}
var columnData = metadata.columns[columns[cell].id] || metadata.columns[cell];
var colspan = (columnData && columnData.colspan);
if (colspan === "*") {
colspan = columns.length - cell;
} else {
colspan = colspan || 1;
}
return colspan;
}
function findFirstFocusableCell(row) {
var cell = 0;
while (cell < columns.length) {
if (canCellBeActive(row, cell)) {
return cell;
}
cell += getColspan(row, cell);
}
return null;
}
function findLastFocusableCell(row) {
var cell = 0;
var lastFocusableCell = null;
while (cell < columns.length) {
if (canCellBeActive(row, cell)) {
lastFocusableCell = cell;
}
cell += getColspan(row, cell);
}
return lastFocusableCell;
}
function gotoRight(row, cell, posX) {
if (cell >= columns.length) {
return null;
}
do {
cell += getColspan(row, cell);
}
while (cell < columns.length && !canCellBeActive(row, cell));
if (cell < columns.length) {
return {
"row": row,
"cell": cell,
"posX": cell
};
}
return null;
}
function gotoLeft(row, cell, posX) {
if (cell <= 0) {
return null;
}
var firstFocusableCell = findFirstFocusableCell(row);
if (firstFocusableCell === null || firstFocusableCell >= cell) {
return null;
}
var prev = {
"row": row,
"cell": firstFocusableCell,
"posX": firstFocusableCell
};
var pos;
while (true) {
pos = gotoRight(prev.row, prev.cell, prev.posX);
if (!pos) {
return null;
}
if (pos.cell >= cell) {
return prev;
}
prev = pos;
}
}
function gotoDown(row, cell, posX) {
var prevCell;
var dataLengthIncludingAddNew = getDataLengthIncludingAddNew();
while (true) {
if (++row >= dataLengthIncludingAddNew) {
return null;
}
prevCell = cell = 0;
while (cell <= posX) {
prevCell = cell;
cell += getColspan(row, cell);
}
if (canCellBeActive(row, prevCell)) {
return {
"row": row,
"cell": prevCell,
"posX": posX
};
}
}
}
function gotoUp(row, cell, posX) {
var prevCell;
while (true) {
if (--row < 0) {
return null;
}
prevCell = cell = 0;
while (cell <= posX) {
prevCell = cell;
cell += getColspan(row, cell);
}
if (canCellBeActive(row, prevCell)) {
return {
"row": row,
"cell": prevCell,
"posX": posX
};
}
}
}
function gotoNext(row, cell, posX) {
if (row == null && cell == null) {
row = cell = posX = 0;
if (canCellBeActive(row, cell)) {
return {
"row": row,
"cell": cell,
"posX": cell
};
}
}
var pos = gotoRight(row, cell, posX);
if (pos) {
return pos;
}
var firstFocusableCell = null;
var dataLengthIncludingAddNew = getDataLengthIncludingAddNew();
// if at last row, cycle through columns rather than get stuck in the last one
if (row === dataLengthIncludingAddNew - 1) { row--; }
while (++row < dataLengthIncludingAddNew) {
firstFocusableCell = findFirstFocusableCell(row);
if (firstFocusableCell !== null) {
return {
"row": row,
"cell": firstFocusableCell,
"posX": firstFocusableCell
};
}
}
return null;
}
function gotoPrev(row, cell, posX) {
if (row == null && cell == null) {
row = getDataLengthIncludingAddNew() - 1;
cell = posX = columns.length - 1;
if (canCellBeActive(row, cell)) {
return {
"row": row,
"cell": cell,
"posX": cell
};
}
}
var pos;
var lastSelectableCell;
while (!pos) {
pos = gotoLeft(row, cell, posX);
if (pos) {
break;
}
if (--row < 0) {
return null;
}
cell = 0;
lastSelectableCell = findLastFocusableCell(row);
if (lastSelectableCell !== null) {
pos = {
"row": row,
"cell": lastSelectableCell,
"posX": lastSelectableCell
};
}
}
return pos;
}
function gotoRowStart(row, cell, posX) {
var newCell = findFirstFocusableCell(row);
if (newCell === null) return null;
return {
"row": row,
"cell": newCell,
"posX": newCell
};
}
function gotoRowEnd(row, cell, posX) {
var newCell = findLastFocusableCell(row);
if (newCell === null) return null;
return {
"row": row,
"cell": newCell,
"posX": newCell
};
}
function navigateRight() {
return navigate("right");
}
function navigateLeft() {
return navigate("left");
}
function navigateDown() {
return navigate("down");
}
function navigateUp() {
return navigate("up");
}
function navigateNext() {
return navigate("next");
}
function navigatePrev() {
return navigate("prev");
}
function navigateRowStart() {
return navigate("home");
}
function navigateRowEnd() {
return navigate("end");
}
/**
* @param {string} dir Navigation direction.
* @return {boolean} Whether navigation resulted in a change of active cell.
*/
function navigate(dir) {
if (!options.enableCellNavigation) {
return false;
}
if (!activeCellNode && dir != "prev" && dir != "next") {
return false;
}
if (!getEditorLock().commitCurrentEdit()) {
return true;
}
setFocus();
var tabbingDirections = {
"up": -1,
"down": 1,
"left": -1,
"right": 1,
"prev": -1,
"next": 1,
"home": -1,
"end": 1
};
tabbingDirection = tabbingDirections[dir];
var stepFunctions = {
"up": gotoUp,
"down": gotoDown,
"left": gotoLeft,
"right": gotoRight,
"prev": gotoPrev,
"next": gotoNext,
"home": gotoRowStart,
"end": gotoRowEnd
};
var stepFn = stepFunctions[dir];
var pos = stepFn(activeRow, activeCell, activePosX);
if (pos) {
if (hasFrozenRows && options.frozenBottom & pos.row == getDataLength()) {
return;
}
var isAddNewRow = (pos.row == getDataLength());
if (( !options.frozenBottom && pos.row >= actualFrozenRow )
|| ( options.frozenBottom && pos.row < actualFrozenRow )
) {
scrollCellIntoView(pos.row, pos.cell, !isAddNewRow && options.emulatePagingWhenScrolling);
}
setActiveCellInternal(getCellNode(pos.row, pos.cell));
activePosX = pos.posX;
return true;
} else {
setActiveCellInternal(getCellNode(activeRow, activeCell));
return false;
}
}
function getCellNode(row, cell) {
if (rowsCache[row]) {
ensureCellNodesInRowsCache(row);
try {
if (rowsCache[row].cellNodesByColumnIdx.length > cell) {
return rowsCache[row].cellNodesByColumnIdx[cell][0];
}
else {
return null;
}
} catch (e) {
return rowsCache[row].cellNodesByColumnIdx[cell];
}
}
return null;
}
function setActiveCell(row, cell, opt_editMode, preClickModeOn, suppressActiveCellChangedEvent) {
if (!initialized) { return; }
if (row > getDataLength() || row < 0 || cell >= columns.length || cell < 0) {
return;
}
if (!options.enableCellNavigation) {
return;
}
scrollCellIntoView(row, cell, false);
setActiveCellInternal(getCellNode(row, cell), opt_editMode, preClickModeOn, suppressActiveCellChangedEvent);
}
function setActiveRow(row, cell, suppressScrollIntoView) {
if (!initialized) { return; }
if (row > getDataLength() || row < 0 || cell >= columns.length || cell < 0) {
return;
}
activeRow = row;
if (!suppressScrollIntoView) {
scrollCellIntoView(row, cell || 0, false);
}
}
function canCellBeActive(row, cell) {
if (!options.enableCellNavigation || row >= getDataLengthIncludingAddNew() ||
row < 0 || cell >= columns.length || cell < 0) {
return false;
}
var rowMetadata = data.getItemMetadata && data.getItemMetadata(row);
if (rowMetadata && typeof rowMetadata.focusable !== "undefined") {
return !!rowMetadata.focusable;
}
var columnMetadata = rowMetadata && rowMetadata.columns;
if (columnMetadata && columnMetadata[columns[cell].id] && typeof columnMetadata[columns[cell].id].focusable !== "undefined") {
return !!columnMetadata[columns[cell].id].focusable;
}
if (columnMetadata && columnMetadata[cell] && typeof columnMetadata[cell].focusable !== "undefined") {
return !!columnMetadata[cell].focusable;
}
return !!columns[cell].focusable;
}
function canCellBeSelected(row, cell) {
if (row >= getDataLength() || row < 0 || cell >= columns.length || cell < 0) {
return false;
}
var rowMetadata = data.getItemMetadata && data.getItemMetadata(row);
if (rowMetadata && typeof rowMetadata.selectable !== "undefined") {
return !!rowMetadata.selectable;
}
var columnMetadata = rowMetadata && rowMetadata.columns && (rowMetadata.columns[columns[cell].id] || rowMetadata.columns[cell]);
if (columnMetadata && typeof columnMetadata.selectable !== "undefined") {
return !!columnMetadata.selectable;
}
return !!columns[cell].selectable;
}
function gotoCell(row, cell, forceEdit, e) {
if (!initialized) { return; }
if (!canCellBeActive(row, cell)) {
return;
}
if (!getEditorLock().commitCurrentEdit()) {
return;
}
scrollCellIntoView(row, cell, false);
var newCell = getCellNode(row, cell);
// if selecting the 'add new' row, start editing right away
var column = columns[cell];
var suppressActiveCellChangedEvent = !!(options.editable && column && column.editor && options.suppressActiveCellChangeOnEdit);
setActiveCellInternal(newCell, (forceEdit || (row === getDataLength()) || options.autoEdit), null, suppressActiveCellChangedEvent, e);
// if no editor was created, set the focus back on the grid
if (!currentEditor) {
setFocus();
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
// IEditor implementation for the editor lock
function commitCurrentEdit() {
var item = getDataItem(activeRow);
var column = columns[activeCell];
if (currentEditor) {
if (currentEditor.isValueChanged()) {
var validationResults = currentEditor.validate();
if (validationResults.valid) {
if (activeRow < getDataLength()) {
var editCommand = {
row: activeRow,
cell: activeCell,
editor: currentEditor,
serializedValue: currentEditor.serializeValue(),
prevSerializedValue: serializedEditorValue,
execute: function () {
this.editor.applyValue(item, this.serializedValue);
updateRow(this.row);
trigger(self.onCellChange, {
row: this.row,
cell: this.cell,
item: item
});
},
undo: function () {
this.editor.applyValue(item, this.prevSerializedValue);
updateRow(this.row);
trigger(self.onCellChange, {
row: this.row,
cell: this.cell,
item: item
});
}
};
if (options.editCommandHandler) {
makeActiveCellNormal();
options.editCommandHandler(item, column, editCommand);
} else {
editCommand.execute();
makeActiveCellNormal();
}
} else {
var newItem = {};
currentEditor.applyValue(newItem, currentEditor.serializeValue());
makeActiveCellNormal();
trigger(self.onAddNewRow, {item: newItem, column: column});
}
// check whether the lock has been re-acquired by event handlers
return !getEditorLock().isActive();
} else {
// Re-add the CSS class to trigger transitions, if any.
$(activeCellNode).removeClass("invalid");
$(activeCellNode).width(); // force layout
$(activeCellNode).addClass("invalid");
trigger(self.onValidationError, {
editor: currentEditor,
cellNode: activeCellNode,
validationResults: validationResults,
row: activeRow,
cell: activeCell,
column: column
});
currentEditor.focus();
return false;
}
}
makeActiveCellNormal();
}
return true;
}
function cancelCurrentEdit() {
makeActiveCellNormal();
return true;
}
function rowsToRanges(rows) {
var ranges = [];
var lastCell = columns.length - 1;
for (var i = 0; i < rows.length; i++) {
ranges.push(new Slick.Range(rows[i], 0, rows[i], lastCell));
}
return ranges;
}
function getSelectedRows() {
if (!selectionModel) {
throw new Error("Selection model is not set");
}
return selectedRows.slice(0);
}
function setSelectedRows(rows) {
if (!selectionModel) {
throw new Error("Selection model is not set");
}
if (self && self.getEditorLock && !self.getEditorLock().isActive()) {
selectionModel.setSelectedRanges(rowsToRanges(rows));
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
// Debug
this.debug = function () {
var s = "";
s += ("\n" + "counter_rows_rendered: " + counter_rows_rendered);
s += ("\n" + "counter_rows_removed: " + counter_rows_removed);
s += ("\n" + "renderedRows: " + renderedRows);
s += ("\n" + "numVisibleRows: " + numVisibleRows);
s += ("\n" + "maxSupportedCssHeight: " + maxSupportedCssHeight);
s += ("\n" + "n(umber of pages): " + n);
s += ("\n" + "(current) page: " + page);
s += ("\n" + "page height (ph): " + ph);
s += ("\n" + "vScrollDir: " + vScrollDir);
alert(s);
};
// a debug helper to be able to access private members
this.eval = function (expr) {
return eval(expr);
};
//////////////////////////////////////////////////////////////////////////////////////////////
// Public API
$.extend(this, {
"slickGridVersion": "2.4.29",
// Events
"onScroll": new Slick.Event(),
"onSort": new Slick.Event(),
"onHeaderMouseEnter": new Slick.Event(),
"onHeaderMouseLeave": new Slick.Event(),
"onHeaderContextMenu": new Slick.Event(),
"onHeaderClick": new Slick.Event(),
"onHeaderCellRendered": new Slick.Event(),
"onBeforeHeaderCellDestroy": new Slick.Event(),
"onHeaderRowCellRendered": new Slick.Event(),
"onFooterRowCellRendered": new Slick.Event(),
"onFooterContextMenu": new Slick.Event(),
"onFooterClick": new Slick.Event(),
"onBeforeHeaderRowCellDestroy": new Slick.Event(),
"onBeforeFooterRowCellDestroy": new Slick.Event(),
"onMouseEnter": new Slick.Event(),
"onMouseLeave": new Slick.Event(),
"onClick": new Slick.Event(),
"onDblClick": new Slick.Event(),
"onContextMenu": new Slick.Event(),
"onKeyDown": new Slick.Event(),
"onAddNewRow": new Slick.Event(),
"onBeforeAppendCell": new Slick.Event(),
"onValidationError": new Slick.Event(),
"onViewportChanged": new Slick.Event(),
"onColumnsReordered": new Slick.Event(),
"onColumnsDrag": new Slick.Event(),
"onColumnsResized": new Slick.Event(),
"onBeforeColumnsResize": new Slick.Event(),
"onCellChange": new Slick.Event(),
"onCompositeEditorChange": new Slick.Event(),
"onBeforeEditCell": new Slick.Event(),
"onBeforeCellEditorDestroy": new Slick.Event(),
"onBeforeDestroy": new Slick.Event(),
"onActiveCellChanged": new Slick.Event(),
"onActiveCellPositionChanged": new Slick.Event(),
"onDragInit": new Slick.Event(),
"onDragStart": new Slick.Event(),
"onDrag": new Slick.Event(),
"onDragEnd": new Slick.Event(),
"onSelectedRowsChanged": new Slick.Event(),
"onCellCssStylesChanged": new Slick.Event(),
"onAutosizeColumns": new Slick.Event(),
"onRendered": new Slick.Event(),
"onSetOptions": new Slick.Event(),
// Methods
"registerPlugin": registerPlugin,
"unregisterPlugin": unregisterPlugin,
"getPluginByName": getPluginByName,
"getColumns": getColumns,
"setColumns": setColumns,
"getColumnIndex": getColumnIndex,
"updateColumnHeader": updateColumnHeader,
"setSortColumn": setSortColumn,
"setSortColumns": setSortColumns,
"getSortColumns": getSortColumns,
"autosizeColumns": autosizeColumns,
"autosizeColumn": autosizeColumn,
"getOptions": getOptions,
"setOptions": setOptions,
"getData": getData,
"getDataLength": getDataLength,
"getDataItem": getDataItem,
"setData": setData,
"getSelectionModel": getSelectionModel,
"setSelectionModel": setSelectionModel,
"getSelectedRows": getSelectedRows,
"setSelectedRows": setSelectedRows,
"getContainerNode": getContainerNode,
"updatePagingStatusFromView": updatePagingStatusFromView,
"applyFormatResultToCellNode": applyFormatResultToCellNode,
"render": render,
"invalidate": invalidate,
"invalidateRow": invalidateRow,
"invalidateRows": invalidateRows,
"invalidateAllRows": invalidateAllRows,
"updateCell": updateCell,
"updateRow": updateRow,
"getViewport": getVisibleRange,
"getRenderedRange": getRenderedRange,
"resizeCanvas": resizeCanvas,
"updateRowCount": updateRowCount,
"scrollRowIntoView": scrollRowIntoView,
"scrollRowToTop": scrollRowToTop,
"scrollCellIntoView": scrollCellIntoView,
"scrollColumnIntoView": scrollColumnIntoView,
"getCanvasNode": getCanvasNode,
"getUID": getUID,
"getHeaderColumnWidthDiff": getHeaderColumnWidthDiff,
"getScrollbarDimensions": getScrollbarDimensions,
"getHeadersWidth": getHeadersWidth,
"getCanvasWidth": getCanvasWidth,
"getCanvases": getCanvases,
"getActiveCanvasNode": getActiveCanvasNode,
"setActiveCanvasNode": setActiveCanvasNode,
"getViewportNode": getViewportNode,
"getActiveViewportNode": getActiveViewportNode,
"setActiveViewportNode": setActiveViewportNode,
"focus": setFocus,
"scrollTo": scrollTo,
"getCellFromPoint": getCellFromPoint,
"getCellFromEvent": getCellFromEvent,
"getActiveCell": getActiveCell,
"setActiveCell": setActiveCell,
"setActiveRow": setActiveRow,
"getActiveCellNode": getActiveCellNode,
"getActiveCellPosition": getActiveCellPosition,
"resetActiveCell": resetActiveCell,
"editActiveCell": makeActiveCellEditable,
"getCellEditor": getCellEditor,
"getCellNode": getCellNode,
"getCellNodeBox": getCellNodeBox,
"canCellBeSelected": canCellBeSelected,
"canCellBeActive": canCellBeActive,
"navigatePrev": navigatePrev,
"navigateNext": navigateNext,
"navigateUp": navigateUp,
"navigateDown": navigateDown,
"navigateLeft": navigateLeft,
"navigateRight": navigateRight,
"navigatePageUp": navigatePageUp,
"navigatePageDown": navigatePageDown,
"navigateTop": navigateTop,
"navigateBottom": navigateBottom,
"navigateRowStart": navigateRowStart,
"navigateRowEnd": navigateRowEnd,
"gotoCell": gotoCell,
"getTopPanel": getTopPanel,
"setTopPanelVisibility": setTopPanelVisibility,
"getPreHeaderPanel": getPreHeaderPanel,
"getPreHeaderPanelLeft": getPreHeaderPanel,
"getPreHeaderPanelRight": getPreHeaderPanelRight,
"setPreHeaderPanelVisibility": setPreHeaderPanelVisibility,
"getHeader": getHeader,
"getHeaderColumn": getHeaderColumn,
"setHeaderRowVisibility": setHeaderRowVisibility,
"getHeaderRow": getHeaderRow,
"getHeaderRowColumn": getHeaderRowColumn,
"setFooterRowVisibility": setFooterRowVisibility,
"getFooterRow": getFooterRow,
"getFooterRowColumn": getFooterRowColumn,
"getGridPosition": getGridPosition,
"flashCell": flashCell,
"addCellCssStyles": addCellCssStyles,
"setCellCssStyles": setCellCssStyles,
"removeCellCssStyles": removeCellCssStyles,
"getCellCssStyles": getCellCssStyles,
"getFrozenRowOffset": getFrozenRowOffset,
"setColumnHeaderVisibility": setColumnHeaderVisibility,
"init": finishInitialization,
"destroy": destroy,
// IEditor implementation
"getEditorLock": getEditorLock,
"getEditController": getEditController
});
init();
}
}(jQuery));
| {
"content_hash": "3ef2626d0548ad4662901b5dfb38b823",
"timestamp": "",
"source": "github",
"line_count": 5963,
"max_line_length": 207,
"avg_line_length": 33.162669797082,
"alnum_prop": 0.5730142756726962,
"repo_name": "cdnjs/cdnjs",
"id": "39353f21950486ce5616169f07f76beb6b219c60",
"size": "197749",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "ajax/libs/6pac-slickgrid/2.4.29/slick.grid.js",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
/*
calendarmws.js - Script for generating calender popups and selecting dates for form
submissions. See http://www.macridesweb.com/oltest/calendarmws.html for a demonstration.
Initial: November 9, 2003 - Last Revised: June 11, 2008
****
Original: Kedar R. Bhave (softricks@hotmail.com)
Web Site: http://www.softricks.com
(uses window popups)
Modifications and customizations to work with the overLIB v3.50
Author: James B. O'Connor (joconnor@nordenterprises.com)
Web Site: http://www.nordenterprises.com
Developed for use with http://home-owners-assoc.com
Note: while overlib works fine with Netscape 4, this function does not work very
well, since portions of the "over" div end up under other fields on the form and
cannot be seen. If you want to use this with NS4, you'll need to change the
positioning in the overlib() call to make sure the "over" div gets positioned
away from all other form fields
The O'Connor script and many more are available free online at:
The JavaScript Source!! http://javascript.internet.com
Further modifications made by Foteos Macrides (http://www.macridesweb.com/oltest/)
and Bill McCormick (wpmccormick@freeshell.org) for overlibmws
*/
var ggPosX = -1;
var ggPosY = -1;
var ggInactive = 0;
var ggOnChange = null;
var ggUseOverlib2 = 0;
var ggWinContent = "";
var weekend = [0,6];
var weekendColor = "#e0e0e0";
var fontface = "Verdana";
var fontsize = 8; // in "pt" units; used with "font-size" style element
var gNow = new Date();
Calendar.Months = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"];
// Non-Leap year Month days..
Calendar.DOMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
// Leap year Month days..
Calendar.lDOMonth = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
function Calendar(p_item, p_month, p_year, p_format) {
if ((p_month == null) && (p_year == null)) return;
if (p_month == null) {
this.gMonthName = null;
this.gMonth = null;
this.gYearly = true;
} else {
this.gMonthName = Calendar.get_month(p_month);
this.gMonth = new Number(p_month);
this.gYearly = false;
}
this.gYear = p_year;
this.gFormat = p_format;
this.gBGColor = "white";
this.gFGColor = "black";
this.gTextColor = "black";
this.gHeaderColor = "black";
this.gReturnItem = p_item;
}
Calendar.get_month = Calendar_get_month;
Calendar.get_daysofmonth = Calendar_get_daysofmonth;
Calendar.calc_month_year = Calendar_calc_month_year;
function Calendar_get_month(monthNo) {
return Calendar.Months[monthNo];
}
function Calendar_get_daysofmonth(monthNo, p_year) {
/*
Check for leap year ..
1.Years evenly divisible by four are normally leap years, except for...
2.Years also evenly divisible by 100 are not leap years, except for...
3.Years also evenly divisible by 400 are leap years.
*/
if ((p_year % 4) == 0) {
if ((p_year % 100) == 0 && (p_year % 400) != 0)
return Calendar.DOMonth[monthNo];
return Calendar.lDOMonth[monthNo];
} else
return Calendar.DOMonth[monthNo];
}
function Calendar_calc_month_year(p_Month, p_Year, incr) {
/*
Will return an 1-D array with 1st element being the calculated month
and second being the calculated year
after applying the month increment/decrement as specified by 'incr' parameter.
'incr' will normally have 1/-1 to navigate thru the months.
*/
var ret_arr = new Array();
if (incr == -1) {
// B A C K W A R D
if (p_Month == 0) {
ret_arr[0] = 11;
ret_arr[1] = parseInt(p_Year) - 1;
} else {
ret_arr[0] = parseInt(p_Month) - 1;
ret_arr[1] = parseInt(p_Year);
}
} else if (incr == 1) {
// F O R W A R D
if (p_Month == 11) {
ret_arr[0] = 0;
ret_arr[1] = parseInt(p_Year) + 1;
} else {
ret_arr[0] = parseInt(p_Month) + 1;
ret_arr[1] = parseInt(p_Year);
}
}
return ret_arr;
}
function Calendar_calc_month_year(p_Month, p_Year, incr) {
/*
Will return an 1-D array with 1st element being the calculated month
and second being the calculated year
after applying the month increment/decrement as specified by 'incr' parameter.
'incr' will normally have 1/-1 to navigate thru the months.
*/
var ret_arr = new Array();
if (incr == -1) {
// B A C K W A R D
if (p_Month == 0) {
ret_arr[0] = 11;
ret_arr[1] = parseInt(p_Year) - 1;
} else {
ret_arr[0] = parseInt(p_Month) - 1;
ret_arr[1] = parseInt(p_Year);
}
} else if (incr == 1) {
// F O R W A R D
if (p_Month == 11) {
ret_arr[0] = 0;
ret_arr[1] = parseInt(p_Year) + 1;
} else {
ret_arr[0] = parseInt(p_Month) + 1;
ret_arr[1] = parseInt(p_Year);
}
}
return ret_arr;
}
// This is for compatibility with Navigator 3, we have to create and discard one object
// before the prototype object exists.
new Calendar();
Calendar.prototype.getMonthlyCalendarCode = function() {
var vCode = "";
var vHeader_Code = "";
var vData_Code = "";
// Begin Table Drawing code here..
vCode += ('<div align="center"><table border="1" bgcolor="' + this.gBGColor +
"\" style='font-size:" + fontsize + "pt;'>");
vHeader_Code = this.cal_header();
vData_Code = this.cal_data();
vCode += (vHeader_Code + vData_Code);
vCode += '</table></div>';
return vCode;
}
Calendar.prototype.show = function() {
var vCode = "";
var vDate = new Date();
vDate.setMonth(this.gMonth);
vDate.setFullYear(this.gYear);
var vNowMonth = gNow.getMonth();
var vNowYear = gNow.getFullYear();
var yOK=!ggInactive||vNowYear<vDate.getFullYear()?1:0;
var mOK=!ggInactive||(yOK||
(vNowYear<=vDate.getFullYear()&&vNowMonth<vDate.getMonth()))?1:0;
// build content into global var ggWinContent
ggWinContent += ('<div style="font-family:\'' + fontface + '\';font-weight:bold;'
+'font-size:' + fontsize + 'pt;text-align:center;">');
ggWinContent += (this.gMonthName + ' ' + this.gYear);
ggWinContent += '</div>';
// Show navigation buttons
var prevMMYYYY = Calendar.calc_month_year(this.gMonth, this.gYear, -1);
var prevMM = prevMMYYYY[0];
var prevYYYY = prevMMYYYY[1];
var nextMMYYYY = Calendar.calc_month_year(this.gMonth, this.gYear, 1);
var nextMM = nextMMYYYY[0];
var nextYYYY = nextMMYYYY[1];
ggWinContent += ('<table width="100%" border="1" cellspacing="0" cellpadding="0" '
+'bgcolor="#e0e0e0" style="font-size:' + fontsize
+'pt;"><tr><td align="center">');
ggWinContent += ('['
+(yOK?'<a href="javascript:void(0);" '
+'title="Go back one year" '
+'onmouseover="window.status=\'Go back one year\'; return true;" '
+'onmouseout="window.status=\'\'; return true;" '
+'onclick="Build(\'' + this.gReturnItem + '\', \'' + this.gMonth + '\', \''
+(parseInt(this.gYear)-1) + '\', \'' + this.gFormat + '\');"'
+'>':'')
+'<<Year'
+(yOK?'</a>':'')
+']</td><td align="center">');
ggWinContent += ('['
+(mOK?'<a href="javascript:void(0);" '
+'title="Go back one month" '
+'onmouseover="window.status=\'Go back one month\'; return true;" '
+'onmouseout="window.status=\'\'; return true;" '
+'onclick="Build(\'' + this.gReturnItem + '\', \'' + prevMM + '\', \''
+prevYYYY + '\', \'' + this.gFormat + '\');"'
+'>':'')
+'<Mon'
+(mOK?'</a>':'')
+']</td><td align="center">');
ggWinContent += ' </td><td align="center">';
ggWinContent += ('[<a href="javascript:void(0);" '
+'title="Go forward one month" '
+'onmouseover="window.status=\'Go forward one month\'; return true;" '
+'onmouseput="window.status=\'\'; return true;" '
+'onclick="Build(\'' + this.gReturnItem + '\', \'' + nextMM + '\', \''
+nextYYYY + '\', \'' + this.gFormat + '\');"'
+'>Mon></a>]</td><td align="center">');
ggWinContent += ('[<a href="javascript:void(0);" '
+'title="Go forward one year" '
+'onmouseover="window.status=\'Go forward one year\'; return true;" '
+'onmouseout="window.status=\'\'; return true;" '
+'onClick="Build(\'' + this.gReturnItem + '\', \'' + this.gMonth + '\', \''
+(parseInt(this.gYear)+1) + '\', \'' + this.gFormat + '\');"'
+'>Year>></a>]</td></tr></table><div style="font-size:3px;">'
+' </div>');
// Get the complete calendar code for the month, and add it to the content var
vCode = this.getMonthlyCalendarCode();
ggWinContent += vCode;
}
Calendar.prototype.showY = function() {
var vCode = "";
var i;
ggWinContent += ('<div style="font-family:\'' + fontface + '\';font-weight:bold;'
+'font-size:' + (fontsize+1) +'pt;text-align:center;">' + this.gYear +'</div>');
var vDate = new Date();
vDate.setDate(1);
vDate.setFullYear(this.gYear);
var vNowYear = gNow.getFullYear();
var yOK=!ggInactive||vNowYear<vDate.getFullYear()?1:0;
// Show navigation buttons
var prevYYYY = parseInt(this.gYear) - 1;
var nextYYYY = parseInt(this.gYear) + 1;
ggWinContent += ('<table width="100%" border="1" cellspacing="0" cellpadding="0" '
+'bgcolor="#e0e0e0" style="font-size:' + fontsize + 'pt;"><tr><td '
+'align="center">');
ggWinContent += ('['
+(yOK?'<a href="javascript:void(0);" '
+'title="Go back one year" '
+'onmouseover="window.status=\'Go back one year\'; return true;" '
+'onmouseout="window.status=\'\'; return true;" '
+'onclick="Build(\'' + this.gReturnItem + '\', null, \'' + prevYYYY + '\', \''
+this.gFormat + '\');">':'')
+'<<Year'
+(yOK?'<a>':'')
+']</td><td align="center">');
ggWinContent += ' </td><td align="center">';
ggWinContent += ('[<a href="javascript:void(0);" '
+'title="Go forward one year" '
+'onmouseover="window.status=\'Go forward one year\'; return true;" '
+'onmouseout="window.status=\'\'; return true;" '
+'onclick="Build(\'' + this.gReturnItem + '\', null, \'' + nextYYYY + '\', \''
+this.gFormat + '\');">Year>></a>]</td></tr></table>');
// Get the complete calendar code for each month.
// start a table and first row in the table
ggWinContent += ('<table width="100%" border="0" cellspacing="0" cellpadding="2" '
+'style="font-size:' + fontsize + 'pt;"><tr>');
for (i=0; i<12; i++) {
// start the table cell
ggWinContent += '<td align="center" valign="top">';
this.gMonth = i;
this.gMonthName = Calendar.get_month(this.gMonth);
vCode = this.getMonthlyCalendarCode();
ggWinContent += (this.gMonthName + '/' + this.gYear + '<div '
+'style="font-size:2px;"> </div>');
ggWinContent += vCode;
ggWinContent += '</td>';
if (i == 3 || i == 7) ggWinContent += '</tr><tr>';
}
ggWinContent += '</tr></table>';
}
Calendar.prototype.cal_header = function() {
var vCode = '<tr>';
vCode += ('<td width="14%" style="font-family:' + fontface + ';color:'
+this.gHeaderColor + ';font-weight:bold;">Sun</td>');
vCode += ('<td width="14%" style="font-family:' + fontface + ';color:'
+this.gHeaderColor + ';font-weight:bold;">Mon</td>');
vCode += ('<td width="14%" style="font-family:' + fontface + ';color:'
+this.gHeaderColor + ';font-weight:bold;">Tue</td>');
vCode += ('<td width="14%" style="font-family:' + fontface + ';color:'
+this.gHeaderColor + ';font-weight:bold;">Wed</td>');
vCode += ('<td width="14%" style="font-family:' + fontface + ';color:'
+this.gHeaderColor + ';font-weight:bold;">Thu</td>');
vCode += ('<td width="14%" style="font-family:' + fontface + ';color:'
+this.gHeaderColor + ';font-weight:bold;">Fri</td>');
vCode += ('<td width="16%" style="font-family:' + fontface + ';color:'
+this.gHeaderColor + ';font-weight:bold;">Sat</td>');
vCode += '</tr>';
return vCode;
}
Calendar.prototype.cal_data = function() {
var vDate = new Date();
vDate.setDate(1);
vDate.setMonth(this.gMonth);
vDate.setFullYear(this.gYear);
var vNowDay = gNow.getDate();
var vNowMonth = gNow.getMonth();
var vNowYear = gNow.getFullYear();
var yOK=!ggInactive||vNowYear<=vDate.getFullYear()?1:0;
var mOK=!ggInactive||vNowYear<vDate.getFullYear()||
(vNowYear==vDate.getFullYear()&&vNowMonth<=vDate.getMonth())?1:0;
var ymOK=yOK&&mOK?1:0;
var dOK=!ggInactive||vNowYear<vDate.getFullYear()||vNowMonth<vDate.getMonth()?1:0;
var vFirstDay=vDate.getDay();
var vDay=1;
var vLastDay=Calendar.get_daysofmonth(this.gMonth, this.gYear);
var vOnLastDay=0;
var vCode = '<tr>';
var i,j,k,m;
var orig = eval("document." + this.gReturnItem + ".value").toString();
/*
Get day for the 1st of the requested month/year..
Place as many blank cells before the 1st day of the month as necessary.
*/
for (i=0; i<vFirstDay; i++) { vCode +=
('<td width="14%"' + this.write_weekend_string(i)
+'style="font-family:\'' + fontface + '\';text-align:center;"> </td>');
}
// Write rest of the 1st week
for (j=vFirstDay; j<7; j++) { vCode +=
('<td width="14%"' + this.write_weekend_string(j) +'style="font-family:\''
+ fontface + '\';text-align:center;">'
+((ymOK)&&(vDay>=vNowDay||dOK)?'<a href="javascript:void(0);" '
+'title="set date to ' + this.format_data(vDay) + '" '
+'onmouseover="window.status=\'set date to ' + this.format_data(vDay) + '\'; '
+'return true;" '
+'onmouseout="window.status=\'\'; return true;" '
+'onclick="document.' + this.gReturnItem + '.value=\'' + this.format_data(vDay)
+'\';ggPosX= -1;ggPosY= -1;' + OLfnRef + (ggUseOverlib2?'cClick2();':'cClick();')
+'if((ggOnChange)&&(document.' + this.gReturnItem + '.value!=\'' + orig
+'\'))ggOnChange();">':'')
+ this.format_day(vDay)
+((ymOK)&&(vDay>=vNowDay||dOK)?'</a>':'')
+'</td>');
vDay += 1;
}
vCode += '</tr>';
// Write the rest of the weeks
for (k=2; k<7; k++) {
vCode += '<tr>';
for (j=0; j<7; j++) { vCode +=
('<td width="14%"' + this.write_weekend_string(j)
+'style="font-family:\'' + fontface + '\';text-align:center;">'
+((ymOK)&&(vDay>=vNowDay||dOK)?'<a '
+'href="javascript:void(0);" '
+'title="set date to ' + this.format_data(vDay) + '" '
+'onmouseover="window.status=\'set date to ' + this.format_data(vDay)
+'\'; return true;" '
+'onmouseout="window.status=\'\'; return true;" '
+'onclick="document.' + this.gReturnItem + '.value=\''
+ this.format_data(vDay) + '\';ggPosX= -1;ggPosY= -1;'
+ OLfnRef + (ggUseOverlib2?'cClick2();':'cClick();')
+'if((ggOnChange)&&(document.' + this.gReturnItem + '.value!=\''
+orig + '\'))ggOnChange();">':'')
+ this.format_day(vDay)
+((ymOK)&&(vDay>=vNowDay||dOK)?'</a>':'')
+'</td>');
vDay += 1;
if (vDay > vLastDay) {
vOnLastDay = 1;
break;
}
}
if (j == 6) vCode += '</tr>';
if (vOnLastDay == 1) break;
}
// Fill up the rest of last week with proper blanks, so that we get proper square blocks
for (m=1; m<(7-j); m++) { vCode +=
('<td width="14%"' + this.write_weekend_string(j+m) + 'style="font-family:\''
+ fontface + '\';color:gray;text-align:center;"> </td>');
}
return vCode;
}
Calendar.prototype.format_day = function(vday) {
var vNowDay = gNow.getDate();
var vNowMonth = gNow.getMonth();
var vNowYear = gNow.getFullYear();
if (vday == vNowDay && this.gMonth == vNowMonth && this.gYear == vNowYear)
return ('<span style="color:red;font-weight:bold;">' + vday + '</span>');
else
return (vday);
}
Calendar.prototype.write_weekend_string = function(vday) {
var i;
// Return special formatting for the weekend day.
for (i=0; i<weekend.length; i++) {
if (vday == weekend[i])
return (' bgcolor="' + weekendColor + '"');
}
return "";
}
Calendar.prototype.format_data = function(p_day) {
var vData;
var vMonth = 1 + this.gMonth;
vMonth = (vMonth.toString().length < 2) ? "0" + vMonth : vMonth;
var vMon = Calendar.get_month(this.gMonth).substr(0,3).toUpperCase();
var vFMon = Calendar.get_month(this.gMonth).toUpperCase();
var vY4 = new String(this.gYear);
var vY2 = new String(this.gYear.substr(2,2));
var vDD = (p_day.toString().length < 2) ? "0" + p_day : p_day;
switch (this.gFormat) {
case "MM\/DD\/YYYY" :
vData = vMonth + "\/" + vDD + "\/" + vY4;
break;
case "MM\/DD\/YY" :
vData = vMonth + "\/" + vDD + "\/" + vY2;
break;
case "MM-DD-YYYY" :
vData = vMonth + "-" + vDD + "-" + vY4;
break;
case "YYYY-MM-DD" :
vData = vY4 + "-" + vMonth + "-" + vDD;
break;
case "MM-DD-YY" :
vData = vMonth + "-" + vDD + "-" + vY2;
break;
case "DD\/MON\/YYYY" :
vData = vDD + "\/" + vMon + "\/" + vY4;
break;
case "DD\/MON\/YY" :
vData = vDD + "\/" + vMon + "\/" + vY2;
break;
case "DD-MON-YYYY" :
vData = vDD + "-" + vMon + "-" + vY4;
break;
case "DD-MON-YY" :
vData = vDD + "-" + vMon + "-" + vY2;
break;
case "DD\/MONTH\/YYYY" :
vData = vDD + "\/" + vFMon + "\/" + vY4;
break;
case "DD\/MONTH\/YY" :
vData = vDD + "\/" + vFMon + "\/" + vY2;
break;
case "DD-MONTH-YYYY" :
vData = vDD + "-" + vFMon + "-" + vY4;
break;
case "DD-MONTH-YY" :
vData = vDD + "-" + vFMon + "-" + vY2;
break;
case "DD\/MM\/YYYY" :
vData = vDD + "\/" + vMonth + "\/" + vY4;
break;
case "DD\/MM\/YY" :
vData = vDD + "\/" + vMonth + "\/" + vY2;
break;
case "DD-MM-YYYY" :
vData = vDD + "-" + vMonth + "-" + vY4;
break;
case "DD-MM-YY" :
vData = vDD + "-" + vMonth + "-" + vY2;
break;
case "DD.MM.YYYY" :
vData = vDD + "." + vMonth + "." + vY4;
break;
case "DD.MM.YY" :
vData = vDD + "." + vMonth + "." + vY2;
break;
default :
vData = vMonth + "\/" + vDD + "\/" + vY4;
}
return vData;
}
function Build(p_item, p_month, p_year, p_format) {
var gCal = new Calendar(p_item, p_month, p_year, p_format);
// Customize your Calendar here..
gCal.gBGColor="white";
gCal.gLinkColor="black";
gCal.gTextColor="black";
gCal.gHeaderColor="darkgreen";
// initialize the content string
ggWinContent = "";
// Check for DRAGGABLE support
if (typeof ol_draggable == 'undefined') DRAGGABLE = DONOTHING;
// Choose appropriate show function
if (gCal.gYearly) {
// Note: you can set ggPosX and ggPosY as part of the onclick javascript
// code before you call the show_yearly_calendar function:
// onclick="ggPosX=20;ggPosY=5;show_yearly_calendar(...);"
if (OLns6) {
if (ggPosX == -1) ggPosX = 20;
if (ggPosY == -1) ggPosY = 10;
}
if (fontsize == 8) fontsize = 6;
// generate the calendar
gCal.showY();
} else {
if (fontsize == 6) fontsize = 8;
gCal.show();
}
// Clear or force EXCLUSIVE setting
o3_exclusive=(ggUseOverlib2)?1:0;
var CalendarOv=(ggUseOverlib2)?overlib2:overlib;
// If X and Y positions are not specified use MIDX and RELY
if (ggPosX == -1 && ggPosY == -1) {
CalendarOv(ggWinContent, AUTOSTATUSCAP, STICKY, EXCLUSIVE, DRAGGABLE,
CLOSECLICK, TEXTSIZE,'8pt', CAPTIONSIZE,'8pt', CLOSESIZE,'8pt',
CAPTION,'Select a date', MIDX,0, RELY,10);
// Otherwise use FIXX and FIXY
} else {
// Make sure popup is on screen
var X = ((ggPosX < 10)?0:ggPosX - 10), Y = ((ggPosY < 10)?0:ggPosY - 10);
window.scroll(X, Y);
// Put up the calendar
CalendarOv(ggWinContent, AUTOSTATUSCAP, STICKY, EXCLUSIVE, DRAGGABLE,
CLOSECLICK, TEXTSIZE,'8pt', CAPTIONSIZE,'8pt', CLOSESIZE,'8pt',
CAPTION,'Select a date', FIXX,ggPosX, FIXY,ggPosY);
// Reset the position variables
ggPosX = -1; ggPosY = -1;
}
ggUseOverlib2=0;
}
function show_calendar() {
var p_item // Return Item.
var p_month // 0-11 for Jan-Dec; 12 for All Months.
var p_year // 4-digit year
var p_format // Date format (YYYY-MM-DD, DD/MM/YYYY, ...)
fontsize = 8;
p_item = arguments[0];
if (arguments[1] == "" || arguments[1] == null || arguments[1] == '12')
p_month = new String(gNow.getMonth());
else
p_month = arguments[1];
if (arguments[2] == "" || arguments[2] == null)
p_year = new String(gNow.getFullYear().toString());
else
p_year = arguments[2];
if (arguments[3] == "" || arguments[3] == null)
p_format = "YYYY-MM-DD";
else
p_format = arguments[3];
if (OLns4) return overlib('Sorry, your browser does not support this feature. '
+'Manually enter<br>' + p_format,
FGCOLOR,'#ffffcc', TEXTSIZE,2, STICKY, NOCLOSE, OFFSETX,-10, OFFSETY,-10,
WIDTH,110, BASE,2);
Build(p_item, p_month, p_year, p_format);
}
function show_yearly_calendar() {
var p_item // Return Item.
var p_year // 4-digit year
var p_format // Date format (YYYY-MM-DD, DD/MM/YYYY, ...)
p_item = arguments[0];
if (arguments[1] == "" || arguments[1] == null)
p_year = new String(gNow.getFullYear().toString());
else
p_year = arguments[1];
if (arguments[2] == "" || arguments[2] == null)
p_format = "YYYY-MM-DD";
else
p_format = arguments[2];
if (OLns4) return overlib('Sorry, your browser does not support this feature. '
+'Manually enter<br>' + p_format,
FGCOLOR,'#ffffcc', TEXTSIZE,2, STICKY, NOCLOSE, OFFSETX,-10, OFFSETY,-10,
WIDTH,110, BASE,2);
Build(p_item, null, p_year, p_format);
}
| {
"content_hash": "b273e54ce34c7d8faa3e1fa8f8d12fa6",
"timestamp": "",
"source": "github",
"line_count": 624,
"max_line_length": 91,
"avg_line_length": 34.145833333333336,
"alnum_prop": 0.5961421129206365,
"repo_name": "NCIP/prot-express",
"id": "0bb30d98746d74fe081acef08c40e66218be8d9b",
"size": "21307",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "software/src/main/webapp/scripts/overlib/calendarmws.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "DOT",
"bytes": "685568"
},
{
"name": "Java",
"bytes": "974572"
},
{
"name": "JavaScript",
"bytes": "912542"
},
{
"name": "Logos",
"bytes": "1739740"
},
{
"name": "Shell",
"bytes": "3327"
},
{
"name": "XML",
"bytes": "150476"
}
],
"symlink_target": ""
} |
<?php
class Comment
{
private $id;
private $avatar;
private $comment;
private $user_id;
private $post_id;
private $likes;
// public function __construct($id = null, $comment = null, $userId = null, $postId = null, $vote = null)
// {
// if (!$id = null) $this->id = $id;
// if (!$comment = null) $this->comment = $comment;
// if (!$userId = null) $this->userId = $userId;
// if (!$postId = null) $this->postId = $postId;
// if(!$vote = null) $this->vote = $vote;
// }
public function getId()
{
return $this->id;
}
public function getAvatar()
{
return $this->avatar;
}
public function getComment()
{
return $this->comment;
}
public function getPost_id()
{
return $this->post_id;
}
public function getUser_id()
{
return $this->user_id;
}
public function getLikes()
{
return $this->likes;
}
public function createComment()
{
$db = new Database();
$query = $db->query("INSERT INTO comments (comment, userId, postId)
VALUES ('".$this->getComment()."','".$this->getUserId()."','".$this->getPostId()."')");
return $query;
}
public function addVote()
{
$db = new Database();
$query = $db->query("INSERT INTO comments (vote)
VALUES ('".$this->getVote()."')");
return $query;
}
public function getComments($postId)
{
$db = new Database();
$query = $db->getObjects("SELECT * FROM comment
WHERE user_id ='".$postId."'", 'comments');
// return $result = usort($query, function($a, $b)
// {
// return strcmp($a->vote, $b->vote);
// });
return $query;
}
}
| {
"content_hash": "af7b828d0a18b0aec6029c3dc9cf823e",
"timestamp": "",
"source": "github",
"line_count": 81,
"max_line_length": 108,
"avg_line_length": 22.48148148148148,
"alnum_prop": 0.5041186161449753,
"repo_name": "borgchrist1/Linkify",
"id": "a474618d6cc6e038e36749236772b65f82052653",
"size": "1821",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "classes/Comment.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4430"
},
{
"name": "HTML",
"bytes": "3935"
},
{
"name": "JavaScript",
"bytes": "1766"
},
{
"name": "PHP",
"bytes": "38977"
}
],
"symlink_target": ""
} |
var WebGLManager = require('./WebGLManager'),
AlphaMaskFilter = require('../filters/spriteMask/SpriteMaskFilter');
/**
* @class
* @memberof PIXI
* @param renderer {PIXI.WebGLRenderer} The renderer this manager works for.
*/
function MaskManager(renderer)
{
WebGLManager.call(this, renderer);
this.scissor = false;
this.enableScissor = true;
this.alphaMaskPool = [];
this.alphaMaskIndex = 0;
}
MaskManager.prototype = Object.create(WebGLManager.prototype);
MaskManager.prototype.constructor = MaskManager;
module.exports = MaskManager;
/**
* Applies the Mask and adds it to the current filter stack.
*
* @param target {PIXI.DisplayObject}
* @param maskData {*[]}
*/
MaskManager.prototype.pushMask = function (target, maskData)
{
if (maskData.texture)
{
this.pushSpriteMask(target, maskData);
}
else
{
// console.log( maskData.graphicsData[0].shape.type)
if(this.enableScissor && !this.scissor && !this.renderer.stencilManager.stencilMaskStack.length && maskData.graphicsData[0].shape.type === 1)
{
var matrix = maskData.worldTransform;
var rot = Math.atan2(matrix.b, matrix.a);
// use the nearest degree!
rot = Math.round(rot * (180/Math.PI));
if(rot % 90)
{
this.pushStencilMask(maskData);
}
else
{
this.pushScissorMask(target, maskData);
}
}
else
{
this.pushStencilMask(maskData);
}
}
};
/**
* Removes the last mask from the mask stack and doesn't return it.
*
* @param target {PIXI.DisplayObject}
* @param maskData {*[]}
*/
MaskManager.prototype.popMask = function (target, maskData)
{
if (maskData.texture)
{
this.popSpriteMask(target, maskData);
}
else
{
if(this.enableScissor && !this.renderer.stencilManager.stencilMaskStack.length)
{
this.popScissorMask(target, maskData);
}
else
{
this.popStencilMask(target, maskData);
}
}
};
/**
* Applies the Mask and adds it to the current filter stack.
*
* @param target {PIXI.RenderTarget}
* @param maskData {PIXI.Sprite}
*/
MaskManager.prototype.pushSpriteMask = function (target, maskData)
{
var alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex];
if (!alphaMaskFilter)
{
alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex] = [new AlphaMaskFilter(maskData)];
}
alphaMaskFilter[0].maskSprite = maskData;
//TODO - may cause issues!
target.filterArea = maskData.getBounds();
this.renderer.filterManager.pushFilter(target, alphaMaskFilter);
this.alphaMaskIndex++;
};
/**
* Removes the last filter from the filter stack and doesn't return it.
*
*/
MaskManager.prototype.popSpriteMask = function ()
{
this.renderer.filterManager.popFilter();
this.alphaMaskIndex--;
};
/**
* Applies the Mask and adds it to the current filter stack.
*
* @param maskData {*[]}
*/
MaskManager.prototype.pushStencilMask = function (maskData)
{
this.renderer.currentRenderer.stop();
this.renderer.stencilManager.pushStencil(maskData);
};
/**
* Removes the last filter from the filter stack and doesn't return it.
*
*/
MaskManager.prototype.popStencilMask = function ()
{
this.renderer.currentRenderer.stop();
this.renderer.stencilManager.popStencil();
};
MaskManager.prototype.pushScissorMask = function (target, maskData)
{
maskData.renderable = true;
var renderTarget = this.renderer._activeRenderTarget;
var bounds = maskData.getBounds();
bounds.fit(renderTarget.size);
maskData.renderable = false;
this.renderer.gl.enable(this.renderer.gl.SCISSOR_TEST);
this.renderer.gl.scissor(bounds.x,
renderTarget.root ? renderTarget.size.height - bounds.y - bounds.height : bounds.y,
bounds.width ,
bounds.height);
this.scissor = true;
};
MaskManager.prototype.popScissorMask = function ()
{
this.scissor = false;
// must be scissor!
var gl = this.renderer.gl;
gl.disable(gl.SCISSOR_TEST);
};
| {
"content_hash": "614dbed16bd90e1bb0e4292d8b247e47",
"timestamp": "",
"source": "github",
"line_count": 174,
"max_line_length": 149,
"avg_line_length": 24.235632183908045,
"alnum_prop": 0.6461939767607304,
"repo_name": "chrooke/jibo-guess-my-number",
"id": "b979ff6e091ee7b0b525e73ac7c58f60744d5637",
"size": "4217",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "node_modules/jibo/node_modules/pixi-animate/node_modules/pixi.js/src/core/renderers/webgl/managers/MaskManager.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "96"
},
{
"name": "HTML",
"bytes": "351"
},
{
"name": "JavaScript",
"bytes": "669"
}
],
"symlink_target": ""
} |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Why use a high-precision library rather than built-in floating-point types?</title>
<link rel="stylesheet" href="../../boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../index.html" title="Math Toolkit">
<link rel="up" href="../high_precision.html" title="Using Boost.Math with High-Precision Floating-Point Libraries">
<link rel="prev" href="../high_precision.html" title="Using Boost.Math with High-Precision Floating-Point Libraries">
<link rel="next" href="use_multiprecision.html" title="Using Boost.Multiprecision">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td>
<td align="center"><a href="../../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="../high_precision.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../high_precision.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="use_multiprecision.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h3 class="title">
<a name="math_toolkit.high_precision.why_high_precision"></a><a class="link" href="why_high_precision.html" title="Why use a high-precision library rather than built-in floating-point types?">Why use
a high-precision library rather than built-in floating-point types?</a>
</h3></div></div></div>
<p>
For nearly all applications, the built-in floating-point types, <code class="computeroutput"><span class="keyword">double</span></code> (and <code class="computeroutput"><span class="keyword">long</span>
<span class="keyword">double</span></code> if this offers higher precision
than <code class="computeroutput"><span class="keyword">double</span></code>) offer enough precision,
typically a dozen decimal digits.
</p>
<p>
Some reasons why one would want to use a higher precision:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; ">
<li class="listitem">
A much more precise result (many more digits) is just a requirement.
</li>
<li class="listitem">
The range of the computed value exceeds the range of the type: factorials
are the textbook example.
</li>
<li class="listitem">
Using double is (or may be) too inaccurate.
</li>
<li class="listitem">
Using long double (or may be) is too inaccurate.
</li>
<li class="listitem">
Using an extended precision type implemented in software as <a href="http://en.wikipedia.org/wiki/Double-double_(arithmetic)#Double-double_arithmetic" target="_top">double-double</a>
(<a href="http://en.wikipedia.org/wiki/Darwin_(operating_system)" target="_top">Darwin</a>)
is sometimes unpredictably inaccurate.
</li>
<li class="listitem">
Loss of precision or inaccuracy caused by extreme arguments or cancellation
error.
</li>
<li class="listitem">
An accuracy as good as possible for a chosen built-in floating-point
type is required.
</li>
<li class="listitem">
As a reference value, for example, to determine the inaccuracy of a value
computed with a built-in floating point type, (perhaps even using some
quick'n'dirty algorithm). The accuracy of many functions and distributions
in Boost.Math has been measured in this way from tables of very high
precision (up to 1000 decimal digits).
</li>
</ul></div>
<p>
Many functions and distributions have differences from exact values that
are only a few least significant bits - computation noise. Others, often
those for which analytical solutions are not available, require approximations
and iteration: these may lose several decimal digits of precision.
</p>
<p>
Much larger loss of precision can occur for <a href="http://en.wikipedia.org/wiki/Boundary_case" target="_top">boundary</a>
or <a href="http://en.wikipedia.org/wiki/Corner_case" target="_top">corner cases</a>,
often caused by <a href="http://en.wikipedia.org/wiki/Loss_of_significance" target="_top">cancellation
errors</a>.
</p>
<p>
(Some of the worst and most common examples of <a href="http://en.wikipedia.org/wiki/Loss_of_significance" target="_top">cancellation
error or loss of significance</a> can be avoided by using <a class="link" href="../stat_tut/overview/complements.html" title="Complements are supported too - and when to use them">complements</a>:
see <a class="link" href="../stat_tut/overview/complements.html#why_complements">why complements?</a>).
</p>
<p>
If you require a value which is as accurate as can be represented in the
floating-point type, and is thus the closest representable value and has
an error less than 1/2 a <a href="http://en.wikipedia.org/wiki/Least_significant_bit" target="_top">least
significant bit</a> or <a href="http://en.wikipedia.org/wiki/Unit_in_the_last_place" target="_top">ulp</a>
it may be useful to use a higher-precision type, for example, <code class="computeroutput"><span class="identifier">cpp_dec_float_50</span></code>, to generate this value.
Conversion of this value to a built-in floating-point type ('float', <code class="computeroutput"><span class="keyword">double</span></code> or <code class="computeroutput"><span class="keyword">long</span>
<span class="keyword">double</span></code>) will not cause any further
loss of precision. A decimal digit string will also be 'read' precisely by
the compiler into a built-in floating-point type to the nearest representable
value.
</p>
<div class="note"><table border="0" summary="Note">
<tr>
<td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="../../../../../../doc/src/images/note.png"></td>
<th align="left">Note</th>
</tr>
<tr><td align="left" valign="top"><p>
In contrast, reading a value from an <code class="computeroutput"><span class="identifier">std</span><span class="special">::</span><span class="identifier">istream</span></code>
into a built-in floating-point type is <span class="bold"><strong>not guaranteed</strong></span>
by the C++ Standard to give the nearest representable value.
</p></td></tr>
</table></div>
<p>
William Kahan coined the term <a href="http://en.wikipedia.org/wiki/Rounding#The_table-maker.27s_dilemma" target="_top">Table-Maker's
Dilemma</a> for the problem of correctly rounding functions. Using a
much higher precision (50 or 100 decimal digits) is a practical way of generating
(almost always) correctly rounded values.
</p>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2006-2010, 2012, 2013 Paul A. Bristow, Christopher Kormanyos,
Hubert Holin, Bruno Lalande, John Maddock, Johan Råde, Gautam Sewani, Benjamin
Sobotta, Thijs van den Berg, Daryle Walker and Xiaogang Zhang<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="../high_precision.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../high_precision.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="use_multiprecision.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| {
"content_hash": "02e695ce23aeb2d88b42c9685094e942",
"timestamp": "",
"source": "github",
"line_count": 136,
"max_line_length": 451,
"avg_line_length": 65.38970588235294,
"alnum_prop": 0.6555717980434049,
"repo_name": "yxcoin/yxcoin",
"id": "37ea70e4b63a22579aa76eefb8510ecd9d1135a5",
"size": "8893",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "src/boost_1_55_0/libs/math/doc/html/math_toolkit/high_precision/why_high_precision.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "222528"
},
{
"name": "Batchfile",
"bytes": "26447"
},
{
"name": "C",
"bytes": "2572612"
},
{
"name": "C#",
"bytes": "40804"
},
{
"name": "C++",
"bytes": "151033085"
},
{
"name": "CMake",
"bytes": "1741"
},
{
"name": "CSS",
"bytes": "270134"
},
{
"name": "Cuda",
"bytes": "26749"
},
{
"name": "Fortran",
"bytes": "1387"
},
{
"name": "HTML",
"bytes": "151665458"
},
{
"name": "IDL",
"bytes": "14"
},
{
"name": "JavaScript",
"bytes": "132031"
},
{
"name": "Lex",
"bytes": "1231"
},
{
"name": "M4",
"bytes": "29689"
},
{
"name": "Makefile",
"bytes": "1094300"
},
{
"name": "Max",
"bytes": "36857"
},
{
"name": "NSIS",
"bytes": "6041"
},
{
"name": "Objective-C",
"bytes": "11848"
},
{
"name": "Objective-C++",
"bytes": "3755"
},
{
"name": "PHP",
"bytes": "59030"
},
{
"name": "Perl",
"bytes": "28121"
},
{
"name": "Perl6",
"bytes": "2053"
},
{
"name": "Python",
"bytes": "1720604"
},
{
"name": "QML",
"bytes": "593"
},
{
"name": "QMake",
"bytes": "24083"
},
{
"name": "Rebol",
"bytes": "354"
},
{
"name": "Roff",
"bytes": "8039"
},
{
"name": "Shell",
"bytes": "350488"
},
{
"name": "Tcl",
"bytes": "1172"
},
{
"name": "TeX",
"bytes": "13404"
},
{
"name": "XSLT",
"bytes": "687839"
},
{
"name": "Yacc",
"bytes": "18910"
}
],
"symlink_target": ""
} |
local function serialize(obj)
local lua = ""
local t = type(obj)
if t == "number" then
lua = lua .. obj
elseif t == "boolean" then
lua = lua .. tostring(obj)
elseif t == "string" then
lua = lua .. string.format("%q", obj)
elseif t == "table" then
lua = lua .. "{"
for k, v in pairs(obj) do
lua = lua .. "[" .. serialize(k) .. "]=" .. serialize(v) .. ","
end
local metatable = getmetatable(obj)
if metatable ~= nil and type(metatable.__index) == "table" then
for k, v in pairs(metatable.__index) do
lua = lua .. "[" .. serialize(k) .. "]=" .. serialize(v) .. ","
end
end
lua = lua .. "}"
elseif t == "nil" then
return nil
else
error("can not serialize a " .. t .. " type.")
end
return lua
end
local function unserialize(lua)
local t = type(lua)
if t == "nil" or lua == "" then
return nil
elseif t == "number" or t == "string" or t == "boolean" then
lua = tostring(lua)
else
error("can not unserialize a " .. t .. " type.")
end
lua = "return " .. lua
local func = loadstring(lua)
if func == nil then
return nil
end
return func()
end
local table = table
table.serialize = serialize
table.unserialize = unserialize
| {
"content_hash": "a2b057930d631079d58493327284e133",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 79,
"avg_line_length": 28.102040816326532,
"alnum_prop": 0.5105301379811183,
"repo_name": "tianxiawuzhei/cocos-quick-lua",
"id": "e1a61985679f1265447818696794b28515d99e84",
"size": "1436",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "libs/libzq/base/serialize.lua",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "6525"
},
{
"name": "C",
"bytes": "2156"
},
{
"name": "C++",
"bytes": "207720"
},
{
"name": "GLSL",
"bytes": "8710"
},
{
"name": "Java",
"bytes": "36937"
},
{
"name": "Lua",
"bytes": "3226387"
},
{
"name": "Makefile",
"bytes": "4774"
},
{
"name": "Objective-C",
"bytes": "12222"
},
{
"name": "Objective-C++",
"bytes": "40986"
},
{
"name": "PHP",
"bytes": "70387"
},
{
"name": "Python",
"bytes": "850"
},
{
"name": "Shell",
"bytes": "10195"
}
],
"symlink_target": ""
} |
namespace ViewStateOptimizer.FileStorage
{
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Web.UI;
/// <summary>
/// This class implements storing the ViewState contents in the files.
/// </summary>
public class FileViewStateOptimizer : BaseViewStateOptimizer
{
/// <summary>
/// Initializes a new instance of the ViewStateOptimizer.FileViewStateOptimizer class.
/// </summary>
/// <param name="page">The System.Web.UI.Page that the view state persistence mechanism is created for.</param>
public FileViewStateOptimizer(Page page)
: base(page)
{
}
/// <summary>
/// Load the ViewState contents into string using the Session for storing the file path.
/// </summary>
/// <returns>Returns the ViewState contents</returns>
public override string LoadViewStateContents()
{
// Don't make anything at the first postback
if (!Page.IsPostBack) return null;
// Get the hashed key from the form
string vsHashedKey = Page.Request.Form[ViewStateOptimizerHelper.Section.FileViewStateOptimizerConfiguration.ViewStateKey];
// Checks the existed the hashed key or not?
if (String.IsNullOrEmpty(vsHashedKey) ||
!vsHashedKey.StartsWith(ViewStateOptimizerHelper.Section.FileViewStateOptimizerConfiguration.ViewStatePrefixValue))
{
throw new ViewStateException();
}
// --- Gets the file path which stored the ViewState contents.
IStateFormatter frmt = StateFormatter;
var salt = Page.Session[vsHashedKey].ToString();
var vsFile = Page.Session[ViewStateOptimizerSecurity.GenerateHashStringBySalt(vsHashedKey, salt)].ToString();
// --- End
// --- Reads the file and return all ViewState contents
if (!String.IsNullOrEmpty(vsFile))
{
if (File.Exists(vsFile))
{
return File.ReadAllText(vsFile);
}
}
// --- End
return null;
}
/// <summary>
/// Save the ViewState contents to the specified file path which stored in the Session.
/// </summary>
/// <param name="viewStateContents">ViewState contents</param>
/// <returns>Returns true if saving OK, otherwise will be false</returns>
public override bool SaveViewStateContents(string viewStateContents)
{
try
{
if (ViewState != null || ControlState != null)
{
// Checks the existed session or not?
if (Page.Session == null)
{
throw new InvalidOperationException("Session is required for FilePageStatePersister.");
}
string vsFile, vsHashedKey, salt;
if (!Page.IsPostBack) // For the first postback
{
// --- Create the unique key for each session each user
var sessionId = Page.Session.SessionID;
var pageUrl = Page.Request.Path;
var vsKey = string.Format("{0}_{1}_{2}_{3}", Guid.NewGuid(), pageUrl, sessionId,
DateTime.Now.Ticks);
vsKey = vsKey.Replace("/", String.Empty);
var vsFileName = vsKey + ".vso";
// --- End
// --- Create a new directory with the specified path if no exists.
var vsPath = Page.MapPath(ViewStateOptimizerHelper.Section.FileViewStateOptimizerConfiguration.ViewStateStorageRelativeFolder);
if (!Directory.Exists(vsPath))
{
Directory.CreateDirectory(vsPath);
}
vsFile = Path.Combine(vsPath, vsFileName);
// --- End
// --- Create new session based upon hash key to secure the viewstate contents
vsHashedKey = ViewStateOptimizerHelper.Section.FileViewStateOptimizerConfiguration.ViewStatePrefixValue + "_" + Convert.ToBase64String(ViewStateOptimizerSecurity.GenerateHash(vsKey));
salt = ViewStateOptimizerSecurity.GenerateSaltString(50);
Page.Session[vsHashedKey] = salt;
Page.Session[ViewStateOptimizerSecurity.GenerateHashStringBySalt(vsHashedKey, salt)] = vsFile;
// --- End
}
else // For the postbacks later
{
// --- Gets the hashed key from the form
vsHashedKey = Page.Request.Form[ViewStateOptimizerHelper.Section.FileViewStateOptimizerConfiguration.ViewStateKey];
if (String.IsNullOrEmpty(vsHashedKey))
{
throw new ViewStateException();
}
// --- End
// --- Gets the specified file path which stored in the Session
salt = Page.Session[vsHashedKey].ToString();
vsFile = Page.Session[ViewStateOptimizerSecurity.GenerateHashStringBySalt(vsHashedKey, salt)].ToString();
if (string.IsNullOrEmpty(vsFile))
{
throw new ViewStateException();
}
// --- End
}
// Write all ViewState contents to the specified file
File.WriteAllText(vsFile, viewStateContents);
// Register a new hidden field to the client-side with the ViewState key and hashed key
Page.ClientScript.RegisterHiddenField(ViewStateOptimizerHelper.Section.FileViewStateOptimizerConfiguration.ViewStateKey, vsHashedKey);
return true;
}
return false;
}
catch
{
return false;
}
}
}
}
| {
"content_hash": "b1771a86b4b778b11058f727448960f5",
"timestamp": "",
"source": "github",
"line_count": 143,
"max_line_length": 189,
"avg_line_length": 34.53146853146853,
"alnum_prop": 0.6952207371405428,
"repo_name": "congdongdotnet/ViewStateOptimizer",
"id": "99575de0e5d2e69a217303dc320c1f52f6bda809",
"size": "4940",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ViewStateOptimizer/FileStorage/FileViewStateOptimizer.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "1544"
},
{
"name": "C#",
"bytes": "24279"
}
],
"symlink_target": ""
} |
package org.apache.tajo.algebra;
import com.google.common.base.Objects;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class DateLiteral extends Expr {
@Expose @SerializedName("Date")
private DateValue date;
public DateLiteral(DateValue date) {
super(OpType.DateLiteral);
this.date = date;
}
public DateValue getDate() {
return date;
}
public String toString() {
return date.toString();
}
public int hashCode() {
return Objects.hashCode(date);
}
@Override
boolean equalsTo(Expr expr) {
if (expr instanceof DateLiteral) {
DateLiteral another = (DateLiteral) expr;
return date.equals(another.date);
}
return false;
}
@Override
public Object clone() throws CloneNotSupportedException {
DateLiteral newDate = (DateLiteral) super.clone();
newDate.date = date;
return newDate;
}
}
| {
"content_hash": "78f0896ee589458c0bdb8b3630c464c8",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 59,
"avg_line_length": 20.6,
"alnum_prop": 0.6957928802588996,
"repo_name": "yeeunshim/tajo_test",
"id": "297a44ef4f3ff2b96f5fe5c2db6dffdf92322d5b",
"size": "1733",
"binary": false,
"copies": "2",
"ref": "refs/heads/yeeun",
"path": "tajo-algebra/src/main/java/org/apache/tajo/algebra/DateLiteral.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "40820"
},
{
"name": "CSS",
"bytes": "3794"
},
{
"name": "Java",
"bytes": "6319806"
},
{
"name": "JavaScript",
"bytes": "502571"
},
{
"name": "Python",
"bytes": "18628"
},
{
"name": "Shell",
"bytes": "64783"
},
{
"name": "XSLT",
"bytes": "1329"
}
],
"symlink_target": ""
} |
'''
This script helps you scrap stock data avaliable on Bloomberg Finance
and store them locally.
Please obey applicable local and federal laws and applicable API term of use
when using this scripts. I, the creater of this script, will not be responsible
for any legal issues resulting from the use of this script.
@author Gan Tu
@version python 2 or python 3
[HOW TO CHANGE PYTHON VERSION]
This script by default should be run by Python 2.
To use this in Python 3, change the followings:
1) change ALL occurrences of "urllib" to "urllib.request".
'''
import urllib
import re
import json
import os
# Stock Symbols Initialization
# Feel free to modify the file source to contain stock symbols you plan to scrap fro
stocks = open("nasdaq_symbols.txt", "r").read().split("\n")
# URL Initialization
urlPrefix = "http://www.bloomberg.com/markets/api/bulk-time-series/price/"
urlAffix = "%3AUS?timeFrame="
# Only four of these are valid options for now
# 1_Day will scrap minute by minute data for one day, while others will be daily close price
# Feel free to modify them for your own need
options = ["1_DAY", "1_MONTH", "1_YEAR", "5_YEAR"]
def setup():
try:
os.mkdir("data")
except Exception as e:
pass
for option in options:
try:
os.mkdir("data/" + option + "/")
except Exception as e:
pass
def scrap():
i = 0
while i < len(stocks):
for option in options:
file = open("data/" + option + "/" + stocks[i] + ".txt", "w")
file.close()
htmltext = urllib.urlopen(urlPrefix + stocks[i] + urlAffix + option)
try:
data = json.load(htmltext)[0]["price"]
key = "date"
if option == "1_DAY":
key = "dateTime"
file = open("data/" + option + "/" + stocks[i] + ".txt", "a")
for price in data:
file.write(stocks[i] + "," + price[key] + "," + str(price["value"]) + "\n")
file.close()
except Exception as e:
pass
i += 1
if __name__ == "__main__":
setup()
scrap()
| {
"content_hash": "89f216fe9ed594268a09ac220bede5d6",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 95,
"avg_line_length": 29.31081081081081,
"alnum_prop": 0.5956662056247118,
"repo_name": "Michael-Tu/tools",
"id": "6740dbc5cd1d471f34b6ff0a348f444320239e03",
"size": "2169",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "stock_scraping/stock_price_scraping_to_local.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "15757"
},
{
"name": "JavaScript",
"bytes": "1408"
},
{
"name": "Makefile",
"bytes": "878"
},
{
"name": "Python",
"bytes": "35798"
},
{
"name": "Shell",
"bytes": "1875"
}
],
"symlink_target": ""
} |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal sealed class ConversionSignatureComparer : IEqualityComparer<SourceUserDefinedConversionSymbol>
{
private static readonly ConversionSignatureComparer s_comparer = new ConversionSignatureComparer();
public static ConversionSignatureComparer Comparer
{
get
{
return s_comparer;
}
}
private ConversionSignatureComparer()
{
}
public bool Equals(SourceUserDefinedConversionSymbol member1, SourceUserDefinedConversionSymbol member2)
{
if (ReferenceEquals(member1, member2))
{
return true;
}
if (ReferenceEquals(member1, null) || ReferenceEquals(member2, null))
{
return false;
}
// SPEC: The signature of a conversion operator consists of the source type and the
// SPEC: target type. The implicit or explicit classification of a conversion operator
// SPEC: is not part of the operator's signature.
// We might be in an error recovery situation in which there are too many or too
// few formal parameters declared. If we are, just say that they are unequal.
if (member1.ParameterCount != 1 || member2.ParameterCount != 1)
{
return false;
}
return member1.ReturnType.Equals(member2.ReturnType, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)
&& member1.ParameterTypesWithAnnotations[0].Equals(member2.ParameterTypesWithAnnotations[0], TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes);
}
public int GetHashCode(SourceUserDefinedConversionSymbol member)
{
if ((object)member == null)
{
return 0;
}
int hash = 1;
hash = Hash.Combine(member.ReturnType.GetHashCode(), hash);
if (member.ParameterCount != 1)
{
return hash;
}
hash = Hash.Combine(member.GetParameterType(0).GetHashCode(), hash);
return hash;
}
}
}
| {
"content_hash": "ba125b588c40a34544f54f00b48e6c29",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 212,
"avg_line_length": 37.24285714285714,
"alnum_prop": 0.6267740698120445,
"repo_name": "agocke/roslyn",
"id": "2e50a4f99c5242b6cb8aed66e8d70d5f53f2d4c6",
"size": "2609",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "src/Compilers/CSharp/Portable/Symbols/ConversionSignatureComparer.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "1C Enterprise",
"bytes": "289100"
},
{
"name": "Batchfile",
"bytes": "9059"
},
{
"name": "C#",
"bytes": "126326705"
},
{
"name": "C++",
"bytes": "5602"
},
{
"name": "CMake",
"bytes": "8276"
},
{
"name": "Dockerfile",
"bytes": "2450"
},
{
"name": "F#",
"bytes": "549"
},
{
"name": "PowerShell",
"bytes": "237208"
},
{
"name": "Shell",
"bytes": "94927"
},
{
"name": "Visual Basic .NET",
"bytes": "70527543"
}
],
"symlink_target": ""
} |
var count = 0;
var jive = require("jive-sdk");
var q = require('q');
var sampleOauth = require("./routes/oauth/sampleOauth") ;
var activities = require('./activities' );
var jive_to_podio_syncing = require('./jive_to_podio_syncing') ;
//var lastTime=0;
exports.task = new jive.tasks.build(
// runnable
function () {
jive.extstreams.findByDefinitionName( '{{{TILE_NAME}}}' ).then( function(instances) {
//var now = new Date();
//console.log( "+ Podio Activity Stream task ...." + now.getTime() + " elapse=" + (now.getTime() - lastTime) ) ;
// lastTime = now.getTime();
if ( instances ) {
//if (0) {
instances.forEach( function( instance ) {
var config = instance['config'];
if ( config && config['posting'] === 'off' ) {
return;
}
activities.pullActivity(instance).then( function(data) {
var promise = q.resolve(1);
data.forEach(function (activity) {
delete activity['podioCreatedDate'];
console.log( "{{{TILE_NAME}}} push: ", JSON.stringify(activity));
promise = promise.thenResolve(jive.extstreams.pushActivity(instance, activity));
});
promise = promise.catch(function(err) {
jive.logger.error('Error pushing activity to Jive', err);
});
return promise;
}).then( function() {
activities.pullComments(instance).then( function(comments) {
//console.log("got " + comments.length + " comment activity record(s) from Podio") ;
var promise = q.resolve(1);
comments.forEach(function (comment) {
delete comment['podioCreatedDate'];
var externalActivityID = comment['externalActivityID'];
delete comment['externalActivityID'];
promise = promise.thenResolve(jive.extstreams.commentOnActivityByExternalID(instance,
externalActivityID, comment));
});
promise = promise.catch(function(err) {
jive.logger.error('Error pushing comments to Jive', err);
});
return promise;
});
}).then ( function() {
jive_to_podio_syncing.jiveCommentsToPodio(instance).then( function(data) {
console.log( "got " + data.length + " comment record(s) from Jive");
if (data.length > 0)
console.log( "got one! (or more") ;
console.log( data );
});
});
});
}
});
}
// interval, 5000 = 5 secs
, 10000 );
| {
"content_hash": "e8bb7deed34a93f381ed535ccd90642c",
"timestamp": "",
"source": "github",
"line_count": 79,
"max_line_length": 117,
"avg_line_length": 40.949367088607595,
"alnum_prop": 0.4476043276661515,
"repo_name": "matthewmccullough/jive-sdk",
"id": "586de972d6f1e07a2eadc42f5a02a5337e2660b7",
"size": "3857",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "jive-sdk-service/generator/examples/example-podio/tiles/PodioActivity/backend/datapusher.js",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "a4fc651bd5925a4c21da716341dc02dc",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "3e44de4502c69f963a649260922e34176b7771d1",
"size": "185",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Euphorbiaceae/Ricinocarpus/Ricinocarpus macrostachyodes/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.