text
stringlengths 2
1.04M
| meta
dict |
---|---|
//---------------------------------------------------------------------
// <copyright file="DataSourceManager.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------
namespace Microsoft.Test.OData.Services.ODataWCFService.DataSource
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.Caching;
using System.ServiceModel;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Hosting;
public static class DataSourceManager
{
private const string CurrentDataSourceTypeRequestKey = "MicrosoftODataDataSourceType";
private const string CurrentDataSourceInstanceSessionKeyFormat = "MicrosoftODataDataSource_{0}";
public static IODataDataSource GetCurrentDataSource()
{
var dataSourceType = default(Type);
if (HostingEnvironment.IsHosted)
{
dataSourceType = (Type)HttpContext.Current.Items[CurrentDataSourceTypeRequestKey];
}
else
{
dataSourceType = (Type)Thread.GetData(Thread.GetNamedDataSlot(CurrentDataSourceTypeRequestKey));
}
return GetCurrentDataSource(dataSourceType, () => (IODataDataSource)Utility.QuickCreateInstance(dataSourceType));
}
public static TDataSource GetCurrentDataSource<TDataSource>()
where TDataSource : class, IODataDataSource, new()
{
return (TDataSource)GetCurrentDataSource(typeof(TDataSource), () => new TDataSource());
}
public static void EnsureCurrentDataSource<TDataSource>()
where TDataSource : class, IODataDataSource, new()
{
if (HostingEnvironment.IsHosted)
{
HttpContext.Current.Items[CurrentDataSourceTypeRequestKey] = typeof(TDataSource);
}
else
{
if (Thread.GetData(Thread.GetNamedDataSlot(CurrentDataSourceTypeRequestKey)) == null)
{
Thread.SetData(Thread.GetNamedDataSlot(CurrentDataSourceTypeRequestKey), typeof(TDataSource));
OperationContext.Current.OperationCompleted += delegate { Thread.SetData(Thread.GetNamedDataSlot(CurrentDataSourceTypeRequestKey), null); };
}
}
// call this method to ensure data source creation
GetCurrentDataSource(typeof(TDataSource), () => new TDataSource());
}
private static IODataDataSource GetCurrentDataSource(Type dataSourceType, Func<IODataDataSource> dataSourceCreator)
{
var result = default(IODataDataSource);
var dataSourceSessionKey = string.Format(CurrentDataSourceInstanceSessionKeyFormat, dataSourceType.AssemblyQualifiedName);
if (HostingEnvironment.IsHosted)
{
// here is deployed on IIS based host, e.g. Azure or IISExpress
var session = HttpContext.Current.Session;
var dataSource = (IODataDataSource)session[dataSourceSessionKey];
if (dataSource == null)
{
dataSource = dataSourceCreator();
session[dataSourceSessionKey] = dataSource;
dataSource.Reset();
dataSource.Initialize();
}
result = dataSource;
}
else
{
// here is deployed on Non-IIS based host, e.g. unit test
if (MemoryCache.Default.Contains(dataSourceSessionKey))
{
result = (IODataDataSource)MemoryCache.Default.Get(dataSourceSessionKey);
}
else
{
var dataSource = dataSourceCreator();
MemoryCache.Default.Add(dataSourceSessionKey, dataSource, new CacheItemPolicy());
dataSource.Reset();
dataSource.Initialize();
result = dataSource;
}
}
return result;
}
}
}
| {
"content_hash": "eca203c709ab459c2d130077c4b87906",
"timestamp": "",
"source": "github",
"line_count": 109,
"max_line_length": 160,
"avg_line_length": 41.04587155963303,
"alnum_prop": 0.5708538220831471,
"repo_name": "mijin2185/odata.net",
"id": "eed6dbc0ea41025c946ba0b3595b6d35bee47321",
"size": "4476",
"binary": false,
"copies": "12",
"ref": "refs/heads/master",
"path": "test/EndToEndTests/Services/ODataWCFLibrary/DataSource/DataSourceManager.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "6954"
},
{
"name": "Batchfile",
"bytes": "1588"
},
{
"name": "C#",
"bytes": "77147399"
},
{
"name": "HTML",
"bytes": "9302"
},
{
"name": "Visual Basic",
"bytes": "7824314"
},
{
"name": "XSLT",
"bytes": "19962"
}
],
"symlink_target": ""
} |
<?php namespace Kris\LaravelFormBuilder\Fields;
use Kris\LaravelFormBuilder\Form;
class ChildFormType extends ParentType
{
/**
* @var Form
*/
protected $form;
/**
* @inheritdoc
*/
protected function getTemplate()
{
return 'child_form';
}
/**
* @return Form
*/
public function getForm()
{
return $this->form;
}
/**
* @inheritdoc
*/
protected function getDefaults()
{
return [
'class' => null,
'value' => null,
'formOptions' => [],
'data' => [],
'exclude' => []
];
}
/**
* @return mixed|void
*/
protected function createChildren()
{
$this->form = $this->getClassFromOptions();
if ($this->form->getFormOption('files')) {
$this->parent->setFormOption('files', true);
}
$model = $this->getOption($this->valueProperty);
if ($model !== null) {
foreach ($this->form->getFields() as $name => $field) {
$field->setValue($this->getModelValueAttribute($model, $name));
}
}
$this->children = $this->form->getFields();
}
/**
* @return Form
* @throws \Exception
*/
protected function getClassFromOptions()
{
if ($this->form instanceof Form) {
return $this->form->setName($this->name);
}
$class = $this->getOption('class');
if (!$class) {
throw new \InvalidArgumentException(
'Please provide full name or instance of Form class.'
);
}
if (is_string($class)) {
$formOptions = array_merge(
['model' => $this->parent->getModel(), 'name' => $this->name],
$this->getOption('formOptions')
);
$data = array_merge($this->parent->getData(), $this->getOption('data'));
return $this->parent->getFormBuilder()->create(
$class,
$formOptions,
$data
);
}
if ($class instanceof Form) {
if (!$class->getModel()) {
$class->setModel($this->parent->getModel());
}
if (!$class->getData()) {
$class->addData($this->parent->getData());
}
return $class->setName($this->name);
}
throw new \InvalidArgumentException(
'Class provided does not exist or it passed in wrong format.'
);
}
/**
* @param $method
* @param $arguments
*
* @return Form|null
*/
public function __call($method, $arguments)
{
if (method_exists($this->form, $method)) {
return call_user_func_array([$this->form, $method], $arguments);
}
throw new \BadMethodCallException(
'Method ['.$method.'] does not exist on form ['.get_class($this->form).']'
);
}
}
| {
"content_hash": "1c54b553aa52833a01aebd4ee9ebbe8f",
"timestamp": "",
"source": "github",
"line_count": 129,
"max_line_length": 86,
"avg_line_length": 23.54263565891473,
"alnum_prop": 0.47942048073757,
"repo_name": "kristijanhusak/laravel4-form-builder",
"id": "0c6dda3f63f87b8d48c587ed62be7552762bd5b1",
"size": "3037",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "src/Kris/LaravelFormBuilder/Fields/ChildFormType.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "134136"
}
],
"symlink_target": ""
} |
const Sequelize = require('sequelize');
const db = require('../_db');
const EventType = db.define('eventType', {
name: {
type: Sequelize.STRING
}
},
{
}
);
module.exports = EventType;
| {
"content_hash": "91b0d3fa8c2e6e7baed587bffa0d5102",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 42,
"avg_line_length": 13.928571428571429,
"alnum_prop": 0.6256410256410256,
"repo_name": "quirkycorgi/Agamari",
"id": "8ae7be63dc8ff14b1e7c56048fb367d13f518e48",
"size": "195",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server/db/models/eventType.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3814"
},
{
"name": "HTML",
"bytes": "1483"
},
{
"name": "JavaScript",
"bytes": "177875"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc -->
<title>TextInterpreter (GWT Javadoc)</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="TextInterpreter (GWT Javadoc)";
}
}
catch(err) {
}
//-->
var methods = {"i0":10};
var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/TextInterpreter.html">Use</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">GWT 2.8.0-rc1</div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../com/google/gwt/uibinder/elementparsers/TabPanelParser.html" title="class in com.google.gwt.uibinder.elementparsers"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../com/google/gwt/uibinder/elementparsers/TextPlaceholderInterpreter.html" title="class in com.google.gwt.uibinder.elementparsers"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/google/gwt/uibinder/elementparsers/TextInterpreter.html" target="_top">Frames</a></li>
<li><a href="TextInterpreter.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">com.google.gwt.uibinder.elementparsers</div>
<h2 title="Class TextInterpreter" class="title">Class TextInterpreter</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>com.google.gwt.uibinder.elementparsers.TextInterpreter</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd>com.google.gwt.uibinder.rebind.XMLElement.Interpreter<java.lang.String></dd>
</dl>
<hr>
<br>
<pre>public class <span class="typeNameLabel">TextInterpreter</span>
extends java.lang.Object
implements com.google.gwt.uibinder.rebind.XMLElement.Interpreter<java.lang.String></pre>
<div class="block">The interpreter of choice for calls to <code>XMLElement.consumeInnerText(com.google.gwt.uibinder.rebind.XMLElement.PostProcessingInterpreter<java.lang.String>)</code>.
It handles <m:msg/> elements, replacing them with references to Messages
interface calls.
<P>
Calls to <code>XMLElement.consumeInnerHtml(com.google.gwt.uibinder.rebind.XMLElement.Interpreter<java.lang.String>)</code> should instead use
<a href="../../../../../com/google/gwt/uibinder/elementparsers/HtmlInterpreter.html" title="class in com.google.gwt.uibinder.elementparsers"><code>HtmlInterpreter</code></a></div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../com/google/gwt/uibinder/elementparsers/TextInterpreter.html#TextInterpreter-com.google.gwt.uibinder.rebind.UiBinderWriter-">TextInterpreter</a></span>(com.google.gwt.uibinder.rebind.UiBinderWriter writer)</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/google/gwt/uibinder/elementparsers/TextInterpreter.html#interpretElement-com.google.gwt.uibinder.rebind.XMLElement-">interpretElement</a></span>(com.google.gwt.uibinder.rebind.XMLElement elem)</code>
<div class="block">Given an XMLElement, return its filtered value.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="TextInterpreter-com.google.gwt.uibinder.rebind.UiBinderWriter-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>TextInterpreter</h4>
<pre>public TextInterpreter(com.google.gwt.uibinder.rebind.UiBinderWriter writer)</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="interpretElement-com.google.gwt.uibinder.rebind.XMLElement-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>interpretElement</h4>
<pre>public java.lang.String interpretElement(com.google.gwt.uibinder.rebind.XMLElement elem)
throws <a href="../../../../../com/google/gwt/core/ext/UnableToCompleteException.html" title="class in com.google.gwt.core.ext">UnableToCompleteException</a></pre>
<div class="block"><span class="descfrmTypeLabel">Description copied from interface: <code>com.google.gwt.uibinder.rebind.XMLElement.Interpreter</code></span></div>
<div class="block">Given an XMLElement, return its filtered value.</div>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code>interpretElement</code> in interface <code>com.google.gwt.uibinder.rebind.XMLElement.Interpreter<java.lang.String></code></dd>
<dt><span class="throwsLabel">Throws:</span></dt>
<dd><code><a href="../../../../../com/google/gwt/core/ext/UnableToCompleteException.html" title="class in com.google.gwt.core.ext">UnableToCompleteException</a></code> - on error</dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/TextInterpreter.html">Use</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">GWT 2.8.0-rc1</div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../com/google/gwt/uibinder/elementparsers/TabPanelParser.html" title="class in com.google.gwt.uibinder.elementparsers"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../com/google/gwt/uibinder/elementparsers/TextPlaceholderInterpreter.html" title="class in com.google.gwt.uibinder.elementparsers"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/google/gwt/uibinder/elementparsers/TextInterpreter.html" target="_top">Frames</a></li>
<li><a href="TextInterpreter.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| {
"content_hash": "ef7653e02eee54518d5d36764b1ee9c3",
"timestamp": "",
"source": "github",
"line_count": 290,
"max_line_length": 391,
"avg_line_length": 39.748275862068965,
"alnum_prop": 0.6646135160926521,
"repo_name": "dougkoellmer/swarm",
"id": "f9e43f9b18d6162e6a3a25d53ce69160cc97816d",
"size": "11527",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tools/gwt/doc/javadoc/com/google/gwt/uibinder/elementparsers/TextInterpreter.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "72"
},
{
"name": "CSS",
"bytes": "25294"
},
{
"name": "Java",
"bytes": "1386664"
},
{
"name": "JavaScript",
"bytes": "401014"
},
{
"name": "Perl",
"bytes": "5572"
},
{
"name": "Shell",
"bytes": "6620"
}
],
"symlink_target": ""
} |
#import <Foundation/Foundation.h>
struct CKComponentContextPreviousState {
id key;
id originalValue;
id newValue;
};
@protocol CKComponentContextDynamicLookup <NSObject>
- (id)contextValueForClass:(Class)c;
@end
struct CKComponentContextContents {
/** The items stored in CKComponentContext. */
NSDictionary<Class, id> *objects;
/** The dynamic lookup implementation, if any; used for classes not found in objects. */
id<CKComponentContextDynamicLookup> dynamicLookup;
bool operator==(const CKComponentContextContents&) const;
bool operator!=(const CKComponentContextContents&) const;
};
struct CKComponentContextPreviousDynamicLookupState {
NSDictionary *previousContents;
id<CKComponentContextDynamicLookup> originalLookup;
id<CKComponentContextDynamicLookup> newLookup;
};
/** Internal helper class. Avoid using this externally. */
struct CKComponentContextHelper {
static CKComponentContextPreviousState store(id key, id object);
static void restore(const CKComponentContextPreviousState &storeResult);
static id fetch(id key);
/**
Returns a structure with all the items that are currently in CKComponentContext.
This could be used to bridge CKComponentContext items to another language or system.
*/
static CKComponentContextContents fetchAll();
/**
Removes all items currently stored in CKComponentContext, and specifies an object that should be consulted
for each lookup instead. This can be used to bridge CKComponentContext to another language or system,
deferring any translation cost to each lookup instead of performing it eagerly.
Since this removes all currently existing items from CKComponentContext, you should always call fetchAll()
first and supply those values to the lookup for it to use. This includes the task of consulting the
*previous* dynamic lookup, if one was already specified.
If new items are stored while the dynamic lookup is active, those items will be returned immediately instead
of consulting the dynamic lookup for as long as they are present. For example:
store([Foo class], foo1);
setDynamicLookup(lookup);
fetch([Foo class]); // consults lookup
store([Foo class], foo2);
fetch([Foo class]); // returns foo2 without consulting lookup
*/
static CKComponentContextPreviousDynamicLookupState setDynamicLookup(id<CKComponentContextDynamicLookup> lookup);
/** Restores the state of CKComponentContext to what it was before a call to setDynamicLookup. */
static void restoreDynamicLookup(const CKComponentContextPreviousDynamicLookupState &setResult);
};
| {
"content_hash": "f903f2f17bcc77aa3e7a29091bb44f97",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 115,
"avg_line_length": 42,
"alnum_prop": 0.782258064516129,
"repo_name": "eczarny/componentkit",
"id": "05733a8bed63994aec392960b3dcd0719ed168fe",
"size": "2919",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "ComponentKit/Utilities/CKComponentContextHelper.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "623"
},
{
"name": "C++",
"bytes": "2524"
},
{
"name": "Objective-C",
"bytes": "344668"
},
{
"name": "Objective-C++",
"bytes": "982486"
},
{
"name": "Shell",
"bytes": "1785"
}
],
"symlink_target": ""
} |
/* nvd3 version 1.8.3-dev (https://github.com/novus/nvd3) 2016-04-26 */
(function(){
// set up main nv object
var nv = {};
// the major global objects under the nv namespace
nv.dev = false; //set false when in production
nv.tooltip = nv.tooltip || {}; // For the tooltip system
nv.utils = nv.utils || {}; // Utility subsystem
nv.models = nv.models || {}; //stores all the possible models/components
nv.charts = {}; //stores all the ready to use charts
nv.logs = {}; //stores some statistics and potential error messages
nv.dom = {}; //DOM manipulation functions
// Node/CommonJS - require D3
if (typeof(module) !== 'undefined' && typeof(exports) !== 'undefined' && typeof(d3) == 'undefined') {
d3 = require('d3');
}
nv.dispatch = d3.dispatch('render_start', 'render_end');
// Function bind polyfill
// Needed ONLY for phantomJS as it's missing until version 2.0 which is unreleased as of this comment
// https://github.com/ariya/phantomjs/issues/10522
// http://kangax.github.io/compat-table/es5/#Function.prototype.bind
// phantomJS is used for running the test suite
if (!Function.prototype.bind) {
Function.prototype.bind = function (oThis) {
if (typeof this !== "function") {
// closest thing possible to the ECMAScript 5 internal IsCallable function
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function () {},
fBound = function () {
return fToBind.apply(this instanceof fNOP && oThis
? this
: oThis,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}
// Development render timers - disabled if dev = false
if (nv.dev) {
nv.dispatch.on('render_start', function(e) {
nv.logs.startTime = +new Date();
});
nv.dispatch.on('render_end', function(e) {
nv.logs.endTime = +new Date();
nv.logs.totalTime = nv.logs.endTime - nv.logs.startTime;
nv.log('total', nv.logs.totalTime); // used for development, to keep track of graph generation times
});
}
// Logs all arguments, and returns the last so you can test things in place
// Note: in IE8 console.log is an object not a function, and if modernizr is used
// then calling Function.prototype.bind with with anything other than a function
// causes a TypeError to be thrown.
nv.log = function() {
if (nv.dev && window.console && console.log && console.log.apply)
console.log.apply(console, arguments);
else if (nv.dev && window.console && typeof console.log == "function" && Function.prototype.bind) {
var log = Function.prototype.bind.call(console.log, console);
log.apply(console, arguments);
}
return arguments[arguments.length - 1];
};
// print console warning, should be used by deprecated functions
nv.deprecated = function(name, info) {
if (console && console.warn) {
console.warn('nvd3 warning: `' + name + '` has been deprecated. ', info || '');
}
};
// The nv.render function is used to queue up chart rendering
// in non-blocking async functions.
// When all queued charts are done rendering, nv.dispatch.render_end is invoked.
nv.render = function render(step) {
// number of graphs to generate in each timeout loop
step = step || 1;
nv.render.active = true;
nv.dispatch.render_start();
var renderLoop = function() {
var chart, graph;
for (var i = 0; i < step && (graph = nv.render.queue[i]); i++) {
chart = graph.generate();
if (typeof graph.callback == typeof(Function)) graph.callback(chart);
}
nv.render.queue.splice(0, i);
if (nv.render.queue.length) {
setTimeout(renderLoop);
}
else {
nv.dispatch.render_end();
nv.render.active = false;
}
};
setTimeout(renderLoop);
};
nv.render.active = false;
nv.render.queue = [];
/*
Adds a chart to the async rendering queue. This method can take arguments in two forms:
nv.addGraph({
generate: <Function>
callback: <Function>
})
or
nv.addGraph(<generate Function>, <callback Function>)
The generate function should contain code that creates the NVD3 model, sets options
on it, adds data to an SVG element, and invokes the chart model. The generate function
should return the chart model. See examples/lineChart.html for a usage example.
The callback function is optional, and it is called when the generate function completes.
*/
nv.addGraph = function(obj) {
if (typeof arguments[0] === typeof(Function)) {
obj = {generate: arguments[0], callback: arguments[1]};
}
nv.render.queue.push(obj);
if (!nv.render.active) {
nv.render();
}
};
// Node/CommonJS exports
if (typeof(module) !== 'undefined' && typeof(exports) !== 'undefined') {
module.exports = nv;
}
if (typeof(window) !== 'undefined') {
window.nv = nv;
}
/* Facade for queueing DOM write operations
* with Fastdom (https://github.com/wilsonpage/fastdom)
* if available.
* This could easily be extended to support alternate
* implementations in the future.
*/
nv.dom.write = function(callback) {
if (window.fastdom !== undefined) {
return fastdom.mutate(callback);
}
return callback();
};
/* Facade for queueing DOM read operations
* with Fastdom (https://github.com/wilsonpage/fastdom)
* if available.
* This could easily be extended to support alternate
* implementations in the future.
*/
nv.dom.read = function(callback) {
if (window.fastdom !== undefined) {
return fastdom.measure(callback);
}
return callback();
};
/* Utility class to handle creation of an interactive layer.
This places a rectangle on top of the chart. When you mouse move over it, it sends a dispatch
containing the X-coordinate. It can also render a vertical line where the mouse is located.
dispatch.elementMousemove is the important event to latch onto. It is fired whenever the mouse moves over
the rectangle. The dispatch is given one object which contains the mouseX/Y location.
It also has 'pointXValue', which is the conversion of mouseX to the x-axis scale.
*/
nv.interactiveGuideline = function() {
"use strict";
var margin = { left: 0, top: 0 } //Pass the chart's top and left magins. Used to calculate the mouseX/Y.
, width = null
, height = null
, xScale = d3.scale.linear()
, dispatch = d3.dispatch('elementMousemove', 'elementMouseout', 'elementClick', 'elementDblclick', 'elementMouseDown', 'elementMouseUp')
, showGuideLine = true
, svgContainer = null // Must pass the chart's svg, we'll use its mousemove event.
, tooltip = nv.models.tooltip()
, isMSIE = "ActiveXObject" in window // Checkt if IE by looking for activeX.
;
tooltip
.duration(0)
.hideDelay(0)
.hidden(false);
function layer(selection) {
selection.each(function(data) {
var container = d3.select(this);
var availableWidth = (width || 960), availableHeight = (height || 400);
var wrap = container.selectAll("g.nv-wrap.nv-interactiveLineLayer")
.data([data]);
var wrapEnter = wrap.enter()
.append("g").attr("class", " nv-wrap nv-interactiveLineLayer");
wrapEnter.append("g").attr("class","nv-interactiveGuideLine");
if (!svgContainer) {
return;
}
function mouseHandler() {
var d3mouse = d3.mouse(this);
var mouseX = d3mouse[0];
var mouseY = d3mouse[1];
var subtractMargin = true;
var mouseOutAnyReason = false;
if (isMSIE) {
/*
D3.js (or maybe SVG.getScreenCTM) has a nasty bug in Internet Explorer 10.
d3.mouse() returns incorrect X,Y mouse coordinates when mouse moving
over a rect in IE 10.
However, d3.event.offsetX/Y also returns the mouse coordinates
relative to the triggering <rect>. So we use offsetX/Y on IE.
*/
mouseX = d3.event.offsetX;
mouseY = d3.event.offsetY;
/*
On IE, if you attach a mouse event listener to the <svg> container,
it will actually trigger it for all the child elements (like <path>, <circle>, etc).
When this happens on IE, the offsetX/Y is set to where ever the child element
is located.
As a result, we do NOT need to subtract margins to figure out the mouse X/Y
position under this scenario. Removing the line below *will* cause
the interactive layer to not work right on IE.
*/
if(d3.event.target.tagName !== "svg") {
subtractMargin = false;
}
if (d3.event.target.className.baseVal.match("nv-legend")) {
mouseOutAnyReason = true;
}
}
if(subtractMargin) {
mouseX -= margin.left;
mouseY -= margin.top;
}
/* If mouseX/Y is outside of the chart's bounds,
trigger a mouseOut event.
*/
if (d3.event.type === 'mouseout'
|| mouseX < 0 || mouseY < 0
|| mouseX > availableWidth || mouseY > availableHeight
|| (d3.event.relatedTarget && d3.event.relatedTarget.ownerSVGElement === undefined)
|| mouseOutAnyReason
) {
if (isMSIE) {
if (d3.event.relatedTarget
&& d3.event.relatedTarget.ownerSVGElement === undefined
&& (d3.event.relatedTarget.className === undefined
|| d3.event.relatedTarget.className.match(tooltip.nvPointerEventsClass))) {
return;
}
}
dispatch.elementMouseout({
mouseX: mouseX,
mouseY: mouseY
});
layer.renderGuideLine(null); //hide the guideline
tooltip.hidden(true);
return;
} else {
tooltip.hidden(false);
}
var scaleIsOrdinal = typeof xScale.rangeBands === 'function';
var pointXValue = undefined;
// Ordinal scale has no invert method
if (scaleIsOrdinal) {
var elementIndex = d3.bisect(xScale.range(), mouseX) - 1;
// Check if mouseX is in the range band
if (xScale.range()[elementIndex] + xScale.rangeBand() >= mouseX) {
pointXValue = xScale.domain()[d3.bisect(xScale.range(), mouseX) - 1];
}
else {
dispatch.elementMouseout({
mouseX: mouseX,
mouseY: mouseY
});
layer.renderGuideLine(null); //hide the guideline
tooltip.hidden(true);
return;
}
}
else {
pointXValue = xScale.invert(mouseX);
}
dispatch.elementMousemove({
mouseX: mouseX,
mouseY: mouseY,
pointXValue: pointXValue
});
//If user double clicks the layer, fire a elementDblclick
if (d3.event.type === "dblclick") {
dispatch.elementDblclick({
mouseX: mouseX,
mouseY: mouseY,
pointXValue: pointXValue
});
}
// if user single clicks the layer, fire elementClick
if (d3.event.type === 'click') {
dispatch.elementClick({
mouseX: mouseX,
mouseY: mouseY,
pointXValue: pointXValue
});
}
// if user presses mouse down the layer, fire elementMouseDown
if (d3.event.type === 'mousedown') {
dispatch.elementMouseDown({
mouseX: mouseX,
mouseY: mouseY,
pointXValue: pointXValue
});
}
// if user presses mouse down the layer, fire elementMouseUp
if (d3.event.type === 'mouseup') {
dispatch.elementMouseUp({
mouseX: mouseX,
mouseY: mouseY,
pointXValue: pointXValue
});
}
}
svgContainer
.on("touchmove",mouseHandler)
.on("mousemove",mouseHandler, true)
.on("mouseout" ,mouseHandler,true)
.on("mousedown" ,mouseHandler,true)
.on("mouseup" ,mouseHandler,true)
.on("dblclick" ,mouseHandler)
.on("click", mouseHandler)
;
layer.guideLine = null;
//Draws a vertical guideline at the given X postion.
layer.renderGuideLine = function(x) {
if (!showGuideLine) return;
if (layer.guideLine && layer.guideLine.attr("x1") === x) return;
nv.dom.write(function() {
var line = wrap.select(".nv-interactiveGuideLine")
.selectAll("line")
.data((x != null) ? [nv.utils.NaNtoZero(x)] : [], String);
line.enter()
.append("line")
.attr("class", "nv-guideline")
.attr("x1", function(d) { return d;})
.attr("x2", function(d) { return d;})
.attr("y1", availableHeight)
.attr("y2",0);
line.exit().remove();
});
}
});
}
layer.dispatch = dispatch;
layer.tooltip = tooltip;
layer.margin = function(_) {
if (!arguments.length) return margin;
margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
return layer;
};
layer.width = function(_) {
if (!arguments.length) return width;
width = _;
return layer;
};
layer.height = function(_) {
if (!arguments.length) return height;
height = _;
return layer;
};
layer.xScale = function(_) {
if (!arguments.length) return xScale;
xScale = _;
return layer;
};
layer.showGuideLine = function(_) {
if (!arguments.length) return showGuideLine;
showGuideLine = _;
return layer;
};
layer.svgContainer = function(_) {
if (!arguments.length) return svgContainer;
svgContainer = _;
return layer;
};
return layer;
};
/* Utility class that uses d3.bisect to find the index in a given array, where a search value can be inserted.
This is different from normal bisectLeft; this function finds the nearest index to insert the search value.
For instance, lets say your array is [1,2,3,5,10,30], and you search for 28.
Normal d3.bisectLeft will return 4, because 28 is inserted after the number 10. But interactiveBisect will return 5
because 28 is closer to 30 than 10.
Unit tests can be found in: interactiveBisectTest.html
Has the following known issues:
* Will not work if the data points move backwards (ie, 10,9,8,7, etc) or if the data points are in random order.
* Won't work if there are duplicate x coordinate values.
*/
nv.interactiveBisect = function (values, searchVal, xAccessor) {
"use strict";
if (! (values instanceof Array)) {
return null;
}
var _xAccessor;
if (typeof xAccessor !== 'function') {
_xAccessor = function(d) {
return d.x;
}
} else {
_xAccessor = xAccessor;
}
var _cmp = function(d, v) {
// Accessors are no longer passed the index of the element along with
// the element itself when invoked by d3.bisector.
//
// Starting at D3 v3.4.4, d3.bisector() started inspecting the
// function passed to determine if it should consider it an accessor
// or a comparator. This meant that accessors that take two arguments
// (expecting an index as the second parameter) are treated as
// comparators where the second argument is the search value against
// which the first argument is compared.
return _xAccessor(d) - v;
};
var bisect = d3.bisector(_cmp).left;
var index = d3.max([0, bisect(values,searchVal) - 1]);
var currentValue = _xAccessor(values[index]);
if (typeof currentValue === 'undefined') {
currentValue = index;
}
if (currentValue === searchVal) {
return index; //found exact match
}
var nextIndex = d3.min([index+1, values.length - 1]);
var nextValue = _xAccessor(values[nextIndex]);
if (typeof nextValue === 'undefined') {
nextValue = nextIndex;
}
if (Math.abs(nextValue - searchVal) >= Math.abs(currentValue - searchVal)) {
return index;
} else {
return nextIndex
}
};
/*
Returns the index in the array "values" that is closest to searchVal.
Only returns an index if searchVal is within some "threshold".
Otherwise, returns null.
*/
nv.nearestValueIndex = function (values, searchVal, threshold) {
"use strict";
var yDistMax = Infinity, indexToHighlight = null;
values.forEach(function(d,i) {
var delta = Math.abs(searchVal - d);
if ( d != null && delta <= yDistMax && delta < threshold) {
yDistMax = delta;
indexToHighlight = i;
}
});
return indexToHighlight;
};
/* Model which can be instantiated to handle tooltip rendering.
Example usage:
var tip = nv.models.tooltip().gravity('w').distance(23)
.data(myDataObject);
tip(); //just invoke the returned function to render tooltip.
*/
nv.models.tooltip = function() {
"use strict";
/*
Tooltip data. If data is given in the proper format, a consistent tooltip is generated.
Example Format of data:
{
key: "Date",
value: "August 2009",
series: [
{key: "Series 1", value: "Value 1", color: "#000"},
{key: "Series 2", value: "Value 2", color: "#00f"}
]
}
*/
var id = "nvtooltip-" + Math.floor(Math.random() * 100000) // Generates a unique id when you create a new tooltip() object.
, data = null
, gravity = 'w' // Can be 'n','s','e','w'. Determines how tooltip is positioned.
, distance = 25 // Distance to offset tooltip from the mouse location.
, snapDistance = 0 // Tolerance allowed before tooltip is moved from its current position (creates 'snapping' effect)
, classes = null // Attaches additional CSS classes to the tooltip DIV that is created.
, chartContainer = null // Parent dom element of the SVG that holds the chart.
, hidden = true // Start off hidden, toggle with hide/show functions below.
, hideDelay = 200 // Delay (in ms) before the tooltip hides after calling hide().
, tooltip = null // d3 select of the tooltip div.
, lastPosition = { left: null, top: null } // Last position the tooltip was in.
, enabled = true // True -> tooltips are rendered. False -> don't render tooltips.
, duration = 100 // Tooltip movement duration, in ms.
, headerEnabled = true // If is to show the tooltip header.
, nvPointerEventsClass = "nv-pointer-events-none" // CSS class to specify whether element should not have mouse events.
;
/*
Function that returns the position (relative to the viewport) the tooltip should be placed in.
Should return: {
left: <leftPos>,
top: <topPos>
}
*/
var position = function() {
return {
left: d3.event !== null ? d3.event.clientX : 0,
top: d3.event !== null ? d3.event.clientY : 0
};
};
// Format function for the tooltip values column.
var valueFormatter = function(d, i) {
return d;
};
// Format function for the tooltip header value.
var headerFormatter = function(d) {
return d;
};
var keyFormatter = function(d, i) {
return d;
};
// By default, the tooltip model renders a beautiful table inside a DIV.
// You can override this function if a custom tooltip is desired.
var contentGenerator = function(d) {
if (d === null) {
return '';
}
var table = d3.select(document.createElement("table"));
if (headerEnabled) {
var theadEnter = table.selectAll("thead")
.data([d])
.enter().append("thead");
theadEnter.append("tr")
.append("td")
.attr("colspan", 3)
.append("strong")
.classed("x-value", true)
.html(headerFormatter(d.value));
}
var tbodyEnter = table.selectAll("tbody")
.data([d])
.enter().append("tbody");
var trowEnter = tbodyEnter.selectAll("tr")
.data(function(p) { return p.series})
.enter()
.append("tr")
.classed("highlight", function(p) { return p.highlight});
trowEnter.append("td")
.classed("legend-color-guide",true)
.append("div")
.style("background-color", function(p) { return p.color});
trowEnter.append("td")
.classed("key",true)
.classed("total",function(p) { return !!p.total})
.html(function(p, i) { return keyFormatter(p.key, i)});
trowEnter.append("td")
.classed("value",true)
.html(function(p, i) { return valueFormatter(p.value, i) });
trowEnter.filter(function (p,i) { return p.percent !== undefined }).append("td")
.classed("percent", true)
.html(function(p, i) { return "(" + d3.format('%')(p.percent) + ")" });
trowEnter.selectAll("td").each(function(p) {
if (p.highlight) {
var opacityScale = d3.scale.linear().domain([0,1]).range(["#fff",p.color]);
var opacity = 0.6;
d3.select(this)
.style("border-bottom-color", opacityScale(opacity))
.style("border-top-color", opacityScale(opacity))
;
}
});
var html = table.node().outerHTML;
if (d.footer !== undefined)
html += "<div class='footer'>" + d.footer + "</div>";
return html;
};
var dataSeriesExists = function(d) {
if (d && d.series) {
if (nv.utils.isArray(d.series)) {
return true;
}
// if object, it's okay just convert to array of the object
if (nv.utils.isObject(d.series)) {
d.series = [d.series];
return true;
}
}
return false;
};
// Calculates the gravity offset of the tooltip. Parameter is position of tooltip
// relative to the viewport.
var calcGravityOffset = function(pos) {
var height = tooltip.node().offsetHeight,
width = tooltip.node().offsetWidth,
clientWidth = document.documentElement.clientWidth, // Don't want scrollbars.
clientHeight = document.documentElement.clientHeight, // Don't want scrollbars.
left, top, tmp;
// calculate position based on gravity
switch (gravity) {
case 'e':
left = - width - distance;
top = - (height / 2);
if(pos.left + left < 0) left = distance;
if((tmp = pos.top + top) < 0) top -= tmp;
if((tmp = pos.top + top + height) > clientHeight) top -= tmp - clientHeight;
break;
case 'w':
left = distance;
top = - (height / 2);
if (pos.left + left + width > clientWidth) left = - width - distance;
if ((tmp = pos.top + top) < 0) top -= tmp;
if ((tmp = pos.top + top + height) > clientHeight) top -= tmp - clientHeight;
break;
case 'n':
left = - (width / 2) - 5; // - 5 is an approximation of the mouse's height.
top = distance;
if (pos.top + top + height > clientHeight) top = - height - distance;
if ((tmp = pos.left + left) < 0) left -= tmp;
if ((tmp = pos.left + left + width) > clientWidth) left -= tmp - clientWidth;
break;
case 's':
left = - (width / 2);
top = - height - distance;
if (pos.top + top < 0) top = distance;
if ((tmp = pos.left + left) < 0) left -= tmp;
if ((tmp = pos.left + left + width) > clientWidth) left -= tmp - clientWidth;
break;
case 'center':
left = - (width / 2);
top = - (height / 2);
break;
default:
left = 0;
top = 0;
break;
}
return { 'left': left, 'top': top };
};
/*
Positions the tooltip in the correct place, as given by the position() function.
*/
var positionTooltip = function() {
nv.dom.read(function() {
var pos = position(),
gravityOffset = calcGravityOffset(pos),
left = pos.left + gravityOffset.left,
top = pos.top + gravityOffset.top;
// delay hiding a bit to avoid flickering
if (hidden) {
tooltip
.interrupt()
.transition()
.delay(hideDelay)
.duration(0)
.style('opacity', 0);
} else {
// using tooltip.style('transform') returns values un-usable for tween
var old_translate = 'translate(' + lastPosition.left + 'px, ' + lastPosition.top + 'px)';
var new_translate = 'translate(' + Math.round(left) + 'px, ' + Math.round(top) + 'px)';
var translateInterpolator = d3.interpolateString(old_translate, new_translate);
var is_hidden = tooltip.style('opacity') < 0.1;
tooltip
.interrupt() // cancel running transitions
.transition()
.duration(is_hidden ? 0 : duration)
// using tween since some versions of d3 can't auto-tween a translate on a div
.styleTween('transform', function (d) {
return translateInterpolator;
}, 'important')
// Safari has its own `-webkit-transform` and does not support `transform`
.styleTween('-webkit-transform', function (d) {
return translateInterpolator;
})
.style('-ms-transform', new_translate)
.style('opacity', 1);
}
lastPosition.left = left;
lastPosition.top = top;
});
};
// Creates new tooltip container, or uses existing one on DOM.
function initTooltip() {
if (!tooltip || !tooltip.node()) {
var container = chartContainer ? chartContainer : document.body;
// Create new tooltip div if it doesn't exist on DOM.
var data = [1];
tooltip = d3.select(container).selectAll('.nvtooltip').data(data);
tooltip.enter().append('div')
.attr("class", "nvtooltip " + (classes ? classes : "xy-tooltip"))
.attr("id", id)
.style("top", 0).style("left", 0)
.style('opacity', 0)
.style('position', 'fixed')
.selectAll("div, table, td, tr").classed(nvPointerEventsClass, true)
.classed(nvPointerEventsClass, true);
tooltip.exit().remove()
}
}
// Draw the tooltip onto the DOM.
function nvtooltip() {
if (!enabled) return;
if (!dataSeriesExists(data)) return;
nv.dom.write(function () {
initTooltip();
// Generate data and set it into tooltip.
// Bonus - If you override contentGenerator and return falsey you can use something like
// React or Knockout to bind the data for your tooltip.
var newContent = contentGenerator(data);
if (newContent) {
tooltip.node().innerHTML = newContent;
}
positionTooltip();
});
return nvtooltip;
}
nvtooltip.nvPointerEventsClass = nvPointerEventsClass;
nvtooltip.options = nv.utils.optionsFunc.bind(nvtooltip);
nvtooltip._options = Object.create({}, {
// simple read/write options
duration: {get: function(){return duration;}, set: function(_){duration=_;}},
gravity: {get: function(){return gravity;}, set: function(_){gravity=_;}},
distance: {get: function(){return distance;}, set: function(_){distance=_;}},
snapDistance: {get: function(){return snapDistance;}, set: function(_){snapDistance=_;}},
classes: {get: function(){return classes;}, set: function(_){classes=_;}},
chartContainer: {get: function(){return chartContainer;}, set: function(_){chartContainer=_;}},
enabled: {get: function(){return enabled;}, set: function(_){enabled=_;}},
hideDelay: {get: function(){return hideDelay;}, set: function(_){hideDelay=_;}},
contentGenerator: {get: function(){return contentGenerator;}, set: function(_){contentGenerator=_;}},
valueFormatter: {get: function(){return valueFormatter;}, set: function(_){valueFormatter=_;}},
headerFormatter: {get: function(){return headerFormatter;}, set: function(_){headerFormatter=_;}},
keyFormatter: {get: function(){return keyFormatter;}, set: function(_){keyFormatter=_;}},
headerEnabled: {get: function(){return headerEnabled;}, set: function(_){headerEnabled=_;}},
position: {get: function(){return position;}, set: function(_){position=_;}},
// Deprecated options
fixedTop: {get: function(){return null;}, set: function(_){
// deprecated after 1.8.1
nv.deprecated('fixedTop', 'feature removed after 1.8.1');
}},
offset: {get: function(){return {left: 0, top: 0};}, set: function(_){
// deprecated after 1.8.1
nv.deprecated('offset', 'use chart.tooltip.distance() instead');
}},
// options with extra logic
hidden: {get: function(){return hidden;}, set: function(_){
if (hidden != _) {
hidden = !!_;
nvtooltip();
}
}},
data: {get: function(){return data;}, set: function(_){
// if showing a single data point, adjust data format with that
if (_.point) {
_.value = _.point.x;
_.series = _.series || {};
_.series.value = _.point.y;
_.series.color = _.point.color || _.series.color;
}
data = _;
}},
// read only properties
node: {get: function(){return tooltip.node();}, set: function(_){}},
id: {get: function(){return id;}, set: function(_){}}
});
nv.utils.initOptions(nvtooltip);
return nvtooltip;
};
/*
Gets the browser window size
Returns object with height and width properties
*/
nv.utils.windowSize = function() {
// Sane defaults
var size = {width: 640, height: 480};
// Most recent browsers use
if (window.innerWidth && window.innerHeight) {
size.width = window.innerWidth;
size.height = window.innerHeight;
return (size);
}
// IE can use depending on mode it is in
if (document.compatMode=='CSS1Compat' &&
document.documentElement &&
document.documentElement.offsetWidth ) {
size.width = document.documentElement.offsetWidth;
size.height = document.documentElement.offsetHeight;
return (size);
}
// Earlier IE uses Doc.body
if (document.body && document.body.offsetWidth) {
size.width = document.body.offsetWidth;
size.height = document.body.offsetHeight;
return (size);
}
return (size);
};
/* handle dumb browser quirks... isinstance breaks if you use frames
typeof returns 'object' for null, NaN is a number, etc.
*/
nv.utils.isArray = Array.isArray;
nv.utils.isObject = function(a) {
return a !== null && typeof a === 'object';
};
nv.utils.isFunction = function(a) {
return typeof a === 'function';
};
nv.utils.isDate = function(a) {
return toString.call(a) === '[object Date]';
};
nv.utils.isNumber = function(a) {
return !isNaN(a) && typeof a === 'number';
};
/*
Binds callback function to run when window is resized
*/
nv.utils.windowResize = function(handler) {
if (window.addEventListener) {
window.addEventListener('resize', handler);
} else {
nv.log("ERROR: Failed to bind to window.resize with: ", handler);
}
// return object with clear function to remove the single added callback.
return {
callback: handler,
clear: function() {
window.removeEventListener('resize', handler);
}
}
};
/*
Backwards compatible way to implement more d3-like coloring of graphs.
Can take in nothing, an array, or a function/scale
To use a normal scale, get the range and pass that because we must be able
to take two arguments and use the index to keep backward compatibility
*/
nv.utils.getColor = function(color) {
//if you pass in nothing, get default colors back
if (color === undefined) {
return nv.utils.defaultColor();
//if passed an array, turn it into a color scale
} else if(nv.utils.isArray(color)) {
var color_scale = d3.scale.ordinal().range(color);
return function(d, i) {
var key = i === undefined ? d : i;
return d.color || color_scale(key);
};
//if passed a function or scale, return it, or whatever it may be
//external libs, such as angularjs-nvd3-directives use this
} else {
//can't really help it if someone passes rubbish as color
return color;
}
};
/*
Default color chooser uses a color scale of 20 colors from D3
https://github.com/mbostock/d3/wiki/Ordinal-Scales#categorical-colors
*/
nv.utils.defaultColor = function() {
// get range of the scale so we'll turn it into our own function.
return nv.utils.getColor(d3.scale.category20().range());
};
/*
Returns a color function that takes the result of 'getKey' for each series and
looks for a corresponding color from the dictionary
*/
nv.utils.customTheme = function(dictionary, getKey, defaultColors) {
// use default series.key if getKey is undefined
getKey = getKey || function(series) { return series.key };
defaultColors = defaultColors || d3.scale.category20().range();
// start at end of default color list and walk back to index 0
var defIndex = defaultColors.length;
return function(series, index) {
var key = getKey(series);
if (nv.utils.isFunction(dictionary[key])) {
return dictionary[key]();
} else if (dictionary[key] !== undefined) {
return dictionary[key];
} else {
// no match in dictionary, use a default color
if (!defIndex) {
// used all the default colors, start over
defIndex = defaultColors.length;
}
defIndex = defIndex - 1;
return defaultColors[defIndex];
}
};
};
/*
From the PJAX example on d3js.org, while this is not really directly needed
it's a very cool method for doing pjax, I may expand upon it a little bit,
open to suggestions on anything that may be useful
*/
nv.utils.pjax = function(links, content) {
var load = function(href) {
d3.html(href, function(fragment) {
var target = d3.select(content).node();
target.parentNode.replaceChild(
d3.select(fragment).select(content).node(),
target);
nv.utils.pjax(links, content);
});
};
d3.selectAll(links).on("click", function() {
history.pushState(this.href, this.textContent, this.href);
load(this.href);
d3.event.preventDefault();
});
d3.select(window).on("popstate", function() {
if (d3.event.state) {
load(d3.event.state);
}
});
};
/*
For when we want to approximate the width in pixels for an SVG:text element.
Most common instance is when the element is in a display:none; container.
Forumla is : text.length * font-size * constant_factor
*/
nv.utils.calcApproxTextWidth = function (svgTextElem) {
if (nv.utils.isFunction(svgTextElem.style) && nv.utils.isFunction(svgTextElem.text)) {
var fontSize = parseInt(svgTextElem.style("font-size").replace("px",""), 10);
var textLength = svgTextElem.text().length;
return nv.utils.NaNtoZero(textLength * fontSize * 0.5);
}
return 0;
};
/*
Numbers that are undefined, null or NaN, convert them to zeros.
*/
nv.utils.NaNtoZero = function(n) {
if (!nv.utils.isNumber(n)
|| isNaN(n)
|| n === null
|| n === Infinity
|| n === -Infinity) {
return 0;
}
return n;
};
/*
Add a way to watch for d3 transition ends to d3
*/
d3.selection.prototype.watchTransition = function(renderWatch){
var args = [this].concat([].slice.call(arguments, 1));
return renderWatch.transition.apply(renderWatch, args);
};
/*
Helper object to watch when d3 has rendered something
*/
nv.utils.renderWatch = function(dispatch, duration) {
if (!(this instanceof nv.utils.renderWatch)) {
return new nv.utils.renderWatch(dispatch, duration);
}
var _duration = duration !== undefined ? duration : 250;
var renderStack = [];
var self = this;
this.models = function(models) {
models = [].slice.call(arguments, 0);
models.forEach(function(model){
model.__rendered = false;
(function(m){
m.dispatch.on('renderEnd', function(arg){
m.__rendered = true;
self.renderEnd('model');
});
})(model);
if (renderStack.indexOf(model) < 0) {
renderStack.push(model);
}
});
return this;
};
this.reset = function(duration) {
if (duration !== undefined) {
_duration = duration;
}
renderStack = [];
};
this.transition = function(selection, args, duration) {
args = arguments.length > 1 ? [].slice.call(arguments, 1) : [];
if (args.length > 1) {
duration = args.pop();
} else {
duration = _duration !== undefined ? _duration : 250;
}
selection.__rendered = false;
if (renderStack.indexOf(selection) < 0) {
renderStack.push(selection);
}
if (duration === 0) {
selection.__rendered = true;
selection.delay = function() { return this; };
selection.duration = function() { return this; };
return selection;
} else {
if (selection.length === 0) {
selection.__rendered = true;
} else if (selection.every( function(d){ return !d.length; } )) {
selection.__rendered = true;
} else {
selection.__rendered = false;
}
var n = 0;
return selection
.transition()
.duration(duration)
.each(function(){ ++n; })
.each('end', function(d, i) {
if (--n === 0) {
selection.__rendered = true;
self.renderEnd.apply(this, args);
}
});
}
};
this.renderEnd = function() {
if (renderStack.every( function(d){ return d.__rendered; } )) {
renderStack.forEach( function(d){ d.__rendered = false; });
dispatch.renderEnd.apply(this, arguments);
}
}
};
/*
Takes multiple objects and combines them into the first one (dst)
example: nv.utils.deepExtend({a: 1}, {a: 2, b: 3}, {c: 4});
gives: {a: 2, b: 3, c: 4}
*/
nv.utils.deepExtend = function(dst){
var sources = arguments.length > 1 ? [].slice.call(arguments, 1) : [];
sources.forEach(function(source) {
for (var key in source) {
var isArray = nv.utils.isArray(dst[key]);
var isObject = nv.utils.isObject(dst[key]);
var srcObj = nv.utils.isObject(source[key]);
if (isObject && !isArray && srcObj) {
nv.utils.deepExtend(dst[key], source[key]);
} else {
dst[key] = source[key];
}
}
});
};
/*
state utility object, used to track d3 states in the models
*/
nv.utils.state = function(){
if (!(this instanceof nv.utils.state)) {
return new nv.utils.state();
}
var state = {};
var _self = this;
var _setState = function(){};
var _getState = function(){ return {}; };
var init = null;
var changed = null;
this.dispatch = d3.dispatch('change', 'set');
this.dispatch.on('set', function(state){
_setState(state, true);
});
this.getter = function(fn){
_getState = fn;
return this;
};
this.setter = function(fn, callback) {
if (!callback) {
callback = function(){};
}
_setState = function(state, update){
fn(state);
if (update) {
callback();
}
};
return this;
};
this.init = function(state){
init = init || {};
nv.utils.deepExtend(init, state);
};
var _set = function(){
var settings = _getState();
if (JSON.stringify(settings) === JSON.stringify(state)) {
return false;
}
for (var key in settings) {
if (state[key] === undefined) {
state[key] = {};
}
state[key] = settings[key];
changed = true;
}
return true;
};
this.update = function(){
if (init) {
_setState(init, false);
init = null;
}
if (_set.call(this)) {
this.dispatch.change(state);
}
};
};
/*
Snippet of code you can insert into each nv.models.* to give you the ability to
do things like:
chart.options({
showXAxis: true,
tooltips: true
});
To enable in the chart:
chart.options = nv.utils.optionsFunc.bind(chart);
*/
nv.utils.optionsFunc = function(args) {
if (args) {
d3.map(args).forEach((function(key,value) {
if (nv.utils.isFunction(this[key])) {
this[key](value);
}
}).bind(this));
}
return this;
};
/*
numTicks: requested number of ticks
data: the chart data
returns the number of ticks to actually use on X axis, based on chart data
to avoid duplicate ticks with the same value
*/
nv.utils.calcTicksX = function(numTicks, data) {
// find max number of values from all data streams
var numValues = 1;
var i = 0;
for (i; i < data.length; i += 1) {
var stream_len = data[i] && data[i].values ? data[i].values.length : 0;
numValues = stream_len > numValues ? stream_len : numValues;
}
nv.log("Requested number of ticks: ", numTicks);
nv.log("Calculated max values to be: ", numValues);
// make sure we don't have more ticks than values to avoid duplicates
numTicks = numTicks > numValues ? numTicks = numValues - 1 : numTicks;
// make sure we have at least one tick
numTicks = numTicks < 1 ? 1 : numTicks;
// make sure it's an integer
numTicks = Math.floor(numTicks);
nv.log("Calculating tick count as: ", numTicks);
return numTicks;
};
/*
returns number of ticks to actually use on Y axis, based on chart data
*/
nv.utils.calcTicksY = function(numTicks, data) {
// currently uses the same logic but we can adjust here if needed later
return nv.utils.calcTicksX(numTicks, data);
};
/*
Add a particular option from an options object onto chart
Options exposed on a chart are a getter/setter function that returns chart
on set to mimic typical d3 option chaining, e.g. svg.option1('a').option2('b');
option objects should be generated via Object.create() to provide
the option of manipulating data via get/set functions.
*/
nv.utils.initOption = function(chart, name) {
// if it's a call option, just call it directly, otherwise do get/set
if (chart._calls && chart._calls[name]) {
chart[name] = chart._calls[name];
} else {
chart[name] = function (_) {
if (!arguments.length) return chart._options[name];
chart._overrides[name] = true;
chart._options[name] = _;
return chart;
};
// calling the option as _option will ignore if set by option already
// so nvd3 can set options internally but the stop if set manually
chart['_' + name] = function(_) {
if (!arguments.length) return chart._options[name];
if (!chart._overrides[name]) {
chart._options[name] = _;
}
return chart;
}
}
};
/*
Add all options in an options object to the chart
*/
nv.utils.initOptions = function(chart) {
chart._overrides = chart._overrides || {};
var ops = Object.getOwnPropertyNames(chart._options || {});
var calls = Object.getOwnPropertyNames(chart._calls || {});
ops = ops.concat(calls);
for (var i in ops) {
nv.utils.initOption(chart, ops[i]);
}
};
/*
Inherit options from a D3 object
d3.rebind makes calling the function on target actually call it on source
Also use _d3options so we can track what we inherit for documentation and chained inheritance
*/
nv.utils.inheritOptionsD3 = function(target, d3_source, oplist) {
target._d3options = oplist.concat(target._d3options || []);
oplist.unshift(d3_source);
oplist.unshift(target);
d3.rebind.apply(this, oplist);
};
/*
Remove duplicates from an array
*/
nv.utils.arrayUnique = function(a) {
return a.sort().filter(function(item, pos) {
return !pos || item != a[pos - 1];
});
};
/*
Keeps a list of custom symbols to draw from in addition to d3.svg.symbol
Necessary since d3 doesn't let you extend its list -_-
Add new symbols by doing nv.utils.symbols.set('name', function(size){...});
*/
nv.utils.symbolMap = d3.map();
/*
Replaces d3.svg.symbol so that we can look both there and our own map
*/
nv.utils.symbol = function() {
var type,
size = 64;
function symbol(d,i) {
var t = type.call(this,d,i);
var s = size.call(this,d,i);
if (d3.svg.symbolTypes.indexOf(t) !== -1) {
return d3.svg.symbol().type(t).size(s)();
} else {
return nv.utils.symbolMap.get(t)(s);
}
}
symbol.type = function(_) {
if (!arguments.length) return type;
type = d3.functor(_);
return symbol;
};
symbol.size = function(_) {
if (!arguments.length) return size;
size = d3.functor(_);
return symbol;
};
return symbol;
};
/*
Inherit option getter/setter functions from source to target
d3.rebind makes calling the function on target actually call it on source
Also track via _inherited and _d3options so we can track what we inherit
for documentation generation purposes and chained inheritance
*/
nv.utils.inheritOptions = function(target, source) {
// inherit all the things
var ops = Object.getOwnPropertyNames(source._options || {});
var calls = Object.getOwnPropertyNames(source._calls || {});
var inherited = source._inherited || [];
var d3ops = source._d3options || [];
var args = ops.concat(calls).concat(inherited).concat(d3ops);
args.unshift(source);
args.unshift(target);
d3.rebind.apply(this, args);
// pass along the lists to keep track of them, don't allow duplicates
target._inherited = nv.utils.arrayUnique(ops.concat(calls).concat(inherited).concat(ops).concat(target._inherited || []));
target._d3options = nv.utils.arrayUnique(d3ops.concat(target._d3options || []));
};
/*
Runs common initialize code on the svg before the chart builds
*/
nv.utils.initSVG = function(svg) {
svg.classed({'nvd3-svg':true});
};
/*
Sanitize and provide default for the container height.
*/
nv.utils.sanitizeHeight = function(height, container) {
return (height || parseInt(container.style('height'), 10) || 400);
};
/*
Sanitize and provide default for the container width.
*/
nv.utils.sanitizeWidth = function(width, container) {
return (width || parseInt(container.style('width'), 10) || 960);
};
/*
Calculate the available height for a chart.
*/
nv.utils.availableHeight = function(height, container, margin) {
return Math.max(0,nv.utils.sanitizeHeight(height, container) - margin.top - margin.bottom);
};
/*
Calculate the available width for a chart.
*/
nv.utils.availableWidth = function(width, container, margin) {
return Math.max(0,nv.utils.sanitizeWidth(width, container) - margin.left - margin.right);
};
/*
Clear any rendered chart components and display a chart's 'noData' message
*/
nv.utils.noData = function(chart, container) {
var opt = chart.options(),
margin = opt.margin(),
noData = opt.noData(),
data = (noData == null) ? ["No Data Available."] : [noData],
height = nv.utils.availableHeight(null, container, margin),
width = nv.utils.availableWidth(null, container, margin),
x = margin.left + width/2,
y = margin.top + height/2;
//Remove any previously created chart components
container.selectAll('g').remove();
var noDataText = container.selectAll('.nv-noData').data(data);
noDataText.enter().append('text')
.attr('class', 'nvd3 nv-noData')
.attr('dy', '-.7em')
.style('text-anchor', 'middle');
noDataText
.attr('x', x)
.attr('y', y)
.text(function(t){ return t; });
};
/*
Wrap long labels.
*/
nv.utils.wrapTicks = function (text, width) {
text.each(function() {
var text = d3.select(this),
words = text.text().split(/\s+/).reverse(),
word,
line = [],
lineNumber = 0,
lineHeight = 1.1,
y = text.attr("y"),
dy = parseFloat(text.attr("dy")),
tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
while (word = words.pop()) {
line.push(word);
tspan.text(line.join(" "));
if (tspan.node().getComputedTextLength() > width) {
line.pop();
tspan.text(line.join(" "));
line = [word];
tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
}
}
});
};
/*
Check equality of 2 array
*/
nv.utils.arrayEquals = function (array1, array2) {
if (array1 === array2)
return true;
if (!array1 || !array2)
return false;
// compare lengths - can save a lot of time
if (array1.length != array2.length)
return false;
for (var i = 0,
l = array1.length; i < l; i++) {
// Check if we have nested arrays
if (array1[i] instanceof Array && array2[i] instanceof Array) {
// recurse into the nested arrays
if (!nv.arrayEquals(array1[i], array2[i]))
return false;
} else if (array1[i] != array2[i]) {
// Warning - two different object instances will never be equal: {x:20} != {x:20}
return false;
}
}
return true;
};nv.models.axis = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var axis = d3.svg.axis();
var scale = d3.scale.linear();
var margin = {top: 0, right: 0, bottom: 0, left: 0}
, width = 75 //only used for tickLabel currently
, height = 60 //only used for tickLabel currently
, axisLabelText = null
, showMaxMin = true //TODO: showMaxMin should be disabled on all ordinal scaled axes
, rotateLabels = 0
, rotateYLabel = true
, staggerLabels = false
, isOrdinal = false
, ticks = null
, axisLabelDistance = 0
, fontSize = undefined
, duration = 250
, dispatch = d3.dispatch('renderEnd')
;
axis
.scale(scale)
.orient('bottom')
.tickFormat(function(d) { return d })
;
//============================================================
// Private Variables
//------------------------------------------------------------
var scale0;
var renderWatch = nv.utils.renderWatch(dispatch, duration);
function chart(selection) {
renderWatch.reset();
selection.each(function(data) {
var container = d3.select(this);
nv.utils.initSVG(container);
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-axis').data([data]);
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-axis');
var gEnter = wrapEnter.append('g');
var g = wrap.select('g');
if (ticks !== null)
axis.ticks(ticks);
else if (axis.orient() == 'top' || axis.orient() == 'bottom')
axis.ticks(Math.abs(scale.range()[1] - scale.range()[0]) / 100);
//TODO: consider calculating width/height based on whether or not label is added, for reference in charts using this component
g.watchTransition(renderWatch, 'axis').call(axis);
scale0 = scale0 || axis.scale();
var fmt = axis.tickFormat();
if (fmt == null) {
fmt = scale0.tickFormat();
}
var axisLabel = g.selectAll('text.nv-axislabel')
.data([axisLabelText || null]);
axisLabel.exit().remove();
//only skip when fontSize is undefined so it can be cleared with a null or blank string
if (fontSize !== undefined) {
g.selectAll('g').select("text").style('font-size', fontSize);
}
var xLabelMargin;
var axisMaxMin;
var w;
switch (axis.orient()) {
case 'top':
axisLabel.enter().append('text').attr('class', 'nv-axislabel');
w = 0;
if (scale.range().length === 1) {
w = isOrdinal ? scale.range()[0] * 2 + scale.rangeBand() : 0;
} else if (scale.range().length === 2) {
w = isOrdinal ? scale.range()[0] + scale.range()[1] + scale.rangeBand() : scale.range()[1];
} else if ( scale.range().length > 2){
w = scale.range()[scale.range().length-1]+(scale.range()[1]-scale.range()[0]);
};
axisLabel
.attr('text-anchor', 'middle')
.attr('y', 0)
.attr('x', w/2);
if (showMaxMin) {
axisMaxMin = wrap.selectAll('g.nv-axisMaxMin')
.data(scale.domain());
axisMaxMin.enter().append('g').attr('class',function(d,i){
return ['nv-axisMaxMin','nv-axisMaxMin-x',(i == 0 ? 'nv-axisMin-x':'nv-axisMax-x')].join(' ')
}).append('text');
axisMaxMin.exit().remove();
axisMaxMin
.attr('transform', function(d,i) {
return 'translate(' + nv.utils.NaNtoZero(scale(d)) + ',0)'
})
.select('text')
.attr('dy', '-0.5em')
.attr('y', -axis.tickPadding())
.attr('text-anchor', 'middle')
.text(function(d,i) {
var v = fmt(d);
return ('' + v).match('NaN') ? '' : v;
});
axisMaxMin.watchTransition(renderWatch, 'min-max top')
.attr('transform', function(d,i) {
return 'translate(' + nv.utils.NaNtoZero(scale.range()[i]) + ',0)'
});
}
break;
case 'bottom':
xLabelMargin = axisLabelDistance + 36;
var maxTextWidth = 30;
var textHeight = 0;
var xTicks = g.selectAll('g').select("text");
var rotateLabelsRule = '';
if (rotateLabels%360) {
//Reset transform on ticks so textHeight can be calculated correctly
xTicks.attr('transform', '');
//Calculate the longest xTick width
xTicks.each(function(d,i){
var box = this.getBoundingClientRect();
var width = box.width;
textHeight = box.height;
if(width > maxTextWidth) maxTextWidth = width;
});
rotateLabelsRule = 'rotate(' + rotateLabels + ' 0,' + (textHeight/2 + axis.tickPadding()) + ')';
//Convert to radians before calculating sin. Add 30 to margin for healthy padding.
var sin = Math.abs(Math.sin(rotateLabels*Math.PI/180));
xLabelMargin = (sin ? sin*maxTextWidth : maxTextWidth)+30;
//Rotate all xTicks
xTicks
.attr('transform', rotateLabelsRule)
.style('text-anchor', rotateLabels%360 > 0 ? 'start' : 'end');
} else {
if (staggerLabels) {
xTicks
.attr('transform', function(d,i) {
return 'translate(0,' + (i % 2 == 0 ? '0' : '12') + ')'
});
} else {
xTicks.attr('transform', "translate(0,0)");
}
}
axisLabel.enter().append('text').attr('class', 'nv-axislabel');
w = 0;
if (scale.range().length === 1) {
w = isOrdinal ? scale.range()[0] * 2 + scale.rangeBand() : 0;
} else if (scale.range().length === 2) {
w = isOrdinal ? scale.range()[0] + scale.range()[1] + scale.rangeBand() : scale.range()[1];
} else if ( scale.range().length > 2){
w = scale.range()[scale.range().length-1]+(scale.range()[1]-scale.range()[0]);
};
axisLabel
.attr('text-anchor', 'middle')
.attr('y', xLabelMargin)
.attr('x', w/2);
if (showMaxMin) {
//if (showMaxMin && !isOrdinal) {
axisMaxMin = wrap.selectAll('g.nv-axisMaxMin')
//.data(scale.domain())
.data([scale.domain()[0], scale.domain()[scale.domain().length - 1]]);
axisMaxMin.enter().append('g').attr('class',function(d,i){
return ['nv-axisMaxMin','nv-axisMaxMin-x',(i == 0 ? 'nv-axisMin-x':'nv-axisMax-x')].join(' ')
}).append('text');
axisMaxMin.exit().remove();
axisMaxMin
.attr('transform', function(d,i) {
return 'translate(' + nv.utils.NaNtoZero((scale(d) + (isOrdinal ? scale.rangeBand() / 2 : 0))) + ',0)'
})
.select('text')
.attr('dy', '.71em')
.attr('y', axis.tickPadding())
.attr('transform', rotateLabelsRule)
.style('text-anchor', rotateLabels ? (rotateLabels%360 > 0 ? 'start' : 'end') : 'middle')
.text(function(d,i) {
var v = fmt(d);
return ('' + v).match('NaN') ? '' : v;
});
axisMaxMin.watchTransition(renderWatch, 'min-max bottom')
.attr('transform', function(d,i) {
return 'translate(' + nv.utils.NaNtoZero((scale(d) + (isOrdinal ? scale.rangeBand() / 2 : 0))) + ',0)'
});
}
break;
case 'right':
axisLabel.enter().append('text').attr('class', 'nv-axislabel');
axisLabel
.style('text-anchor', rotateYLabel ? 'middle' : 'begin')
.attr('transform', rotateYLabel ? 'rotate(90)' : '')
.attr('y', rotateYLabel ? (-Math.max(margin.right, width) + 12 - (axisLabelDistance || 0)) : -10) //TODO: consider calculating this based on largest tick width... OR at least expose this on chart
.attr('x', rotateYLabel ? (d3.max(scale.range()) / 2) : axis.tickPadding());
if (showMaxMin) {
axisMaxMin = wrap.selectAll('g.nv-axisMaxMin')
.data(scale.domain());
axisMaxMin.enter().append('g').attr('class',function(d,i){
return ['nv-axisMaxMin','nv-axisMaxMin-y',(i == 0 ? 'nv-axisMin-y':'nv-axisMax-y')].join(' ')
}).append('text')
.style('opacity', 0);
axisMaxMin.exit().remove();
axisMaxMin
.attr('transform', function(d,i) {
return 'translate(0,' + nv.utils.NaNtoZero(scale(d)) + ')'
})
.select('text')
.attr('dy', '.32em')
.attr('y', 0)
.attr('x', axis.tickPadding())
.style('text-anchor', 'start')
.text(function(d, i) {
var v = fmt(d);
return ('' + v).match('NaN') ? '' : v;
});
axisMaxMin.watchTransition(renderWatch, 'min-max right')
.attr('transform', function(d,i) {
return 'translate(0,' + nv.utils.NaNtoZero(scale.range()[i]) + ')'
})
.select('text')
.style('opacity', 1);
}
break;
case 'left':
/*
//For dynamically placing the label. Can be used with dynamically-sized chart axis margins
var yTicks = g.selectAll('g').select("text");
yTicks.each(function(d,i){
var labelPadding = this.getBoundingClientRect().width + axis.tickPadding() + 16;
if(labelPadding > width) width = labelPadding;
});
*/
axisLabel.enter().append('text').attr('class', 'nv-axislabel');
axisLabel
.style('text-anchor', rotateYLabel ? 'middle' : 'end')
.attr('transform', rotateYLabel ? 'rotate(-90)' : '')
.attr('y', rotateYLabel ? (-Math.max(margin.left, width) + 25 - (axisLabelDistance || 0)) : -10)
.attr('x', rotateYLabel ? (-d3.max(scale.range()) / 2) : -axis.tickPadding());
if (showMaxMin) {
axisMaxMin = wrap.selectAll('g.nv-axisMaxMin')
.data(scale.domain());
axisMaxMin.enter().append('g').attr('class',function(d,i){
return ['nv-axisMaxMin','nv-axisMaxMin-y',(i == 0 ? 'nv-axisMin-y':'nv-axisMax-y')].join(' ')
}).append('text')
.style('opacity', 0);
axisMaxMin.exit().remove();
axisMaxMin
.attr('transform', function(d,i) {
return 'translate(0,' + nv.utils.NaNtoZero(scale0(d)) + ')'
})
.select('text')
.attr('dy', '.32em')
.attr('y', 0)
.attr('x', -axis.tickPadding())
.attr('text-anchor', 'end')
.text(function(d,i) {
var v = fmt(d);
return ('' + v).match('NaN') ? '' : v;
});
axisMaxMin.watchTransition(renderWatch, 'min-max right')
.attr('transform', function(d,i) {
return 'translate(0,' + nv.utils.NaNtoZero(scale.range()[i]) + ')'
})
.select('text')
.style('opacity', 1);
}
break;
}
axisLabel.text(function(d) { return d });
if (showMaxMin && (axis.orient() === 'left' || axis.orient() === 'right')) {
//check if max and min overlap other values, if so, hide the values that overlap
g.selectAll('g') // the g's wrapping each tick
.each(function(d,i) {
d3.select(this).select('text').attr('opacity', 1);
if (scale(d) < scale.range()[1] + 10 || scale(d) > scale.range()[0] - 10) { // 10 is assuming text height is 16... if d is 0, leave it!
if (d > 1e-10 || d < -1e-10) // accounts for minor floating point errors... though could be problematic if the scale is EXTREMELY SMALL
d3.select(this).attr('opacity', 0);
d3.select(this).select('text').attr('opacity', 0); // Don't remove the ZERO line!!
}
});
//if Max and Min = 0 only show min, Issue #281
if (scale.domain()[0] == scale.domain()[1] && scale.domain()[0] == 0) {
wrap.selectAll('g.nv-axisMaxMin').style('opacity', function (d, i) {
return !i ? 1 : 0
});
}
}
if (showMaxMin && (axis.orient() === 'top' || axis.orient() === 'bottom')) {
var maxMinRange = [];
wrap.selectAll('g.nv-axisMaxMin')
.each(function(d,i) {
try {
if (i) // i== 1, max position
maxMinRange.push(scale(d) - this.getBoundingClientRect().width - 4); //assuming the max and min labels are as wide as the next tick (with an extra 4 pixels just in case)
else // i==0, min position
maxMinRange.push(scale(d) + this.getBoundingClientRect().width + 4)
}catch (err) {
if (i) // i== 1, max position
maxMinRange.push(scale(d) - 4); //assuming the max and min labels are as wide as the next tick (with an extra 4 pixels just in case)
else // i==0, min position
maxMinRange.push(scale(d) + 4);
}
});
// the g's wrapping each tick
g.selectAll('g').each(function(d, i) {
if (scale(d) < maxMinRange[0] || scale(d) > maxMinRange[1]) {
if (d > 1e-10 || d < -1e-10) // accounts for minor floating point errors... though could be problematic if the scale is EXTREMELY SMALL
d3.select(this).remove();
else
d3.select(this).select('text').remove(); // Don't remove the ZERO line!!
}
});
}
//Highlight zero tick line
g.selectAll('.tick')
.filter(function (d) {
/*
The filter needs to return only ticks at or near zero.
Numbers like 0.00001 need to count as zero as well,
and the arithmetic trick below solves that.
*/
return !parseFloat(Math.round(d * 100000) / 1000000) && (d !== undefined)
})
.classed('zero', true);
//store old scales for use in transitions on update
scale0 = scale.copy();
});
renderWatch.renderEnd('axis immediate');
return chart;
}
//============================================================
// Expose Public Variables
//------------------------------------------------------------
// expose chart's sub-components
chart.axis = axis;
chart.dispatch = dispatch;
chart.options = nv.utils.optionsFunc.bind(chart);
chart._options = Object.create({}, {
// simple options, just get/set the necessary values
axisLabelDistance: {get: function(){return axisLabelDistance;}, set: function(_){axisLabelDistance=_;}},
staggerLabels: {get: function(){return staggerLabels;}, set: function(_){staggerLabels=_;}},
rotateLabels: {get: function(){return rotateLabels;}, set: function(_){rotateLabels=_;}},
rotateYLabel: {get: function(){return rotateYLabel;}, set: function(_){rotateYLabel=_;}},
showMaxMin: {get: function(){return showMaxMin;}, set: function(_){showMaxMin=_;}},
axisLabel: {get: function(){return axisLabelText;}, set: function(_){axisLabelText=_;}},
height: {get: function(){return height;}, set: function(_){height=_;}},
ticks: {get: function(){return ticks;}, set: function(_){ticks=_;}},
width: {get: function(){return width;}, set: function(_){width=_;}},
fontSize: {get: function(){return fontSize;}, set: function(_){fontSize=_;}},
// options that require extra logic in the setter
margin: {get: function(){return margin;}, set: function(_){
margin.top = _.top !== undefined ? _.top : margin.top;
margin.right = _.right !== undefined ? _.right : margin.right;
margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
margin.left = _.left !== undefined ? _.left : margin.left;
}},
duration: {get: function(){return duration;}, set: function(_){
duration=_;
renderWatch.reset(duration);
}},
scale: {get: function(){return scale;}, set: function(_){
scale = _;
axis.scale(scale);
isOrdinal = typeof scale.rangeBands === 'function';
nv.utils.inheritOptionsD3(chart, scale, ['domain', 'range', 'rangeBand', 'rangeBands']);
}}
});
nv.utils.initOptions(chart);
nv.utils.inheritOptionsD3(chart, axis, ['orient', 'tickValues', 'tickSubdivide', 'tickSize', 'tickPadding', 'tickFormat']);
nv.utils.inheritOptionsD3(chart, scale, ['domain', 'range', 'rangeBand', 'rangeBands']);
return chart;
};
nv.models.boxPlot = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var margin = {top: 0, right: 0, bottom: 0, left: 0},
width = 960,
height = 500,
id = Math.floor(Math.random() * 10000), // Create semi-unique ID in case user doesn't select one
xScale = d3.scale.ordinal(),
yScale = d3.scale.linear(),
getX = function(d) { return d.label }, // Default data model selectors.
getQ1 = function(d) { return d.values.Q1 },
getQ2 = function(d) { return d.values.Q2 },
getQ3 = function(d) { return d.values.Q3 },
getWl = function(d) { return d.values.whisker_low },
getWh = function(d) { return d.values.whisker_high },
getColor = function(d) { return d.color },
getOlItems = function(d) { return d.values.outliers },
getOlValue = function(d, i, j) { return d },
getOlLabel = function(d, i, j) { return d },
getOlColor = function(d, i, j) { return undefined },
color = nv.utils.defaultColor(),
container = null,
xDomain, xRange,
yDomain, yRange,
dispatch = d3.dispatch('elementMouseover', 'elementMouseout', 'elementMousemove', 'renderEnd'),
duration = 250,
maxBoxWidth = null;
//============================================================
// Private Variables
//------------------------------------------------------------
var xScale0, yScale0;
var renderWatch = nv.utils.renderWatch(dispatch, duration);
function chart(selection) {
renderWatch.reset();
selection.each(function(data) {
var availableWidth = width - margin.left - margin.right,
availableHeight = height - margin.top - margin.bottom;
container = d3.select(this);
nv.utils.initSVG(container);
// Setup Scales
xScale.domain(xDomain || data.map(function(d,i) { return getX(d,i); }))
.rangeBands(xRange || [0, availableWidth], 0.1);
// if we know yDomain, no need to calculate
var yData = []
if (!yDomain) {
// (y-range is based on quartiles, whiskers and outliers)
var values = [], yMin, yMax;
data.forEach(function (d, i) {
var q1 = getQ1(d), q3 = getQ3(d), wl = getWl(d), wh = getWh(d);
var olItems = getOlItems(d);
if (olItems) {
olItems.forEach(function (e, i) {
values.push(getOlValue(e, i, undefined));
});
}
if (wl) { values.push(wl) }
if (q1) { values.push(q1) }
if (q3) { values.push(q3) }
if (wh) { values.push(wh) }
});
yMin = d3.min(values);
yMax = d3.max(values);
yData = [ yMin, yMax ] ;
}
yScale.domain(yDomain || yData);
yScale.range(yRange || [availableHeight, 0]);
//store old scales if they exist
xScale0 = xScale0 || xScale;
yScale0 = yScale0 || yScale.copy().range([yScale(0),yScale(0)]);
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap').data([data]);
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap');
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
var boxplots = wrap.selectAll('.nv-boxplot').data(function(d) { return d });
var boxEnter = boxplots.enter().append('g').style('stroke-opacity', 1e-6).style('fill-opacity', 1e-6);
boxplots
.attr('class', 'nv-boxplot')
.attr('transform', function(d,i,j) { return 'translate(' + (xScale(getX(d,i)) + xScale.rangeBand() * 0.05) + ', 0)'; })
.classed('hover', function(d) { return d.hover });
boxplots
.watchTransition(renderWatch, 'nv-boxplot: boxplots')
.style('stroke-opacity', 1)
.style('fill-opacity', 0.75)
.delay(function(d,i) { return i * duration / data.length })
.attr('transform', function(d,i) {
return 'translate(' + (xScale(getX(d,i)) + xScale.rangeBand() * 0.05) + ', 0)';
});
boxplots.exit().remove();
// ----- add the SVG elements for each boxPlot -----
// conditionally append whisker lines
boxEnter.each(function(d,i) {
var box = d3.select(this);
[getWl, getWh].forEach(function (f) {
if (f(d)) {
var key = (f === getWl) ? 'low' : 'high';
box.append('line')
.style('stroke', getColor(d) || color(d,i))
.attr('class', 'nv-boxplot-whisker nv-boxplot-' + key);
box.append('line')
.style('stroke', getColor(d) || color(d,i))
.attr('class', 'nv-boxplot-tick nv-boxplot-' + key);
}
});
});
var box_width = function() { return (maxBoxWidth === null ? xScale.rangeBand() * 0.9 : Math.min(75, xScale.rangeBand() * 0.9)); };
var box_left = function() { return xScale.rangeBand() * 0.45 - box_width()/2; };
var box_right = function() { return xScale.rangeBand() * 0.45 + box_width()/2; };
// update whisker lines and ticks
[getWl, getWh].forEach(function (f) {
var key = (f === getWl) ? 'low' : 'high';
var endpoint = (f === getWl) ? getQ1 : getQ3;
boxplots.select('line.nv-boxplot-whisker.nv-boxplot-' + key)
.watchTransition(renderWatch, 'nv-boxplot: boxplots')
.attr('x1', xScale.rangeBand() * 0.45 )
.attr('y1', function(d,i) { return yScale(f(d)); })
.attr('x2', xScale.rangeBand() * 0.45 )
.attr('y2', function(d,i) { return yScale(endpoint(d)); });
boxplots.select('line.nv-boxplot-tick.nv-boxplot-' + key)
.watchTransition(renderWatch, 'nv-boxplot: boxplots')
.attr('x1', box_left )
.attr('y1', function(d,i) { return yScale(f(d)); })
.attr('x2', box_right )
.attr('y2', function(d,i) { return yScale(f(d)); });
});
[getWl, getWh].forEach(function (f) {
var key = (f === getWl) ? 'low' : 'high';
boxEnter.selectAll('.nv-boxplot-' + key)
.on('mouseover', function(d,i,j) {
d3.select(this).classed('hover', true);
dispatch.elementMouseover({
series: { key: f(d), color: getColor(d) || color(d,j) },
e: d3.event
});
})
.on('mouseout', function(d,i,j) {
d3.select(this).classed('hover', false);
dispatch.elementMouseout({
series: { key: f(d), color: getColor(d) || color(d,j) },
e: d3.event
});
})
.on('mousemove', function(d,i) {
dispatch.elementMousemove({e: d3.event});
});
});
// boxes
boxEnter.append('rect')
.attr('class', 'nv-boxplot-box')
// tooltip events
.on('mouseover', function(d,i) {
d3.select(this).classed('hover', true);
dispatch.elementMouseover({
key: getX(d),
value: getX(d),
series: [
{ key: 'Q3', value: getQ3(d), color: getColor(d) || color(d,i) },
{ key: 'Q2', value: getQ2(d), color: getColor(d) || color(d,i) },
{ key: 'Q1', value: getQ1(d), color: getColor(d) || color(d,i) }
],
data: d,
index: i,
e: d3.event
});
})
.on('mouseout', function(d,i) {
d3.select(this).classed('hover', false);
dispatch.elementMouseout({
key: getX(d),
value: getX(d),
series: [
{ key: 'Q3', value: getQ3(d), color: getColor(d) || color(d,i) },
{ key: 'Q2', value: getQ2(d), color: getColor(d) || color(d,i) },
{ key: 'Q1', value: getQ1(d), color: getColor(d) || color(d,i) }
],
data: d,
index: i,
e: d3.event
});
})
.on('mousemove', function(d,i) {
dispatch.elementMousemove({e: d3.event});
});
// box transitions
boxplots.select('rect.nv-boxplot-box')
.watchTransition(renderWatch, 'nv-boxplot: boxes')
.attr('y', function(d,i) { return yScale(getQ3(d)); })
.attr('width', box_width)
.attr('x', box_left )
.attr('height', function(d,i) { return Math.abs(yScale(getQ3(d)) - yScale(getQ1(d))) || 1 })
.style('fill', function(d,i) { return getColor(d) || color(d,i) })
.style('stroke', function(d,i) { return getColor(d) || color(d,i) });
// median line
boxEnter.append('line').attr('class', 'nv-boxplot-median');
boxplots.select('line.nv-boxplot-median')
.watchTransition(renderWatch, 'nv-boxplot: boxplots line')
.attr('x1', box_left)
.attr('y1', function(d,i) { return yScale(getQ2(d)); })
.attr('x2', box_right)
.attr('y2', function(d,i) { return yScale(getQ2(d)); });
// outliers
var outliers = boxplots.selectAll('.nv-boxplot-outlier').data(function(d) {
return getOlItems(d) || [];
});
outliers.enter().append('circle')
.style('fill', function(d,i,j) { return getOlColor(d,i,j) || color(d,j) })
.style('stroke', function(d,i,j) { return getOlColor(d,i,j) || color(d,j) })
.style('z-index', 9000)
.on('mouseover', function(d,i,j) {
d3.select(this).classed('hover', true);
dispatch.elementMouseover({
series: { key: getOlLabel(d,i,j), color: getOlColor(d,i,j) || color(d,j) },
e: d3.event
});
})
.on('mouseout', function(d,i,j) {
d3.select(this).classed('hover', false);
dispatch.elementMouseout({
series: { key: getOlLabel(d,i,j), color: getOlColor(d,i,j) || color(d,j) },
e: d3.event
});
})
.on('mousemove', function(d,i) {
dispatch.elementMousemove({e: d3.event});
});
outliers.attr('class', 'nv-boxplot-outlier');
outliers
.watchTransition(renderWatch, 'nv-boxplot: nv-boxplot-outlier')
.attr('cx', xScale.rangeBand() * 0.45)
.attr('cy', function(d,i,j) { return yScale(getOlValue(d,i,j)); })
.attr('r', '3');
outliers.exit().remove();
//store old scales for use in transitions on update
xScale0 = xScale.copy();
yScale0 = yScale.copy();
});
renderWatch.renderEnd('nv-boxplot immediate');
return chart;
}
//============================================================
// Expose Public Variables
//------------------------------------------------------------
chart.dispatch = dispatch;
chart.options = nv.utils.optionsFunc.bind(chart);
chart._options = Object.create({}, {
// simple options, just get/set the necessary values
width: {get: function(){return width;}, set: function(_){width=_;}},
height: {get: function(){return height;}, set: function(_){height=_;}},
maxBoxWidth: {get: function(){return maxBoxWidth;}, set: function(_){maxBoxWidth=_;}},
x: {get: function(){return getX;}, set: function(_){getX=_;}},
q1: {get: function(){return getQ1;}, set: function(_){getQ1=_;}},
q2: {get: function(){return getQ2;}, set: function(_){getQ2=_;}},
q3: {get: function(){return getQ3;}, set: function(_){getQ3=_;}},
wl: {get: function(){return getWl;}, set: function(_){getWl=_;}},
wh: {get: function(){return getWh;}, set: function(_){getWh=_;}},
itemColor: {get: function(){return getColor;}, set: function(_){getColor=_;}},
outliers: {get: function(){return getOlItems;}, set: function(_){getOlItems=_;}},
outlierValue: {get: function(){return getOlValue;}, set: function(_){getOlValue=_;}},
outlierLabel: {get: function(){return getOlLabel;}, set: function(_){getOlLabel=_;}},
outlierColor: {get: function(){return getOlColor;}, set: function(_){getOlColor=_;}},
xScale: {get: function(){return xScale;}, set: function(_){xScale=_;}},
yScale: {get: function(){return yScale;}, set: function(_){yScale=_;}},
xDomain: {get: function(){return xDomain;}, set: function(_){xDomain=_;}},
yDomain: {get: function(){return yDomain;}, set: function(_){yDomain=_;}},
xRange: {get: function(){return xRange;}, set: function(_){xRange=_;}},
yRange: {get: function(){return yRange;}, set: function(_){yRange=_;}},
id: {get: function(){return id;}, set: function(_){id=_;}},
// rectClass: {get: function(){return rectClass;}, set: function(_){rectClass=_;}},
y: {
get: function() {
console.warn('BoxPlot \'y\' chart option is deprecated. Please use model overrides instead.');
return {};
},
set: function(_) {
console.warn('BoxPlot \'y\' chart option is deprecated. Please use model overrides instead.');
}
},
// options that require extra logic in the setter
margin: {get: function(){return margin;}, set: function(_){
margin.top = _.top !== undefined ? _.top : margin.top;
margin.right = _.right !== undefined ? _.right : margin.right;
margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
margin.left = _.left !== undefined ? _.left : margin.left;
}},
color: {get: function(){return color;}, set: function(_){
color = nv.utils.getColor(_);
}},
duration: {get: function(){return duration;}, set: function(_){
duration = _;
renderWatch.reset(duration);
}}
});
nv.utils.initOptions(chart);
return chart;
};
nv.models.boxPlotChart = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var boxplot = nv.models.boxPlot(),
xAxis = nv.models.axis(),
yAxis = nv.models.axis();
var margin = {top: 15, right: 10, bottom: 50, left: 60},
width = null,
height = null,
color = nv.utils.getColor(),
showXAxis = true,
showYAxis = true,
rightAlignYAxis = false,
staggerLabels = false,
tooltip = nv.models.tooltip(),
x, y,
noData = 'No Data Available.',
dispatch = d3.dispatch('beforeUpdate', 'renderEnd'),
duration = 250;
xAxis
.orient('bottom')
.showMaxMin(false)
.tickFormat(function(d) { return d })
;
yAxis
.orient((rightAlignYAxis) ? 'right' : 'left')
.tickFormat(d3.format(',.1f'))
;
tooltip.duration(0);
//============================================================
// Private Variables
//------------------------------------------------------------
var renderWatch = nv.utils.renderWatch(dispatch, duration);
function chart(selection) {
renderWatch.reset();
renderWatch.models(boxplot);
if (showXAxis) renderWatch.models(xAxis);
if (showYAxis) renderWatch.models(yAxis);
selection.each(function(data) {
var container = d3.select(this), that = this;
nv.utils.initSVG(container);
var availableWidth = (width || parseInt(container.style('width')) || 960) - margin.left - margin.right;
var availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom;
chart.update = function() {
dispatch.beforeUpdate();
container.transition().duration(duration).call(chart);
};
chart.container = this;
// TODO still need to find a way to validate quartile data presence using boxPlot callbacks.
// Display No Data message if there's nothing to show. (quartiles required at minimum).
if (!data || !data.length) {
var noDataText = container.selectAll('.nv-noData').data([noData]);
noDataText.enter().append('text')
.attr('class', 'nvd3 nv-noData')
.attr('dy', '-.7em')
.style('text-anchor', 'middle');
noDataText
.attr('x', margin.left + availableWidth / 2)
.attr('y', margin.top + availableHeight / 2)
.text(function(d) { return d });
return chart;
} else {
container.selectAll('.nv-noData').remove();
}
// Setup Scales
x = boxplot.xScale();
y = boxplot.yScale().clamp(true);
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-boxPlotWithAxes').data([data]);
var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-boxPlotWithAxes').append('g');
var defsEnter = gEnter.append('defs');
var g = wrap.select('g');
gEnter.append('g').attr('class', 'nv-x nv-axis');
gEnter.append('g').attr('class', 'nv-y nv-axis')
.append('g').attr('class', 'nv-zeroLine')
.append('line');
gEnter.append('g').attr('class', 'nv-barsWrap');
g.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
if (rightAlignYAxis) {
g.select('.nv-y.nv-axis')
.attr('transform', 'translate(' + availableWidth + ',0)');
}
// Main Chart Component(s)
boxplot.width(availableWidth).height(availableHeight);
var barsWrap = g.select('.nv-barsWrap')
.datum(data.filter(function(d) { return !d.disabled }))
barsWrap.transition().call(boxplot);
defsEnter.append('clipPath')
.attr('id', 'nv-x-label-clip-' + boxplot.id())
.append('rect');
g.select('#nv-x-label-clip-' + boxplot.id() + ' rect')
.attr('width', x.rangeBand() * (staggerLabels ? 2 : 1))
.attr('height', 16)
.attr('x', -x.rangeBand() / (staggerLabels ? 1 : 2 ));
// Setup Axes
if (showXAxis) {
xAxis
.scale(x)
.ticks( nv.utils.calcTicksX(availableWidth/100, data) )
.tickSize(-availableHeight, 0);
g.select('.nv-x.nv-axis').attr('transform', 'translate(0,' + y.range()[0] + ')');
g.select('.nv-x.nv-axis').call(xAxis);
var xTicks = g.select('.nv-x.nv-axis').selectAll('g');
if (staggerLabels) {
xTicks
.selectAll('text')
.attr('transform', function(d,i,j) { return 'translate(0,' + (j % 2 === 0 ? '5' : '17') + ')' })
}
}
if (showYAxis) {
yAxis
.scale(y)
.ticks( Math.floor(availableHeight/36) ) // can't use nv.utils.calcTicksY with Object data
.tickSize( -availableWidth, 0);
g.select('.nv-y.nv-axis').call(yAxis);
}
// Zero line
g.select('.nv-zeroLine line')
.attr('x1',0)
.attr('x2',availableWidth)
.attr('y1', y(0))
.attr('y2', y(0))
;
//============================================================
// Event Handling/Dispatching (in chart's scope)
//------------------------------------------------------------
});
renderWatch.renderEnd('nv-boxplot chart immediate');
return chart;
}
//============================================================
// Event Handling/Dispatching (out of chart's scope)
//------------------------------------------------------------
boxplot.dispatch.on('elementMouseover.tooltip', function(evt) {
tooltip.data(evt).hidden(false);
});
boxplot.dispatch.on('elementMouseout.tooltip', function(evt) {
tooltip.data(evt).hidden(true);
});
boxplot.dispatch.on('elementMousemove.tooltip', function(evt) {
tooltip();
});
//============================================================
// Expose Public Variables
//------------------------------------------------------------
chart.dispatch = dispatch;
chart.boxplot = boxplot;
chart.xAxis = xAxis;
chart.yAxis = yAxis;
chart.tooltip = tooltip;
chart.options = nv.utils.optionsFunc.bind(chart);
chart._options = Object.create({}, {
// simple options, just get/set the necessary values
width: {get: function(){return width;}, set: function(_){width=_;}},
height: {get: function(){return height;}, set: function(_){height=_;}},
staggerLabels: {get: function(){return staggerLabels;}, set: function(_){staggerLabels=_;}},
showXAxis: {get: function(){return showXAxis;}, set: function(_){showXAxis=_;}},
showYAxis: {get: function(){return showYAxis;}, set: function(_){showYAxis=_;}},
tooltipContent: {get: function(){return tooltip;}, set: function(_){tooltip=_;}},
noData: {get: function(){return noData;}, set: function(_){noData=_;}},
// options that require extra logic in the setter
margin: {get: function(){return margin;}, set: function(_){
margin.top = _.top !== undefined ? _.top : margin.top;
margin.right = _.right !== undefined ? _.right : margin.right;
margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
margin.left = _.left !== undefined ? _.left : margin.left;
}},
duration: {get: function(){return duration;}, set: function(_){
duration = _;
renderWatch.reset(duration);
boxplot.duration(duration);
xAxis.duration(duration);
yAxis.duration(duration);
}},
color: {get: function(){return color;}, set: function(_){
color = nv.utils.getColor(_);
boxplot.color(color);
}},
rightAlignYAxis: {get: function(){return rightAlignYAxis;}, set: function(_){
rightAlignYAxis = _;
yAxis.orient( (_) ? 'right' : 'left');
}}
});
nv.utils.inheritOptions(chart, boxplot);
nv.utils.initOptions(chart);
return chart;
}
// Chart design based on the recommendations of Stephen Few. Implementation
// based on the work of Clint Ivy, Jamie Love, and Jason Davies.
// http://projects.instantcognition.com/protovis/bulletchart/
nv.models.bullet = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var margin = {top: 0, right: 0, bottom: 0, left: 0}
, orient = 'left' // TODO top & bottom
, reverse = false
, ranges = function(d) { return d.ranges }
, markers = function(d) { return d.markers ? d.markers : [] }
, measures = function(d) { return d.measures }
, rangeLabels = function(d) { return d.rangeLabels ? d.rangeLabels : [] }
, markerLabels = function(d) { return d.markerLabels ? d.markerLabels : [] }
, measureLabels = function(d) { return d.measureLabels ? d.measureLabels : [] }
, forceX = [0] // List of numbers to Force into the X scale (ie. 0, or a max / min, etc.)
, width = 380
, height = 30
, container = null
, tickFormat = null
, color = nv.utils.getColor(['#1f77b4'])
, dispatch = d3.dispatch('elementMouseover', 'elementMouseout', 'elementMousemove')
, defaultRangeLabels = ["Maximum", "Mean", "Minimum"]
, legacyRangeClassNames = ["Max", "Avg", "Min"]
;
function sortLabels(labels, values){
var lz = labels.slice();
labels.sort(function(a, b){
var iA = lz.indexOf(a);
var iB = lz.indexOf(b);
return d3.descending(values[iA], values[iB]);
});
};
function chart(selection) {
selection.each(function(d, i) {
var availableWidth = width - margin.left - margin.right,
availableHeight = height - margin.top - margin.bottom;
container = d3.select(this);
nv.utils.initSVG(container);
var rangez = ranges.call(this, d, i).slice(),
markerz = markers.call(this, d, i).slice(),
measurez = measures.call(this, d, i).slice(),
rangeLabelz = rangeLabels.call(this, d, i).slice(),
markerLabelz = markerLabels.call(this, d, i).slice(),
measureLabelz = measureLabels.call(this, d, i).slice();
// Sort labels according to their sorted values
sortLabels(rangeLabelz, rangez);
sortLabels(markerLabelz, markerz);
sortLabels(measureLabelz, measurez);
// sort values descending
rangez.sort(d3.descending);
markerz.sort(d3.descending);
measurez.sort(d3.descending);
// Setup Scales
// Compute the new x-scale.
var x1 = d3.scale.linear()
.domain( d3.extent(d3.merge([forceX, rangez])) )
.range(reverse ? [availableWidth, 0] : [0, availableWidth]);
// Retrieve the old x-scale, if this is an update.
var x0 = this.__chart__ || d3.scale.linear()
.domain([0, Infinity])
.range(x1.range());
// Stash the new scale.
this.__chart__ = x1;
var rangeMin = d3.min(rangez), //rangez[2]
rangeMax = d3.max(rangez), //rangez[0]
rangeAvg = rangez[1];
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-bullet').data([d]);
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-bullet');
var gEnter = wrapEnter.append('g');
var g = wrap.select('g');
for(var i=0,il=rangez.length; i<il; i++){
var rangeClassNames = 'nv-range nv-range'+i;
if(i <= 2){
rangeClassNames = rangeClassNames + ' nv-range'+legacyRangeClassNames[i];
}
gEnter.append('rect').attr('class', rangeClassNames);
}
gEnter.append('rect').attr('class', 'nv-measure');
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
var w0 = function(d) { return Math.abs(x0(d) - x0(0)) }, // TODO: could optimize by precalculating x0(0) and x1(0)
w1 = function(d) { return Math.abs(x1(d) - x1(0)) };
var xp0 = function(d) { return d < 0 ? x0(d) : x0(0) },
xp1 = function(d) { return d < 0 ? x1(d) : x1(0) };
for(var i=0,il=rangez.length; i<il; i++){
var range = rangez[i];
g.select('rect.nv-range'+i)
.attr('height', availableHeight)
.attr('width', w1(range))
.attr('x', xp1(range))
.datum(range)
}
g.select('rect.nv-measure')
.style('fill', color)
.attr('height', availableHeight / 3)
.attr('y', availableHeight / 3)
.attr('width', measurez < 0 ?
x1(0) - x1(measurez[0])
: x1(measurez[0]) - x1(0))
.attr('x', xp1(measurez))
.on('mouseover', function() {
dispatch.elementMouseover({
value: measurez[0],
label: measureLabelz[0] || 'Current',
color: d3.select(this).style("fill")
})
})
.on('mousemove', function() {
dispatch.elementMousemove({
value: measurez[0],
label: measureLabelz[0] || 'Current',
color: d3.select(this).style("fill")
})
})
.on('mouseout', function() {
dispatch.elementMouseout({
value: measurez[0],
label: measureLabelz[0] || 'Current',
color: d3.select(this).style("fill")
})
});
var h3 = availableHeight / 6;
var markerData = markerz.map( function(marker, index) {
return {value: marker, label: markerLabelz[index]}
});
gEnter
.selectAll("path.nv-markerTriangle")
.data(markerData)
.enter()
.append('path')
.attr('class', 'nv-markerTriangle')
.attr('d', 'M0,' + h3 + 'L' + h3 + ',' + (-h3) + ' ' + (-h3) + ',' + (-h3) + 'Z')
.on('mouseover', function(d) {
dispatch.elementMouseover({
value: d.value,
label: d.label || 'Previous',
color: d3.select(this).style("fill"),
pos: [x1(d.value), availableHeight/2]
})
})
.on('mousemove', function(d) {
dispatch.elementMousemove({
value: d.value,
label: d.label || 'Previous',
color: d3.select(this).style("fill")
})
})
.on('mouseout', function(d, i) {
dispatch.elementMouseout({
value: d.value,
label: d.label || 'Previous',
color: d3.select(this).style("fill")
})
});
g.selectAll("path.nv-markerTriangle")
.data(markerData)
.attr('transform', function(d) { return 'translate(' + x1(d.value) + ',' + (availableHeight / 2) + ')' });
wrap.selectAll('.nv-range')
.on('mouseover', function(d,i) {
var label = rangeLabelz[i] || defaultRangeLabels[i];
dispatch.elementMouseover({
value: d,
label: label,
color: d3.select(this).style("fill")
})
})
.on('mousemove', function() {
dispatch.elementMousemove({
value: measurez[0],
label: measureLabelz[0] || 'Previous',
color: d3.select(this).style("fill")
})
})
.on('mouseout', function(d,i) {
var label = rangeLabelz[i] || defaultRangeLabels[i];
dispatch.elementMouseout({
value: d,
label: label,
color: d3.select(this).style("fill")
})
});
});
return chart;
}
//============================================================
// Expose Public Variables
//------------------------------------------------------------
chart.dispatch = dispatch;
chart.options = nv.utils.optionsFunc.bind(chart);
chart._options = Object.create({}, {
// simple options, just get/set the necessary values
ranges: {get: function(){return ranges;}, set: function(_){ranges=_;}}, // ranges (bad, satisfactory, good)
markers: {get: function(){return markers;}, set: function(_){markers=_;}}, // markers (previous, goal)
measures: {get: function(){return measures;}, set: function(_){measures=_;}}, // measures (actual, forecast)
forceX: {get: function(){return forceX;}, set: function(_){forceX=_;}},
width: {get: function(){return width;}, set: function(_){width=_;}},
height: {get: function(){return height;}, set: function(_){height=_;}},
tickFormat: {get: function(){return tickFormat;}, set: function(_){tickFormat=_;}},
// options that require extra logic in the setter
margin: {get: function(){return margin;}, set: function(_){
margin.top = _.top !== undefined ? _.top : margin.top;
margin.right = _.right !== undefined ? _.right : margin.right;
margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
margin.left = _.left !== undefined ? _.left : margin.left;
}},
orient: {get: function(){return orient;}, set: function(_){ // left, right, top, bottom
orient = _;
reverse = orient == 'right' || orient == 'bottom';
}},
color: {get: function(){return color;}, set: function(_){
color = nv.utils.getColor(_);
}}
});
nv.utils.initOptions(chart);
return chart;
};
// Chart design based on the recommendations of Stephen Few. Implementation
// based on the work of Clint Ivy, Jamie Love, and Jason Davies.
// http://projects.instantcognition.com/protovis/bulletchart/
nv.models.bulletChart = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var bullet = nv.models.bullet();
var tooltip = nv.models.tooltip();
var orient = 'left' // TODO top & bottom
, reverse = false
, margin = {top: 5, right: 40, bottom: 20, left: 120}
, ranges = function(d) { return d.ranges }
, markers = function(d) { return d.markers ? d.markers : [] }
, measures = function(d) { return d.measures }
, width = null
, height = 55
, tickFormat = null
, ticks = null
, noData = null
, dispatch = d3.dispatch()
;
tooltip
.duration(0)
.headerEnabled(false);
function chart(selection) {
selection.each(function(d, i) {
var container = d3.select(this);
nv.utils.initSVG(container);
var availableWidth = nv.utils.availableWidth(width, container, margin),
availableHeight = height - margin.top - margin.bottom,
that = this;
chart.update = function() { chart(selection) };
chart.container = this;
// Display No Data message if there's nothing to show.
if (!d || !ranges.call(this, d, i)) {
nv.utils.noData(chart, container)
return chart;
} else {
container.selectAll('.nv-noData').remove();
}
var rangez = ranges.call(this, d, i).slice().sort(d3.descending),
markerz = markers.call(this, d, i).slice().sort(d3.descending),
measurez = measures.call(this, d, i).slice().sort(d3.descending);
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-bulletChart').data([d]);
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-bulletChart');
var gEnter = wrapEnter.append('g');
var g = wrap.select('g');
gEnter.append('g').attr('class', 'nv-bulletWrap');
gEnter.append('g').attr('class', 'nv-titles');
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
// Compute the new x-scale.
var x1 = d3.scale.linear()
.domain([0, Math.max(rangez[0], (markerz[0] || 0), measurez[0])]) // TODO: need to allow forceX and forceY, and xDomain, yDomain
.range(reverse ? [availableWidth, 0] : [0, availableWidth]);
// Retrieve the old x-scale, if this is an update.
var x0 = this.__chart__ || d3.scale.linear()
.domain([0, Infinity])
.range(x1.range());
// Stash the new scale.
this.__chart__ = x1;
var w0 = function(d) { return Math.abs(x0(d) - x0(0)) }, // TODO: could optimize by precalculating x0(0) and x1(0)
w1 = function(d) { return Math.abs(x1(d) - x1(0)) };
var title = gEnter.select('.nv-titles').append('g')
.attr('text-anchor', 'end')
.attr('transform', 'translate(-6,' + (height - margin.top - margin.bottom) / 2 + ')');
title.append('text')
.attr('class', 'nv-title')
.text(function(d) { return d.title; });
title.append('text')
.attr('class', 'nv-subtitle')
.attr('dy', '1em')
.text(function(d) { return d.subtitle; });
bullet
.width(availableWidth)
.height(availableHeight)
var bulletWrap = g.select('.nv-bulletWrap');
d3.transition(bulletWrap).call(bullet);
// Compute the tick format.
var format = tickFormat || x1.tickFormat( availableWidth / 100 );
// Update the tick groups.
var tick = g.selectAll('g.nv-tick')
.data(x1.ticks( ticks ? ticks : (availableWidth / 50) ), function(d) {
return this.textContent || format(d);
});
// Initialize the ticks with the old scale, x0.
var tickEnter = tick.enter().append('g')
.attr('class', 'nv-tick')
.attr('transform', function(d) { return 'translate(' + x0(d) + ',0)' })
.style('opacity', 1e-6);
tickEnter.append('line')
.attr('y1', availableHeight)
.attr('y2', availableHeight * 7 / 6);
tickEnter.append('text')
.attr('text-anchor', 'middle')
.attr('dy', '1em')
.attr('y', availableHeight * 7 / 6)
.text(format);
// Transition the updating ticks to the new scale, x1.
var tickUpdate = d3.transition(tick)
.attr('transform', function(d) { return 'translate(' + x1(d) + ',0)' })
.style('opacity', 1);
tickUpdate.select('line')
.attr('y1', availableHeight)
.attr('y2', availableHeight * 7 / 6);
tickUpdate.select('text')
.attr('y', availableHeight * 7 / 6);
// Transition the exiting ticks to the new scale, x1.
d3.transition(tick.exit())
.attr('transform', function(d) { return 'translate(' + x1(d) + ',0)' })
.style('opacity', 1e-6)
.remove();
});
d3.timer.flush();
return chart;
}
//============================================================
// Event Handling/Dispatching (out of chart's scope)
//------------------------------------------------------------
bullet.dispatch.on('elementMouseover.tooltip', function(evt) {
evt['series'] = {
key: evt.label,
value: evt.value,
color: evt.color
};
tooltip.data(evt).hidden(false);
});
bullet.dispatch.on('elementMouseout.tooltip', function(evt) {
tooltip.hidden(true);
});
bullet.dispatch.on('elementMousemove.tooltip', function(evt) {
tooltip();
});
//============================================================
// Expose Public Variables
//------------------------------------------------------------
chart.bullet = bullet;
chart.dispatch = dispatch;
chart.tooltip = tooltip;
chart.options = nv.utils.optionsFunc.bind(chart);
chart._options = Object.create({}, {
// simple options, just get/set the necessary values
ranges: {get: function(){return ranges;}, set: function(_){ranges=_;}}, // ranges (bad, satisfactory, good)
markers: {get: function(){return markers;}, set: function(_){markers=_;}}, // markers (previous, goal)
measures: {get: function(){return measures;}, set: function(_){measures=_;}}, // measures (actual, forecast)
width: {get: function(){return width;}, set: function(_){width=_;}},
height: {get: function(){return height;}, set: function(_){height=_;}},
tickFormat: {get: function(){return tickFormat;}, set: function(_){tickFormat=_;}},
ticks: {get: function(){return ticks;}, set: function(_){ticks=_;}},
noData: {get: function(){return noData;}, set: function(_){noData=_;}},
// options that require extra logic in the setter
margin: {get: function(){return margin;}, set: function(_){
margin.top = _.top !== undefined ? _.top : margin.top;
margin.right = _.right !== undefined ? _.right : margin.right;
margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
margin.left = _.left !== undefined ? _.left : margin.left;
}},
orient: {get: function(){return orient;}, set: function(_){ // left, right, top, bottom
orient = _;
reverse = orient == 'right' || orient == 'bottom';
}}
});
nv.utils.inheritOptions(chart, bullet);
nv.utils.initOptions(chart);
return chart;
};
nv.models.candlestickBar = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var margin = {top: 0, right: 0, bottom: 0, left: 0}
, width = null
, height = null
, id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one
, container
, x = d3.scale.linear()
, y = d3.scale.linear()
, getX = function(d) { return d.x }
, getY = function(d) { return d.y }
, getOpen = function(d) { return d.open }
, getClose = function(d) { return d.close }
, getHigh = function(d) { return d.high }
, getLow = function(d) { return d.low }
, forceX = []
, forceY = []
, padData = false // If true, adds half a data points width to front and back, for lining up a line chart with a bar chart
, clipEdge = true
, color = nv.utils.defaultColor()
, interactive = false
, xDomain
, yDomain
, xRange
, yRange
, dispatch = d3.dispatch('stateChange', 'changeState', 'renderEnd', 'chartClick', 'elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout', 'elementMousemove')
;
//============================================================
// Private Variables
//------------------------------------------------------------
function chart(selection) {
selection.each(function(data) {
container = d3.select(this);
var availableWidth = nv.utils.availableWidth(width, container, margin),
availableHeight = nv.utils.availableHeight(height, container, margin);
nv.utils.initSVG(container);
// Width of the candlestick bars.
var barWidth = (availableWidth / data[0].values.length) * .45;
// Setup Scales
x.domain(xDomain || d3.extent(data[0].values.map(getX).concat(forceX) ));
if (padData)
x.range(xRange || [availableWidth * .5 / data[0].values.length, availableWidth * (data[0].values.length - .5) / data[0].values.length ]);
else
x.range(xRange || [5 + barWidth / 2, availableWidth - barWidth / 2 - 5]);
y.domain(yDomain || [
d3.min(data[0].values.map(getLow).concat(forceY)),
d3.max(data[0].values.map(getHigh).concat(forceY))
]
).range(yRange || [availableHeight, 0]);
// If scale's domain don't have a range, slightly adjust to make one... so a chart can show a single data point
if (x.domain()[0] === x.domain()[1])
x.domain()[0] ?
x.domain([x.domain()[0] - x.domain()[0] * 0.01, x.domain()[1] + x.domain()[1] * 0.01])
: x.domain([-1,1]);
if (y.domain()[0] === y.domain()[1])
y.domain()[0] ?
y.domain([y.domain()[0] + y.domain()[0] * 0.01, y.domain()[1] - y.domain()[1] * 0.01])
: y.domain([-1,1]);
// Setup containers and skeleton of chart
var wrap = d3.select(this).selectAll('g.nv-wrap.nv-candlestickBar').data([data[0].values]);
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-candlestickBar');
var defsEnter = wrapEnter.append('defs');
var gEnter = wrapEnter.append('g');
var g = wrap.select('g');
gEnter.append('g').attr('class', 'nv-ticks');
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
container
.on('click', function(d,i) {
dispatch.chartClick({
data: d,
index: i,
pos: d3.event,
id: id
});
});
defsEnter.append('clipPath')
.attr('id', 'nv-chart-clip-path-' + id)
.append('rect');
wrap.select('#nv-chart-clip-path-' + id + ' rect')
.attr('width', availableWidth)
.attr('height', availableHeight);
g .attr('clip-path', clipEdge ? 'url(#nv-chart-clip-path-' + id + ')' : '');
var ticks = wrap.select('.nv-ticks').selectAll('.nv-tick')
.data(function(d) { return d });
ticks.exit().remove();
var tickGroups = ticks.enter().append('g');
// The colors are currently controlled by CSS.
ticks
.attr('class', function(d, i, j) { return (getOpen(d, i) > getClose(d, i) ? 'nv-tick negative' : 'nv-tick positive') + ' nv-tick-' + j + '-' + i});
var lines = tickGroups.append('line')
.attr('class', 'nv-candlestick-lines')
.attr('transform', function(d, i) { return 'translate(' + x(getX(d, i)) + ',0)'; })
.attr('x1', 0)
.attr('y1', function(d, i) { return y(getHigh(d, i)); })
.attr('x2', 0)
.attr('y2', function(d, i) { return y(getLow(d, i)); });
var rects = tickGroups.append('rect')
.attr('class', 'nv-candlestick-rects nv-bars')
.attr('transform', function(d, i) {
return 'translate(' + (x(getX(d, i)) - barWidth/2) + ','
+ (y(getY(d, i)) - (getOpen(d, i) > getClose(d, i) ? (y(getClose(d, i)) - y(getOpen(d, i))) : 0))
+ ')';
})
.attr('x', 0)
.attr('y', 0)
.attr('width', barWidth)
.attr('height', function(d, i) {
var open = getOpen(d, i);
var close = getClose(d, i);
return open > close ? y(close) - y(open) : y(open) - y(close);
});
ticks.select('.nv-candlestick-lines').transition()
.attr('transform', function(d, i) { return 'translate(' + x(getX(d, i)) + ',0)'; })
.attr('x1', 0)
.attr('y1', function(d, i) { return y(getHigh(d, i)); })
.attr('x2', 0)
.attr('y2', function(d, i) { return y(getLow(d, i)); });
ticks.select('.nv-candlestick-rects').transition()
.attr('transform', function(d, i) {
return 'translate(' + (x(getX(d, i)) - barWidth/2) + ','
+ (y(getY(d, i)) - (getOpen(d, i) > getClose(d, i) ? (y(getClose(d, i)) - y(getOpen(d, i))) : 0))
+ ')';
})
.attr('x', 0)
.attr('y', 0)
.attr('width', barWidth)
.attr('height', function(d, i) {
var open = getOpen(d, i);
var close = getClose(d, i);
return open > close ? y(close) - y(open) : y(open) - y(close);
});
});
return chart;
}
//Create methods to allow outside functions to highlight a specific bar.
chart.highlightPoint = function(pointIndex, isHoverOver) {
chart.clearHighlights();
container.select(".nv-candlestickBar .nv-tick-0-" + pointIndex)
.classed("hover", isHoverOver)
;
};
chart.clearHighlights = function() {
container.select(".nv-candlestickBar .nv-tick.hover")
.classed("hover", false)
;
};
//============================================================
// Expose Public Variables
//------------------------------------------------------------
chart.dispatch = dispatch;
chart.options = nv.utils.optionsFunc.bind(chart);
chart._options = Object.create({}, {
// simple options, just get/set the necessary values
width: {get: function(){return width;}, set: function(_){width=_;}},
height: {get: function(){return height;}, set: function(_){height=_;}},
xScale: {get: function(){return x;}, set: function(_){x=_;}},
yScale: {get: function(){return y;}, set: function(_){y=_;}},
xDomain: {get: function(){return xDomain;}, set: function(_){xDomain=_;}},
yDomain: {get: function(){return yDomain;}, set: function(_){yDomain=_;}},
xRange: {get: function(){return xRange;}, set: function(_){xRange=_;}},
yRange: {get: function(){return yRange;}, set: function(_){yRange=_;}},
forceX: {get: function(){return forceX;}, set: function(_){forceX=_;}},
forceY: {get: function(){return forceY;}, set: function(_){forceY=_;}},
padData: {get: function(){return padData;}, set: function(_){padData=_;}},
clipEdge: {get: function(){return clipEdge;}, set: function(_){clipEdge=_;}},
id: {get: function(){return id;}, set: function(_){id=_;}},
interactive: {get: function(){return interactive;}, set: function(_){interactive=_;}},
x: {get: function(){return getX;}, set: function(_){getX=_;}},
y: {get: function(){return getY;}, set: function(_){getY=_;}},
open: {get: function(){return getOpen();}, set: function(_){getOpen=_;}},
close: {get: function(){return getClose();}, set: function(_){getClose=_;}},
high: {get: function(){return getHigh;}, set: function(_){getHigh=_;}},
low: {get: function(){return getLow;}, set: function(_){getLow=_;}},
// options that require extra logic in the setter
margin: {get: function(){return margin;}, set: function(_){
margin.top = _.top != undefined ? _.top : margin.top;
margin.right = _.right != undefined ? _.right : margin.right;
margin.bottom = _.bottom != undefined ? _.bottom : margin.bottom;
margin.left = _.left != undefined ? _.left : margin.left;
}},
color: {get: function(){return color;}, set: function(_){
color = nv.utils.getColor(_);
}}
});
nv.utils.initOptions(chart);
return chart;
};
nv.models.cumulativeLineChart = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var lines = nv.models.line()
, xAxis = nv.models.axis()
, yAxis = nv.models.axis()
, legend = nv.models.legend()
, controls = nv.models.legend()
, interactiveLayer = nv.interactiveGuideline()
, tooltip = nv.models.tooltip()
;
var margin = {top: 30, right: 30, bottom: 50, left: 60}
, color = nv.utils.defaultColor()
, width = null
, height = null
, showLegend = true
, showXAxis = true
, showYAxis = true
, rightAlignYAxis = false
, showControls = true
, useInteractiveGuideline = false
, rescaleY = true
, x //can be accessed via chart.xScale()
, y //can be accessed via chart.yScale()
, id = lines.id()
, state = nv.utils.state()
, defaultState = null
, noData = null
, average = function(d) { return d.average }
, dispatch = d3.dispatch('stateChange', 'changeState', 'renderEnd')
, transitionDuration = 250
, duration = 250
, noErrorCheck = false //if set to TRUE, will bypass an error check in the indexify function.
;
state.index = 0;
state.rescaleY = rescaleY;
xAxis.orient('bottom').tickPadding(7);
yAxis.orient((rightAlignYAxis) ? 'right' : 'left');
tooltip.valueFormatter(function(d, i) {
return yAxis.tickFormat()(d, i);
}).headerFormatter(function(d, i) {
return xAxis.tickFormat()(d, i);
});
controls.updateState(false);
//============================================================
// Private Variables
//------------------------------------------------------------
var dx = d3.scale.linear()
, index = {i: 0, x: 0}
, renderWatch = nv.utils.renderWatch(dispatch, duration)
;
var stateGetter = function(data) {
return function(){
return {
active: data.map(function(d) { return !d.disabled }),
index: index.i,
rescaleY: rescaleY
};
}
};
var stateSetter = function(data) {
return function(state) {
if (state.index !== undefined)
index.i = state.index;
if (state.rescaleY !== undefined)
rescaleY = state.rescaleY;
if (state.active !== undefined)
data.forEach(function(series,i) {
series.disabled = !state.active[i];
});
}
};
function chart(selection) {
renderWatch.reset();
renderWatch.models(lines);
if (showXAxis) renderWatch.models(xAxis);
if (showYAxis) renderWatch.models(yAxis);
selection.each(function(data) {
var container = d3.select(this);
nv.utils.initSVG(container);
container.classed('nv-chart-' + id, true);
var that = this;
var availableWidth = nv.utils.availableWidth(width, container, margin),
availableHeight = nv.utils.availableHeight(height, container, margin);
chart.update = function() {
if (duration === 0)
container.call(chart);
else
container.transition().duration(duration).call(chart)
};
chart.container = this;
state
.setter(stateSetter(data), chart.update)
.getter(stateGetter(data))
.update();
// DEPRECATED set state.disableddisabled
state.disabled = data.map(function(d) { return !!d.disabled });
if (!defaultState) {
var key;
defaultState = {};
for (key in state) {
if (state[key] instanceof Array)
defaultState[key] = state[key].slice(0);
else
defaultState[key] = state[key];
}
}
var indexDrag = d3.behavior.drag()
.on('dragstart', dragStart)
.on('drag', dragMove)
.on('dragend', dragEnd);
function dragStart(d,i) {
d3.select(chart.container)
.style('cursor', 'ew-resize');
}
function dragMove(d,i) {
index.x = d3.event.x;
index.i = Math.round(dx.invert(index.x));
updateZero();
}
function dragEnd(d,i) {
d3.select(chart.container)
.style('cursor', 'auto');
// update state and send stateChange with new index
state.index = index.i;
dispatch.stateChange(state);
}
// Display No Data message if there's nothing to show.
if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) {
nv.utils.noData(chart, container)
return chart;
} else {
container.selectAll('.nv-noData').remove();
}
// Setup Scales
x = lines.xScale();
y = lines.yScale();
if (!rescaleY) {
var seriesDomains = data
.filter(function(series) { return !series.disabled })
.map(function(series,i) {
var initialDomain = d3.extent(series.values, lines.y());
//account for series being disabled when losing 95% or more
if (initialDomain[0] < -.95) initialDomain[0] = -.95;
return [
(initialDomain[0] - initialDomain[1]) / (1 + initialDomain[1]),
(initialDomain[1] - initialDomain[0]) / (1 + initialDomain[0])
];
});
var completeDomain = [
d3.min(seriesDomains, function(d) { return d[0] }),
d3.max(seriesDomains, function(d) { return d[1] })
];
lines.yDomain(completeDomain);
} else {
lines.yDomain(null);
}
dx.domain([0, data[0].values.length - 1]) //Assumes all series have same length
.range([0, availableWidth])
.clamp(true);
var data = indexify(index.i, data);
// Setup containers and skeleton of chart
var interactivePointerEvents = (useInteractiveGuideline) ? "none" : "all";
var wrap = container.selectAll('g.nv-wrap.nv-cumulativeLine').data([data]);
var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-cumulativeLine').append('g');
var g = wrap.select('g');
gEnter.append('g').attr('class', 'nv-interactive');
gEnter.append('g').attr('class', 'nv-x nv-axis').style("pointer-events","none");
gEnter.append('g').attr('class', 'nv-y nv-axis');
gEnter.append('g').attr('class', 'nv-background');
gEnter.append('g').attr('class', 'nv-linesWrap').style("pointer-events",interactivePointerEvents);
gEnter.append('g').attr('class', 'nv-avgLinesWrap').style("pointer-events","none");
gEnter.append('g').attr('class', 'nv-legendWrap');
gEnter.append('g').attr('class', 'nv-controlsWrap');
// Legend
if (!showLegend) {
g.select('.nv-legendWrap').selectAll('*').remove();
} else {
legend.width(availableWidth);
g.select('.nv-legendWrap')
.datum(data)
.call(legend);
if ( margin.top != legend.height()) {
margin.top = legend.height();
availableHeight = nv.utils.availableHeight(height, container, margin);
}
g.select('.nv-legendWrap')
.attr('transform', 'translate(0,' + (-margin.top) +')')
}
// Controls
if (!showControls) {
g.select('.nv-controlsWrap').selectAll('*').remove();
} else {
var controlsData = [
{ key: 'Re-scale y-axis', disabled: !rescaleY }
];
controls
.width(140)
.color(['#444', '#444', '#444'])
.rightAlign(false)
.margin({top: 5, right: 0, bottom: 5, left: 20})
;
g.select('.nv-controlsWrap')
.datum(controlsData)
.attr('transform', 'translate(0,' + (-margin.top) +')')
.call(controls);
}
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
if (rightAlignYAxis) {
g.select(".nv-y.nv-axis")
.attr("transform", "translate(" + availableWidth + ",0)");
}
// Show error if series goes below 100%
var tempDisabled = data.filter(function(d) { return d.tempDisabled });
wrap.select('.tempDisabled').remove(); //clean-up and prevent duplicates
if (tempDisabled.length) {
wrap.append('text').attr('class', 'tempDisabled')
.attr('x', availableWidth / 2)
.attr('y', '-.71em')
.style('text-anchor', 'end')
.text(tempDisabled.map(function(d) { return d.key }).join(', ') + ' values cannot be calculated for this time period.');
}
//Set up interactive layer
if (useInteractiveGuideline) {
interactiveLayer
.width(availableWidth)
.height(availableHeight)
.margin({left:margin.left,top:margin.top})
.svgContainer(container)
.xScale(x);
wrap.select(".nv-interactive").call(interactiveLayer);
}
gEnter.select('.nv-background')
.append('rect');
g.select('.nv-background rect')
.attr('width', availableWidth)
.attr('height', availableHeight);
lines
//.x(function(d) { return d.x })
.y(function(d) { return d.display.y })
.width(availableWidth)
.height(availableHeight)
.color(data.map(function(d,i) {
return d.color || color(d, i);
}).filter(function(d,i) { return !data[i].disabled && !data[i].tempDisabled; }));
var linesWrap = g.select('.nv-linesWrap')
.datum(data.filter(function(d) { return !d.disabled && !d.tempDisabled }));
linesWrap.call(lines);
//Store a series index number in the data array.
data.forEach(function(d,i) {
d.seriesIndex = i;
});
var avgLineData = data.filter(function(d) {
return !d.disabled && !!average(d);
});
var avgLines = g.select(".nv-avgLinesWrap").selectAll("line")
.data(avgLineData, function(d) { return d.key; });
var getAvgLineY = function(d) {
//If average lines go off the svg element, clamp them to the svg bounds.
var yVal = y(average(d));
if (yVal < 0) return 0;
if (yVal > availableHeight) return availableHeight;
return yVal;
};
avgLines.enter()
.append('line')
.style('stroke-width',2)
.style('stroke-dasharray','10,10')
.style('stroke',function (d,i) {
return lines.color()(d,d.seriesIndex);
})
.attr('x1',0)
.attr('x2',availableWidth)
.attr('y1', getAvgLineY)
.attr('y2', getAvgLineY);
avgLines
.style('stroke-opacity',function(d){
//If average lines go offscreen, make them transparent
var yVal = y(average(d));
if (yVal < 0 || yVal > availableHeight) return 0;
return 1;
})
.attr('x1',0)
.attr('x2',availableWidth)
.attr('y1', getAvgLineY)
.attr('y2', getAvgLineY);
avgLines.exit().remove();
//Create index line
var indexLine = linesWrap.selectAll('.nv-indexLine')
.data([index]);
indexLine.enter().append('rect').attr('class', 'nv-indexLine')
.attr('width', 3)
.attr('x', -2)
.attr('fill', 'red')
.attr('fill-opacity', .5)
.style("pointer-events","all")
.call(indexDrag);
indexLine
.attr('transform', function(d) { return 'translate(' + dx(d.i) + ',0)' })
.attr('height', availableHeight);
// Setup Axes
if (showXAxis) {
xAxis
.scale(x)
._ticks( nv.utils.calcTicksX(availableWidth/70, data) )
.tickSize(-availableHeight, 0);
g.select('.nv-x.nv-axis')
.attr('transform', 'translate(0,' + y.range()[0] + ')');
g.select('.nv-x.nv-axis')
.call(xAxis);
}
if (showYAxis) {
yAxis
.scale(y)
._ticks( nv.utils.calcTicksY(availableHeight/36, data) )
.tickSize( -availableWidth, 0);
g.select('.nv-y.nv-axis')
.call(yAxis);
}
//============================================================
// Event Handling/Dispatching (in chart's scope)
//------------------------------------------------------------
function updateZero() {
indexLine
.data([index]);
//When dragging the index line, turn off line transitions.
// Then turn them back on when done dragging.
var oldDuration = chart.duration();
chart.duration(0);
chart.update();
chart.duration(oldDuration);
}
g.select('.nv-background rect')
.on('click', function() {
index.x = d3.mouse(this)[0];
index.i = Math.round(dx.invert(index.x));
// update state and send stateChange with new index
state.index = index.i;
dispatch.stateChange(state);
updateZero();
});
lines.dispatch.on('elementClick', function(e) {
index.i = e.pointIndex;
index.x = dx(index.i);
// update state and send stateChange with new index
state.index = index.i;
dispatch.stateChange(state);
updateZero();
});
controls.dispatch.on('legendClick', function(d,i) {
d.disabled = !d.disabled;
rescaleY = !d.disabled;
state.rescaleY = rescaleY;
dispatch.stateChange(state);
chart.update();
});
legend.dispatch.on('stateChange', function(newState) {
for (var key in newState)
state[key] = newState[key];
dispatch.stateChange(state);
chart.update();
});
interactiveLayer.dispatch.on('elementMousemove', function(e) {
lines.clearHighlights();
var singlePoint, pointIndex, pointXLocation, allData = [];
data
.filter(function(series, i) {
series.seriesIndex = i;
return !series.disabled;
})
.forEach(function(series,i) {
pointIndex = nv.interactiveBisect(series.values, e.pointXValue, chart.x());
lines.highlightPoint(i, pointIndex, true);
var point = series.values[pointIndex];
if (typeof point === 'undefined') return;
if (typeof singlePoint === 'undefined') singlePoint = point;
if (typeof pointXLocation === 'undefined') pointXLocation = chart.xScale()(chart.x()(point,pointIndex));
allData.push({
key: series.key,
value: chart.y()(point, pointIndex),
color: color(series,series.seriesIndex)
});
});
//Highlight the tooltip entry based on which point the mouse is closest to.
if (allData.length > 2) {
var yValue = chart.yScale().invert(e.mouseY);
var domainExtent = Math.abs(chart.yScale().domain()[0] - chart.yScale().domain()[1]);
var threshold = 0.03 * domainExtent;
var indexToHighlight = nv.nearestValueIndex(allData.map(function(d){return d.value}),yValue,threshold);
if (indexToHighlight !== null)
allData[indexToHighlight].highlight = true;
}
var xValue = xAxis.tickFormat()(chart.x()(singlePoint,pointIndex), pointIndex);
interactiveLayer.tooltip
.chartContainer(that.parentNode)
.valueFormatter(function(d,i) {
return yAxis.tickFormat()(d);
})
.data(
{
value: xValue,
series: allData
}
)();
interactiveLayer.renderGuideLine(pointXLocation);
});
interactiveLayer.dispatch.on("elementMouseout",function(e) {
lines.clearHighlights();
});
// Update chart from a state object passed to event handler
dispatch.on('changeState', function(e) {
if (typeof e.disabled !== 'undefined') {
data.forEach(function(series,i) {
series.disabled = e.disabled[i];
});
state.disabled = e.disabled;
}
if (typeof e.index !== 'undefined') {
index.i = e.index;
index.x = dx(index.i);
state.index = e.index;
indexLine
.data([index]);
}
if (typeof e.rescaleY !== 'undefined') {
rescaleY = e.rescaleY;
}
chart.update();
});
});
renderWatch.renderEnd('cumulativeLineChart immediate');
return chart;
}
//============================================================
// Event Handling/Dispatching (out of chart's scope)
//------------------------------------------------------------
lines.dispatch.on('elementMouseover.tooltip', function(evt) {
var point = {
x: chart.x()(evt.point),
y: chart.y()(evt.point),
color: evt.point.color
};
evt.point = point;
tooltip.data(evt).hidden(false);
});
lines.dispatch.on('elementMouseout.tooltip', function(evt) {
tooltip.hidden(true)
});
//============================================================
// Functions
//------------------------------------------------------------
var indexifyYGetter = null;
/* Normalize the data according to an index point. */
function indexify(idx, data) {
if (!indexifyYGetter) indexifyYGetter = lines.y();
return data.map(function(line, i) {
if (!line.values) {
return line;
}
var indexValue = line.values[idx];
if (indexValue == null) {
return line;
}
var v = indexifyYGetter(indexValue, idx);
//TODO: implement check below, and disable series if series loses 100% or more cause divide by 0 issue
if (v < -.95 && !noErrorCheck) {
//if a series loses more than 100%, calculations fail.. anything close can cause major distortion (but is mathematically correct till it hits 100)
line.tempDisabled = true;
return line;
}
line.tempDisabled = false;
line.values = line.values.map(function(point, pointIndex) {
point.display = {'y': (indexifyYGetter(point, pointIndex) - v) / (1 + v) };
return point;
});
return line;
})
}
//============================================================
// Expose Public Variables
//------------------------------------------------------------
// expose chart's sub-components
chart.dispatch = dispatch;
chart.lines = lines;
chart.legend = legend;
chart.controls = controls;
chart.xAxis = xAxis;
chart.yAxis = yAxis;
chart.interactiveLayer = interactiveLayer;
chart.state = state;
chart.tooltip = tooltip;
chart.options = nv.utils.optionsFunc.bind(chart);
chart._options = Object.create({}, {
// simple options, just get/set the necessary values
width: {get: function(){return width;}, set: function(_){width=_;}},
height: {get: function(){return height;}, set: function(_){height=_;}},
rescaleY: {get: function(){return rescaleY;}, set: function(_){rescaleY=_;}},
showControls: {get: function(){return showControls;}, set: function(_){showControls=_;}},
showLegend: {get: function(){return showLegend;}, set: function(_){showLegend=_;}},
average: {get: function(){return average;}, set: function(_){average=_;}},
defaultState: {get: function(){return defaultState;}, set: function(_){defaultState=_;}},
noData: {get: function(){return noData;}, set: function(_){noData=_;}},
showXAxis: {get: function(){return showXAxis;}, set: function(_){showXAxis=_;}},
showYAxis: {get: function(){return showYAxis;}, set: function(_){showYAxis=_;}},
noErrorCheck: {get: function(){return noErrorCheck;}, set: function(_){noErrorCheck=_;}},
// options that require extra logic in the setter
margin: {get: function(){return margin;}, set: function(_){
margin.top = _.top !== undefined ? _.top : margin.top;
margin.right = _.right !== undefined ? _.right : margin.right;
margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
margin.left = _.left !== undefined ? _.left : margin.left;
}},
color: {get: function(){return color;}, set: function(_){
color = nv.utils.getColor(_);
legend.color(color);
}},
useInteractiveGuideline: {get: function(){return useInteractiveGuideline;}, set: function(_){
useInteractiveGuideline = _;
if (_ === true) {
chart.interactive(false);
chart.useVoronoi(false);
}
}},
rightAlignYAxis: {get: function(){return rightAlignYAxis;}, set: function(_){
rightAlignYAxis = _;
yAxis.orient( (_) ? 'right' : 'left');
}},
duration: {get: function(){return duration;}, set: function(_){
duration = _;
lines.duration(duration);
xAxis.duration(duration);
yAxis.duration(duration);
renderWatch.reset(duration);
}}
});
nv.utils.inheritOptions(chart, lines);
nv.utils.initOptions(chart);
return chart;
};
//TODO: consider deprecating by adding necessary features to multiBar model
nv.models.discreteBar = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var margin = {top: 0, right: 0, bottom: 0, left: 0}
, width = 960
, height = 500
, id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one
, container
, x = d3.scale.ordinal()
, y = d3.scale.linear()
, getX = function(d) { return d.x }
, getY = function(d) { return d.y }
, forceY = [0] // 0 is forced by default.. this makes sense for the majority of bar graphs... user can always do chart.forceY([]) to remove
, color = nv.utils.defaultColor()
, showValues = false
, valueFormat = d3.format(',.2f')
, xDomain
, yDomain
, xRange
, yRange
, dispatch = d3.dispatch('chartClick', 'elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout', 'elementMousemove', 'renderEnd')
, rectClass = 'discreteBar'
, duration = 250
;
//============================================================
// Private Variables
//------------------------------------------------------------
var x0, y0;
var renderWatch = nv.utils.renderWatch(dispatch, duration);
function chart(selection) {
renderWatch.reset();
selection.each(function(data) {
var availableWidth = width - margin.left - margin.right,
availableHeight = height - margin.top - margin.bottom;
container = d3.select(this);
nv.utils.initSVG(container);
//add series index to each data point for reference
data.forEach(function(series, i) {
series.values.forEach(function(point) {
point.series = i;
});
});
// Setup Scales
// remap and flatten the data for use in calculating the scales' domains
var seriesData = (xDomain && yDomain) ? [] : // if we know xDomain and yDomain, no need to calculate
data.map(function(d) {
return d.values.map(function(d,i) {
return { x: getX(d,i), y: getY(d,i), y0: d.y0 }
})
});
x .domain(xDomain || d3.merge(seriesData).map(function(d) { return d.x }))
.rangeBands(xRange || [0, availableWidth], .1);
y .domain(yDomain || d3.extent(d3.merge(seriesData).map(function(d) { return d.y }).concat(forceY)));
// If showValues, pad the Y axis range to account for label height
if (showValues) y.range(yRange || [availableHeight - (y.domain()[0] < 0 ? 12 : 0), y.domain()[1] > 0 ? 12 : 0]);
else y.range(yRange || [availableHeight, 0]);
//store old scales if they exist
x0 = x0 || x;
y0 = y0 || y.copy().range([y(0),y(0)]);
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-discretebar').data([data]);
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-discretebar');
var gEnter = wrapEnter.append('g');
var g = wrap.select('g');
gEnter.append('g').attr('class', 'nv-groups');
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
//TODO: by definition, the discrete bar should not have multiple groups, will modify/remove later
var groups = wrap.select('.nv-groups').selectAll('.nv-group')
.data(function(d) { return d }, function(d) { return d.key });
groups.enter().append('g')
.style('stroke-opacity', 1e-6)
.style('fill-opacity', 1e-6);
groups.exit()
.watchTransition(renderWatch, 'discreteBar: exit groups')
.style('stroke-opacity', 1e-6)
.style('fill-opacity', 1e-6)
.remove();
groups
.attr('class', function(d,i) { return 'nv-group nv-series-' + i })
.classed('hover', function(d) { return d.hover });
groups
.watchTransition(renderWatch, 'discreteBar: groups')
.style('stroke-opacity', 1)
.style('fill-opacity', .75);
var bars = groups.selectAll('g.nv-bar')
.data(function(d) { return d.values });
bars.exit().remove();
var barsEnter = bars.enter().append('g')
.attr('transform', function(d,i,j) {
return 'translate(' + (x(getX(d,i)) + x.rangeBand() * .05 ) + ', ' + y(0) + ')'
})
.on('mouseover', function(d,i) { //TODO: figure out why j works above, but not here
d3.select(this).classed('hover', true);
dispatch.elementMouseover({
data: d,
index: i,
color: d3.select(this).style("fill")
});
})
.on('mouseout', function(d,i) {
d3.select(this).classed('hover', false);
dispatch.elementMouseout({
data: d,
index: i,
color: d3.select(this).style("fill")
});
})
.on('mousemove', function(d,i) {
dispatch.elementMousemove({
data: d,
index: i,
color: d3.select(this).style("fill")
});
})
.on('click', function(d,i) {
var element = this;
dispatch.elementClick({
data: d,
index: i,
color: d3.select(this).style("fill"),
event: d3.event,
element: element
});
d3.event.stopPropagation();
})
.on('dblclick', function(d,i) {
dispatch.elementDblClick({
data: d,
index: i,
color: d3.select(this).style("fill")
});
d3.event.stopPropagation();
});
barsEnter.append('rect')
.attr('height', 0)
.attr('width', x.rangeBand() * .9 / data.length )
if (showValues) {
barsEnter.append('text')
.attr('text-anchor', 'middle')
;
bars.select('text')
.text(function(d,i) { return valueFormat(getY(d,i)) })
.watchTransition(renderWatch, 'discreteBar: bars text')
.attr('x', x.rangeBand() * .9 / 2)
.attr('y', function(d,i) { return getY(d,i) < 0 ? y(getY(d,i)) - y(0) + 12 : -4 })
;
} else {
bars.selectAll('text').remove();
}
bars
.attr('class', function(d,i) { return getY(d,i) < 0 ? 'nv-bar negative' : 'nv-bar positive' })
.style('fill', function(d,i) { return d.color || color(d,i) })
.style('stroke', function(d,i) { return d.color || color(d,i) })
.select('rect')
.attr('class', rectClass)
.watchTransition(renderWatch, 'discreteBar: bars rect')
.attr('width', x.rangeBand() * .9 / data.length);
bars.watchTransition(renderWatch, 'discreteBar: bars')
//.delay(function(d,i) { return i * 1200 / data[0].values.length })
.attr('transform', function(d,i) {
var left = x(getX(d,i)) + x.rangeBand() * .05,
top = getY(d,i) < 0 ?
y(0) :
y(0) - y(getY(d,i)) < 1 ?
y(0) - 1 : //make 1 px positive bars show up above y=0
y(getY(d,i));
return 'translate(' + left + ', ' + top + ')'
})
.select('rect')
.attr('height', function(d,i) {
return Math.max(Math.abs(y(getY(d,i)) - y(0)), 1)
});
//store old scales for use in transitions on update
x0 = x.copy();
y0 = y.copy();
});
renderWatch.renderEnd('discreteBar immediate');
return chart;
}
//============================================================
// Expose Public Variables
//------------------------------------------------------------
chart.dispatch = dispatch;
chart.options = nv.utils.optionsFunc.bind(chart);
chart._options = Object.create({}, {
// simple options, just get/set the necessary values
width: {get: function(){return width;}, set: function(_){width=_;}},
height: {get: function(){return height;}, set: function(_){height=_;}},
forceY: {get: function(){return forceY;}, set: function(_){forceY=_;}},
showValues: {get: function(){return showValues;}, set: function(_){showValues=_;}},
x: {get: function(){return getX;}, set: function(_){getX=_;}},
y: {get: function(){return getY;}, set: function(_){getY=_;}},
xScale: {get: function(){return x;}, set: function(_){x=_;}},
yScale: {get: function(){return y;}, set: function(_){y=_;}},
xDomain: {get: function(){return xDomain;}, set: function(_){xDomain=_;}},
yDomain: {get: function(){return yDomain;}, set: function(_){yDomain=_;}},
xRange: {get: function(){return xRange;}, set: function(_){xRange=_;}},
yRange: {get: function(){return yRange;}, set: function(_){yRange=_;}},
valueFormat: {get: function(){return valueFormat;}, set: function(_){valueFormat=_;}},
id: {get: function(){return id;}, set: function(_){id=_;}},
rectClass: {get: function(){return rectClass;}, set: function(_){rectClass=_;}},
// options that require extra logic in the setter
margin: {get: function(){return margin;}, set: function(_){
margin.top = _.top !== undefined ? _.top : margin.top;
margin.right = _.right !== undefined ? _.right : margin.right;
margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
margin.left = _.left !== undefined ? _.left : margin.left;
}},
color: {get: function(){return color;}, set: function(_){
color = nv.utils.getColor(_);
}},
duration: {get: function(){return duration;}, set: function(_){
duration = _;
renderWatch.reset(duration);
}}
});
nv.utils.initOptions(chart);
return chart;
};
nv.models.discreteBarChart = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var discretebar = nv.models.discreteBar()
, xAxis = nv.models.axis()
, yAxis = nv.models.axis()
, legend = nv.models.legend()
, tooltip = nv.models.tooltip()
;
var margin = {top: 15, right: 10, bottom: 50, left: 60}
, width = null
, height = null
, color = nv.utils.getColor()
, showLegend = false
, showXAxis = true
, showYAxis = true
, rightAlignYAxis = false
, staggerLabels = false
, wrapLabels = false
, rotateLabels = 0
, x
, y
, noData = null
, dispatch = d3.dispatch('beforeUpdate','renderEnd')
, duration = 250
;
xAxis
.orient('bottom')
.showMaxMin(false)
.tickFormat(function(d) { return d })
;
yAxis
.orient((rightAlignYAxis) ? 'right' : 'left')
.tickFormat(d3.format(',.1f'))
;
tooltip
.duration(0)
.headerEnabled(false)
.valueFormatter(function(d, i) {
return yAxis.tickFormat()(d, i);
})
.keyFormatter(function(d, i) {
return xAxis.tickFormat()(d, i);
});
//============================================================
// Private Variables
//------------------------------------------------------------
var renderWatch = nv.utils.renderWatch(dispatch, duration);
function chart(selection) {
renderWatch.reset();
renderWatch.models(discretebar);
if (showXAxis) renderWatch.models(xAxis);
if (showYAxis) renderWatch.models(yAxis);
selection.each(function(data) {
var container = d3.select(this),
that = this;
nv.utils.initSVG(container);
var availableWidth = nv.utils.availableWidth(width, container, margin),
availableHeight = nv.utils.availableHeight(height, container, margin);
chart.update = function() {
dispatch.beforeUpdate();
container.transition().duration(duration).call(chart);
};
chart.container = this;
// Display No Data message if there's nothing to show.
if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) {
nv.utils.noData(chart, container);
return chart;
} else {
container.selectAll('.nv-noData').remove();
}
// Setup Scales
x = discretebar.xScale();
y = discretebar.yScale().clamp(true);
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-discreteBarWithAxes').data([data]);
var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-discreteBarWithAxes').append('g');
var defsEnter = gEnter.append('defs');
var g = wrap.select('g');
gEnter.append('g').attr('class', 'nv-x nv-axis');
gEnter.append('g').attr('class', 'nv-y nv-axis')
.append('g').attr('class', 'nv-zeroLine')
.append('line');
gEnter.append('g').attr('class', 'nv-barsWrap');
gEnter.append('g').attr('class', 'nv-legendWrap');
g.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
// Legend
if (!showLegend) {
g.select('.nv-legendWrap').selectAll('*').remove();
} else {
legend.width(availableWidth);
g.select('.nv-legendWrap')
.datum(data)
.call(legend);
if ( margin.top != legend.height()) {
margin.top = legend.height();
availableHeight = nv.utils.availableHeight(height, container, margin);
}
wrap.select('.nv-legendWrap')
.attr('transform', 'translate(0,' + (-margin.top) +')')
}
if (rightAlignYAxis) {
g.select(".nv-y.nv-axis")
.attr("transform", "translate(" + availableWidth + ",0)");
}
// Main Chart Component(s)
discretebar
.width(availableWidth)
.height(availableHeight);
var barsWrap = g.select('.nv-barsWrap')
.datum(data.filter(function(d) { return !d.disabled }));
barsWrap.transition().call(discretebar);
defsEnter.append('clipPath')
.attr('id', 'nv-x-label-clip-' + discretebar.id())
.append('rect');
g.select('#nv-x-label-clip-' + discretebar.id() + ' rect')
.attr('width', x.rangeBand() * (staggerLabels ? 2 : 1))
.attr('height', 16)
.attr('x', -x.rangeBand() / (staggerLabels ? 1 : 2 ));
// Setup Axes
if (showXAxis) {
xAxis
.scale(x)
._ticks( nv.utils.calcTicksX(availableWidth/100, data) )
.tickSize(-availableHeight, 0);
g.select('.nv-x.nv-axis')
.attr('transform', 'translate(0,' + (y.range()[0] + ((discretebar.showValues() && y.domain()[0] < 0) ? 16 : 0)) + ')');
g.select('.nv-x.nv-axis').call(xAxis);
var xTicks = g.select('.nv-x.nv-axis').selectAll('g');
if (staggerLabels) {
xTicks
.selectAll('text')
.attr('transform', function(d,i,j) { return 'translate(0,' + (j % 2 == 0 ? '5' : '17') + ')' })
}
if (rotateLabels) {
xTicks
.selectAll('.tick text')
.attr('transform', 'rotate(' + rotateLabels + ' 0,0)')
.style('text-anchor', rotateLabels > 0 ? 'start' : 'end');
}
if (wrapLabels) {
g.selectAll('.tick text')
.call(nv.utils.wrapTicks, chart.xAxis.rangeBand())
}
}
if (showYAxis) {
yAxis
.scale(y)
._ticks( nv.utils.calcTicksY(availableHeight/36, data) )
.tickSize( -availableWidth, 0);
g.select('.nv-y.nv-axis').call(yAxis);
}
// Zero line
g.select(".nv-zeroLine line")
.attr("x1",0)
.attr("x2",(rightAlignYAxis) ? -availableWidth : availableWidth)
.attr("y1", y(0))
.attr("y2", y(0))
;
});
renderWatch.renderEnd('discreteBar chart immediate');
return chart;
}
//============================================================
// Event Handling/Dispatching (out of chart's scope)
//------------------------------------------------------------
discretebar.dispatch.on('elementMouseover.tooltip', function(evt) {
evt['series'] = {
key: chart.x()(evt.data),
value: chart.y()(evt.data),
color: evt.color
};
tooltip.data(evt).hidden(false);
});
discretebar.dispatch.on('elementMouseout.tooltip', function(evt) {
tooltip.hidden(true);
});
discretebar.dispatch.on('elementMousemove.tooltip', function(evt) {
tooltip();
});
//============================================================
// Expose Public Variables
//------------------------------------------------------------
chart.dispatch = dispatch;
chart.discretebar = discretebar;
chart.legend = legend;
chart.xAxis = xAxis;
chart.yAxis = yAxis;
chart.tooltip = tooltip;
chart.options = nv.utils.optionsFunc.bind(chart);
chart._options = Object.create({}, {
// simple options, just get/set the necessary values
width: {get: function(){return width;}, set: function(_){width=_;}},
height: {get: function(){return height;}, set: function(_){height=_;}},
showLegend: {get: function(){return showLegend;}, set: function(_){showLegend=_;}},
staggerLabels: {get: function(){return staggerLabels;}, set: function(_){staggerLabels=_;}},
rotateLabels: {get: function(){return rotateLabels;}, set: function(_){rotateLabels=_;}},
wrapLabels: {get: function(){return wrapLabels;}, set: function(_){wrapLabels=!!_;}},
showXAxis: {get: function(){return showXAxis;}, set: function(_){showXAxis=_;}},
showYAxis: {get: function(){return showYAxis;}, set: function(_){showYAxis=_;}},
noData: {get: function(){return noData;}, set: function(_){noData=_;}},
// options that require extra logic in the setter
margin: {get: function(){return margin;}, set: function(_){
margin.top = _.top !== undefined ? _.top : margin.top;
margin.right = _.right !== undefined ? _.right : margin.right;
margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
margin.left = _.left !== undefined ? _.left : margin.left;
}},
duration: {get: function(){return duration;}, set: function(_){
duration = _;
renderWatch.reset(duration);
discretebar.duration(duration);
xAxis.duration(duration);
yAxis.duration(duration);
}},
color: {get: function(){return color;}, set: function(_){
color = nv.utils.getColor(_);
discretebar.color(color);
legend.color(color);
}},
rightAlignYAxis: {get: function(){return rightAlignYAxis;}, set: function(_){
rightAlignYAxis = _;
yAxis.orient( (_) ? 'right' : 'left');
}}
});
nv.utils.inheritOptions(chart, discretebar);
nv.utils.initOptions(chart);
return chart;
}
nv.models.distribution = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var margin = {top: 0, right: 0, bottom: 0, left: 0}
, width = 400 //technically width or height depending on x or y....
, size = 8
, axis = 'x' // 'x' or 'y'... horizontal or vertical
, getData = function(d) { return d[axis] } // defaults d.x or d.y
, color = nv.utils.defaultColor()
, scale = d3.scale.linear()
, domain
, duration = 250
, dispatch = d3.dispatch('renderEnd')
;
//============================================================
//============================================================
// Private Variables
//------------------------------------------------------------
var scale0;
var renderWatch = nv.utils.renderWatch(dispatch, duration);
//============================================================
function chart(selection) {
renderWatch.reset();
selection.each(function(data) {
var availableLength = width - (axis === 'x' ? margin.left + margin.right : margin.top + margin.bottom),
naxis = axis == 'x' ? 'y' : 'x',
container = d3.select(this);
nv.utils.initSVG(container);
//------------------------------------------------------------
// Setup Scales
scale0 = scale0 || scale;
//------------------------------------------------------------
//------------------------------------------------------------
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-distribution').data([data]);
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-distribution');
var gEnter = wrapEnter.append('g');
var g = wrap.select('g');
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')
//------------------------------------------------------------
var distWrap = g.selectAll('g.nv-dist')
.data(function(d) { return d }, function(d) { return d.key });
distWrap.enter().append('g');
distWrap
.attr('class', function(d,i) { return 'nv-dist nv-series-' + i })
.style('stroke', function(d,i) { return color(d, i) });
var dist = distWrap.selectAll('line.nv-dist' + axis)
.data(function(d) { return d.values })
dist.enter().append('line')
.attr(axis + '1', function(d,i) { return scale0(getData(d,i)) })
.attr(axis + '2', function(d,i) { return scale0(getData(d,i)) })
renderWatch.transition(distWrap.exit().selectAll('line.nv-dist' + axis), 'dist exit')
// .transition()
.attr(axis + '1', function(d,i) { return scale(getData(d,i)) })
.attr(axis + '2', function(d,i) { return scale(getData(d,i)) })
.style('stroke-opacity', 0)
.remove();
dist
.attr('class', function(d,i) { return 'nv-dist' + axis + ' nv-dist' + axis + '-' + i })
.attr(naxis + '1', 0)
.attr(naxis + '2', size);
renderWatch.transition(dist, 'dist')
// .transition()
.attr(axis + '1', function(d,i) { return scale(getData(d,i)) })
.attr(axis + '2', function(d,i) { return scale(getData(d,i)) })
scale0 = scale.copy();
});
renderWatch.renderEnd('distribution immediate');
return chart;
}
//============================================================
// Expose Public Variables
//------------------------------------------------------------
chart.options = nv.utils.optionsFunc.bind(chart);
chart.dispatch = dispatch;
chart.margin = function(_) {
if (!arguments.length) return margin;
margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
return chart;
};
chart.width = function(_) {
if (!arguments.length) return width;
width = _;
return chart;
};
chart.axis = function(_) {
if (!arguments.length) return axis;
axis = _;
return chart;
};
chart.size = function(_) {
if (!arguments.length) return size;
size = _;
return chart;
};
chart.getData = function(_) {
if (!arguments.length) return getData;
getData = d3.functor(_);
return chart;
};
chart.scale = function(_) {
if (!arguments.length) return scale;
scale = _;
return chart;
};
chart.color = function(_) {
if (!arguments.length) return color;
color = nv.utils.getColor(_);
return chart;
};
chart.duration = function(_) {
if (!arguments.length) return duration;
duration = _;
renderWatch.reset(duration);
return chart;
};
//============================================================
return chart;
}
nv.models.focus = function(content) {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var content = content || nv.models.line()
, xAxis = nv.models.axis()
, yAxis = nv.models.axis()
, brush = d3.svg.brush()
;
var margin = {top: 10, right: 0, bottom: 30, left: 0}
, color = nv.utils.defaultColor()
, width = null
, height = 70
, showXAxis = true
, showYAxis = false
, rightAlignYAxis = false
, ticks = null
, x
, y
, brushExtent = null
, duration = 250
, dispatch = d3.dispatch('brush', 'onBrush', 'renderEnd')
;
content.interactive(false);
content.pointActive(function(d) { return false; });
//============================================================
// Private Variables
//------------------------------------------------------------
var renderWatch = nv.utils.renderWatch(dispatch, duration);
function chart(selection) {
renderWatch.reset();
renderWatch.models(content);
if (showXAxis) renderWatch.models(xAxis);
if (showYAxis) renderWatch.models(yAxis);
selection.each(function(data) {
var container = d3.select(this);
nv.utils.initSVG(container);
var availableWidth = nv.utils.availableWidth(width, container, margin),
availableHeight = height - margin.top - margin.bottom;
chart.update = function() {
if( duration === 0 ) {
container.call( chart );
} else {
container.transition().duration(duration).call(chart);
}
};
chart.container = this;
// Setup Scales
x = content.xScale();
y = content.yScale();
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-focus').data([data]);
var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-focus').append('g');
var g = wrap.select('g');
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
gEnter.append('g').attr('class', 'nv-background').append('rect');
gEnter.append('g').attr('class', 'nv-x nv-axis');
gEnter.append('g').attr('class', 'nv-y nv-axis');
gEnter.append('g').attr('class', 'nv-contentWrap');
gEnter.append('g').attr('class', 'nv-brushBackground');
gEnter.append('g').attr('class', 'nv-x nv-brush');
if (rightAlignYAxis) {
g.select(".nv-y.nv-axis")
.attr("transform", "translate(" + availableWidth + ",0)");
}
g.select('.nv-background rect')
.attr('width', availableWidth)
.attr('height', availableHeight);
content
.width(availableWidth)
.height(availableHeight)
.color(data.map(function(d,i) {
return d.color || color(d, i);
}).filter(function(d,i) { return !data[i].disabled; }));
var contentWrap = g.select('.nv-contentWrap')
.datum(data.filter(function(d) { return !d.disabled; }));
d3.transition(contentWrap).call(content);
// Setup Brush
brush
.x(x)
.on('brush', function() {
onBrush();
});
if (brushExtent) brush.extent(brushExtent);
var brushBG = g.select('.nv-brushBackground').selectAll('g')
.data([brushExtent || brush.extent()]);
var brushBGenter = brushBG.enter()
.append('g');
brushBGenter.append('rect')
.attr('class', 'left')
.attr('x', 0)
.attr('y', 0)
.attr('height', availableHeight);
brushBGenter.append('rect')
.attr('class', 'right')
.attr('x', 0)
.attr('y', 0)
.attr('height', availableHeight);
var gBrush = g.select('.nv-x.nv-brush')
.call(brush);
gBrush.selectAll('rect')
.attr('height', availableHeight);
gBrush.selectAll('.resize').append('path').attr('d', resizePath);
onBrush();
g.select('.nv-background rect')
.attr('width', availableWidth)
.attr('height', availableHeight);
if (showXAxis) {
xAxis.scale(x)
._ticks( nv.utils.calcTicksX(availableWidth/100, data) )
.tickSize(-availableHeight, 0);
g.select('.nv-x.nv-axis')
.attr('transform', 'translate(0,' + y.range()[0] + ')');
d3.transition(g.select('.nv-x.nv-axis'))
.call(xAxis);
}
if (showYAxis) {
yAxis
.scale(y)
._ticks( nv.utils.calcTicksY(availableHeight/36, data) )
.tickSize( -availableWidth, 0);
d3.transition(g.select('.nv-y.nv-axis'))
.call(yAxis);
}
g.select('.nv-x.nv-axis')
.attr('transform', 'translate(0,' + y.range()[0] + ')');
//============================================================
// Event Handling/Dispatching (in chart's scope)
//------------------------------------------------------------
//============================================================
// Functions
//------------------------------------------------------------
// Taken from crossfilter (http://square.github.com/crossfilter/)
function resizePath(d) {
var e = +(d == 'e'),
x = e ? 1 : -1,
y = availableHeight / 3;
return 'M' + (0.5 * x) + ',' + y
+ 'A6,6 0 0 ' + e + ' ' + (6.5 * x) + ',' + (y + 6)
+ 'V' + (2 * y - 6)
+ 'A6,6 0 0 ' + e + ' ' + (0.5 * x) + ',' + (2 * y)
+ 'Z'
+ 'M' + (2.5 * x) + ',' + (y + 8)
+ 'V' + (2 * y - 8)
+ 'M' + (4.5 * x) + ',' + (y + 8)
+ 'V' + (2 * y - 8);
}
function updateBrushBG() {
if (!brush.empty()) brush.extent(brushExtent);
brushBG
.data([brush.empty() ? x.domain() : brushExtent])
.each(function(d,i) {
var leftWidth = x(d[0]) - x.range()[0],
rightWidth = availableWidth - x(d[1]);
d3.select(this).select('.left')
.attr('width', leftWidth < 0 ? 0 : leftWidth);
d3.select(this).select('.right')
.attr('x', x(d[1]))
.attr('width', rightWidth < 0 ? 0 : rightWidth);
});
}
function onBrush() {
brushExtent = brush.empty() ? null : brush.extent();
var extent = brush.empty() ? x.domain() : brush.extent();
//The brush extent cannot be less than one. If it is, don't update the line chart.
if (Math.abs(extent[0] - extent[1]) <= 1) {
return;
}
dispatch.brush({extent: extent, brush: brush});
updateBrushBG();
dispatch.onBrush(extent);
}
});
renderWatch.renderEnd('focus immediate');
return chart;
}
//============================================================
// Event Handling/Dispatching (out of chart's scope)
//------------------------------------------------------------
//============================================================
// Expose Public Variables
//------------------------------------------------------------
// expose chart's sub-components
chart.dispatch = dispatch;
chart.content = content;
chart.brush = brush;
chart.xAxis = xAxis;
chart.yAxis = yAxis;
chart.options = nv.utils.optionsFunc.bind(chart);
chart._options = Object.create({}, {
// simple options, just get/set the necessary values
width: {get: function(){return width;}, set: function(_){width=_;}},
height: {get: function(){return height;}, set: function(_){height=_;}},
showXAxis: {get: function(){return showXAxis;}, set: function(_){showXAxis=_;}},
showYAxis: {get: function(){return showYAxis;}, set: function(_){showYAxis=_;}},
brushExtent: {get: function(){return brushExtent;}, set: function(_){brushExtent=_;}},
// options that require extra logic in the setter
margin: {get: function(){return margin;}, set: function(_){
margin.top = _.top !== undefined ? _.top : margin.top;
margin.right = _.right !== undefined ? _.right : margin.right;
margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
margin.left = _.left !== undefined ? _.left : margin.left;
}},
duration: {get: function(){return duration;}, set: function(_){
duration = _;
renderWatch.reset(duration);
content.duration(duration);
xAxis.duration(duration);
yAxis.duration(duration);
}},
color: {get: function(){return color;}, set: function(_){
color = nv.utils.getColor(_);
content.color(color);
}},
interpolate: {get: function(){return content.interpolate();}, set: function(_){
content.interpolate(_);
}},
xTickFormat: {get: function(){return xAxis.tickFormat();}, set: function(_){
xAxis.tickFormat(_);
}},
yTickFormat: {get: function(){return yAxis.tickFormat();}, set: function(_){
yAxis.tickFormat(_);
}},
x: {get: function(){return content.x();}, set: function(_){
content.x(_);
}},
y: {get: function(){return content.y();}, set: function(_){
content.y(_);
}},
rightAlignYAxis: {get: function(){return rightAlignYAxis;}, set: function(_){
rightAlignYAxis = _;
yAxis.orient( rightAlignYAxis ? 'right' : 'left');
}},
});
nv.utils.inheritOptions(chart, content);
nv.utils.initOptions(chart);
return chart;
};
nv.models.forceDirectedGraph = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var margin = {top: 2, right: 0, bottom: 2, left: 0}
, width = 400
, height = 32
, container = null
, dispatch = d3.dispatch('renderEnd')
, color = nv.utils.getColor(['#000'])
, tooltip = nv.models.tooltip()
, noData = null
// Force directed graph specific parameters [default values]
, linkStrength = 0.1
, friction = 0.9
, linkDist = 30
, charge = -120
, gravity = 0.1
, theta = 0.8
, alpha = 0.1
, radius = 5
// These functions allow to add extra attributes to ndes and links
,nodeExtras = function(nodes) { /* Do nothing */ }
,linkExtras = function(links) { /* Do nothing */ }
;
//============================================================
// Private Variables
//------------------------------------------------------------
var renderWatch = nv.utils.renderWatch(dispatch);
function chart(selection) {
renderWatch.reset();
selection.each(function(data) {
container = d3.select(this);
nv.utils.initSVG(container);
var availableWidth = nv.utils.availableWidth(width, container, margin),
availableHeight = nv.utils.availableHeight(height, container, margin);
container
.attr("width", availableWidth)
.attr("height", availableHeight);
// Display No Data message if there's nothing to show.
if (!data || !data.links || !data.nodes) {
nv.utils.noData(chart, container)
return chart;
} else {
container.selectAll('.nv-noData').remove();
}
container.selectAll('*').remove();
// Collect names of all fields in the nodes
var nodeFieldSet = new Set();
data.nodes.forEach(function(node) {
var keys = Object.keys(node);
keys.forEach(function(key) {
nodeFieldSet.add(key);
});
});
var force = d3.layout.force()
.nodes(data.nodes)
.links(data.links)
.size([availableWidth, availableHeight])
.linkStrength(linkStrength)
.friction(friction)
.linkDistance(linkDist)
.charge(charge)
.gravity(gravity)
.theta(theta)
.alpha(alpha)
.start();
var link = container.selectAll(".link")
.data(data.links)
.enter().append("line")
.attr("class", "nv-force-link")
.style("stroke-width", function(d) { return Math.sqrt(d.value); });
var node = container.selectAll(".node")
.data(data.nodes)
.enter()
.append("g")
.attr("class", "nv-force-node")
.call(force.drag);
node
.append("circle")
.attr("r", radius)
.style("fill", function(d) { return color(d) } )
.on("mouseover", function(evt) {
container.select('.nv-series-' + evt.seriesIndex + ' .nv-distx-' + evt.pointIndex)
.attr('y1', evt.py);
container.select('.nv-series-' + evt.seriesIndex + ' .nv-disty-' + evt.pointIndex)
.attr('x2', evt.px);
// Add 'series' object to
var nodeColor = color(evt);
evt.series = [];
nodeFieldSet.forEach(function(field) {
evt.series.push({
color: nodeColor,
key: field,
value: evt[field]
});
});
tooltip.data(evt).hidden(false);
})
.on("mouseout", function(d) {
tooltip.hidden(true);
});
tooltip.headerFormatter(function(d) {return "Node";});
// Apply extra attributes to nodes and links (if any)
linkExtras(link);
nodeExtras(node);
force.on("tick", function() {
link.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
node.attr("transform", function(d) {
return "translate(" + d.x + ", " + d.y + ")";
});
});
});
return chart;
}
//============================================================
// Expose Public Variables
//------------------------------------------------------------
chart.options = nv.utils.optionsFunc.bind(chart);
chart._options = Object.create({}, {
// simple options, just get/set the necessary values
width: {get: function(){return width;}, set: function(_){width=_;}},
height: {get: function(){return height;}, set: function(_){height=_;}},
// Force directed graph specific parameters
linkStrength:{get: function(){return linkStrength;}, set: function(_){linkStrength=_;}},
friction: {get: function(){return friction;}, set: function(_){friction=_;}},
linkDist: {get: function(){return linkDist;}, set: function(_){linkDist=_;}},
charge: {get: function(){return charge;}, set: function(_){charge=_;}},
gravity: {get: function(){return gravity;}, set: function(_){gravity=_;}},
theta: {get: function(){return theta;}, set: function(_){theta=_;}},
alpha: {get: function(){return alpha;}, set: function(_){alpha=_;}},
radius: {get: function(){return radius;}, set: function(_){radius=_;}},
//functor options
x: {get: function(){return getX;}, set: function(_){getX=d3.functor(_);}},
y: {get: function(){return getY;}, set: function(_){getY=d3.functor(_);}},
// options that require extra logic in the setter
margin: {get: function(){return margin;}, set: function(_){
margin.top = _.top !== undefined ? _.top : margin.top;
margin.right = _.right !== undefined ? _.right : margin.right;
margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
margin.left = _.left !== undefined ? _.left : margin.left;
}},
color: {get: function(){return color;}, set: function(_){
color = nv.utils.getColor(_);
}},
noData: {get: function(){return noData;}, set: function(_){noData=_;}},
nodeExtras: {get: function(){return nodeExtras;}, set: function(_){
nodeExtras = _;
}},
linkExtras: {get: function(){return linkExtras;}, set: function(_){
linkExtras = _;
}}
});
chart.dispatch = dispatch;
chart.tooltip = tooltip;
nv.utils.initOptions(chart);
return chart;
};
nv.models.furiousLegend = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var margin = {top: 5, right: 0, bottom: 5, left: 0}
, width = 400
, height = 20
, getKey = function(d) { return d.key }
, color = nv.utils.getColor()
, maxKeyLength = 20 //default value for key lengths
, align = true
, padding = 28 //define how much space between legend items. - recommend 32 for furious version
, rightAlign = true
, updateState = true //If true, legend will update data.disabled and trigger a 'stateChange' dispatch.
, radioButtonMode = false //If true, clicking legend items will cause it to behave like a radio button. (only one can be selected at a time)
, expanded = false
, dispatch = d3.dispatch('legendClick', 'legendDblclick', 'legendMouseover', 'legendMouseout', 'stateChange')
, vers = 'classic' //Options are "classic" and "furious"
;
function chart(selection) {
selection.each(function(data) {
var availableWidth = width - margin.left - margin.right,
container = d3.select(this);
nv.utils.initSVG(container);
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-legend').data([data]);
var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-legend').append('g');
var g = wrap.select('g');
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
var series = g.selectAll('.nv-series')
.data(function(d) {
if(vers != 'furious') return d;
return d.filter(function(n) {
return expanded ? true : !n.disengaged;
});
});
var seriesEnter = series.enter().append('g').attr('class', 'nv-series')
var seriesShape;
if(vers == 'classic') {
seriesEnter.append('circle')
.style('stroke-width', 2)
.attr('class','nv-legend-symbol')
.attr('r', 5);
seriesShape = series.select('circle');
} else if (vers == 'furious') {
seriesEnter.append('rect')
.style('stroke-width', 2)
.attr('class','nv-legend-symbol')
.attr('rx', 3)
.attr('ry', 3);
seriesShape = series.select('rect');
seriesEnter.append('g')
.attr('class', 'nv-check-box')
.property('innerHTML','<path d="M0.5,5 L22.5,5 L22.5,26.5 L0.5,26.5 L0.5,5 Z" class="nv-box"></path><path d="M5.5,12.8618467 L11.9185089,19.2803556 L31,0.198864511" class="nv-check"></path>')
.attr('transform', 'translate(-10,-8)scale(0.5)');
var seriesCheckbox = series.select('.nv-check-box');
seriesCheckbox.each(function(d,i) {
d3.select(this).selectAll('path')
.attr('stroke', setTextColor(d,i));
});
}
seriesEnter.append('text')
.attr('text-anchor', 'start')
.attr('class','nv-legend-text')
.attr('dy', '.32em')
.attr('dx', '8');
var seriesText = series.select('text.nv-legend-text');
series
.on('mouseover', function(d,i) {
dispatch.legendMouseover(d,i); //TODO: Make consistent with other event objects
})
.on('mouseout', function(d,i) {
dispatch.legendMouseout(d,i);
})
.on('click', function(d,i) {
dispatch.legendClick(d,i);
// make sure we re-get data in case it was modified
var data = series.data();
if (updateState) {
if(vers =='classic') {
if (radioButtonMode) {
//Radio button mode: set every series to disabled,
// and enable the clicked series.
data.forEach(function(series) { series.disabled = true});
d.disabled = false;
}
else {
d.disabled = !d.disabled;
if (data.every(function(series) { return series.disabled})) {
//the default behavior of NVD3 legends is, if every single series
// is disabled, turn all series' back on.
data.forEach(function(series) { series.disabled = false});
}
}
} else if(vers == 'furious') {
if(expanded) {
d.disengaged = !d.disengaged;
d.userDisabled = d.userDisabled == undefined ? !!d.disabled : d.userDisabled;
d.disabled = d.disengaged || d.userDisabled;
} else if (!expanded) {
d.disabled = !d.disabled;
d.userDisabled = d.disabled;
var engaged = data.filter(function(d) { return !d.disengaged; });
if (engaged.every(function(series) { return series.userDisabled })) {
//the default behavior of NVD3 legends is, if every single series
// is disabled, turn all series' back on.
data.forEach(function(series) {
series.disabled = series.userDisabled = false;
});
}
}
}
dispatch.stateChange({
disabled: data.map(function(d) { return !!d.disabled }),
disengaged: data.map(function(d) { return !!d.disengaged })
});
}
})
.on('dblclick', function(d,i) {
if(vers == 'furious' && expanded) return;
dispatch.legendDblclick(d,i);
if (updateState) {
// make sure we re-get data in case it was modified
var data = series.data();
//the default behavior of NVD3 legends, when double clicking one,
// is to set all other series' to false, and make the double clicked series enabled.
data.forEach(function(series) {
series.disabled = true;
if(vers == 'furious') series.userDisabled = series.disabled;
});
d.disabled = false;
if(vers == 'furious') d.userDisabled = d.disabled;
dispatch.stateChange({
disabled: data.map(function(d) { return !!d.disabled })
});
}
});
series.classed('nv-disabled', function(d) { return d.userDisabled });
series.exit().remove();
seriesText
.attr('fill', setTextColor)
.text(getKey);
//TODO: implement fixed-width and max-width options (max-width is especially useful with the align option)
// NEW ALIGNING CODE, TODO: clean up
var versPadding;
switch(vers) {
case 'furious' :
versPadding = 23;
break;
case 'classic' :
versPadding = 20;
}
if (align) {
var seriesWidths = [];
series.each(function(d,i) {
var legendText;
if (getKey(d) && (getKey(d).length > maxKeyLength)) {
var trimmedKey = getKey(d).substring(0, maxKeyLength);
legendText = d3.select(this).select('text').text(trimmedKey + "...");
d3.select(this).append("svg:title").text(getKey(d));
} else {
legendText = d3.select(this).select('text');
}
var nodeTextLength;
try {
nodeTextLength = legendText.node().getComputedTextLength();
// If the legendText is display:none'd (nodeTextLength == 0), simulate an error so we approximate, instead
if(nodeTextLength <= 0) throw Error();
}
catch(e) {
nodeTextLength = nv.utils.calcApproxTextWidth(legendText);
}
seriesWidths.push(nodeTextLength + padding);
});
var seriesPerRow = 0;
var legendWidth = 0;
var columnWidths = [];
while ( legendWidth < availableWidth && seriesPerRow < seriesWidths.length) {
columnWidths[seriesPerRow] = seriesWidths[seriesPerRow];
legendWidth += seriesWidths[seriesPerRow++];
}
if (seriesPerRow === 0) seriesPerRow = 1; //minimum of one series per row
while ( legendWidth > availableWidth && seriesPerRow > 1 ) {
columnWidths = [];
seriesPerRow--;
for (var k = 0; k < seriesWidths.length; k++) {
if (seriesWidths[k] > (columnWidths[k % seriesPerRow] || 0) )
columnWidths[k % seriesPerRow] = seriesWidths[k];
}
legendWidth = columnWidths.reduce(function(prev, cur, index, array) {
return prev + cur;
});
}
var xPositions = [];
for (var i = 0, curX = 0; i < seriesPerRow; i++) {
xPositions[i] = curX;
curX += columnWidths[i];
}
series
.attr('transform', function(d, i) {
return 'translate(' + xPositions[i % seriesPerRow] + ',' + (5 + Math.floor(i / seriesPerRow) * versPadding) + ')';
});
//position legend as far right as possible within the total width
if (rightAlign) {
g.attr('transform', 'translate(' + (width - margin.right - legendWidth) + ',' + margin.top + ')');
}
else {
g.attr('transform', 'translate(0' + ',' + margin.top + ')');
}
height = margin.top + margin.bottom + (Math.ceil(seriesWidths.length / seriesPerRow) * versPadding);
} else {
var ypos = 5,
newxpos = 5,
maxwidth = 0,
xpos;
series
.attr('transform', function(d, i) {
var length = d3.select(this).select('text').node().getComputedTextLength() + padding;
xpos = newxpos;
if (width < margin.left + margin.right + xpos + length) {
newxpos = xpos = 5;
ypos += versPadding;
}
newxpos += length;
if (newxpos > maxwidth) maxwidth = newxpos;
return 'translate(' + xpos + ',' + ypos + ')';
});
//position legend as far right as possible within the total width
g.attr('transform', 'translate(' + (width - margin.right - maxwidth) + ',' + margin.top + ')');
height = margin.top + margin.bottom + ypos + 15;
}
if(vers == 'furious') {
// Size rectangles after text is placed
seriesShape
.attr('width', function(d,i) {
return seriesText[0][i].getComputedTextLength() + 27;
})
.attr('height', 18)
.attr('y', -9)
.attr('x', -15)
}
seriesShape
.style('fill', setBGColor)
.style('stroke', function(d,i) { return d.color || color(d, i) });
});
function setTextColor(d,i) {
if(vers != 'furious') return '#000';
if(expanded) {
return d.disengaged ? color(d,i) : '#fff';
} else if (!expanded) {
return !!d.disabled ? color(d,i) : '#fff';
}
}
function setBGColor(d,i) {
if(expanded && vers == 'furious') {
return d.disengaged ? '#fff' : color(d,i);
} else {
return !!d.disabled ? '#fff' : color(d,i);
}
}
return chart;
}
//============================================================
// Expose Public Variables
//------------------------------------------------------------
chart.dispatch = dispatch;
chart.options = nv.utils.optionsFunc.bind(chart);
chart._options = Object.create({}, {
// simple options, just get/set the necessary values
width: {get: function(){return width;}, set: function(_){width=_;}},
height: {get: function(){return height;}, set: function(_){height=_;}},
key: {get: function(){return getKey;}, set: function(_){getKey=_;}},
align: {get: function(){return align;}, set: function(_){align=_;}},
rightAlign: {get: function(){return rightAlign;}, set: function(_){rightAlign=_;}},
maxKeyLength: {get: function(){return maxKeyLength;}, set: function(_){maxKeyLength=_;}},
padding: {get: function(){return padding;}, set: function(_){padding=_;}},
updateState: {get: function(){return updateState;}, set: function(_){updateState=_;}},
radioButtonMode: {get: function(){return radioButtonMode;}, set: function(_){radioButtonMode=_;}},
expanded: {get: function(){return expanded;}, set: function(_){expanded=_;}},
vers: {get: function(){return vers;}, set: function(_){vers=_;}},
// options that require extra logic in the setter
margin: {get: function(){return margin;}, set: function(_){
margin.top = _.top !== undefined ? _.top : margin.top;
margin.right = _.right !== undefined ? _.right : margin.right;
margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
margin.left = _.left !== undefined ? _.left : margin.left;
}},
color: {get: function(){return color;}, set: function(_){
color = nv.utils.getColor(_);
}}
});
nv.utils.initOptions(chart);
return chart;
};
//TODO: consider deprecating and using multibar with single series for this
nv.models.historicalBar = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var margin = {top: 0, right: 0, bottom: 0, left: 0}
, width = null
, height = null
, id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one
, container = null
, x = d3.scale.linear()
, y = d3.scale.linear()
, getX = function(d) { return d.x }
, getY = function(d) { return d.y }
, forceX = []
, forceY = [0]
, padData = false
, clipEdge = true
, color = nv.utils.defaultColor()
, xDomain
, yDomain
, xRange
, yRange
, dispatch = d3.dispatch('chartClick', 'elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout', 'elementMousemove', 'renderEnd')
, interactive = true
;
var renderWatch = nv.utils.renderWatch(dispatch, 0);
function chart(selection) {
selection.each(function(data) {
renderWatch.reset();
container = d3.select(this);
var availableWidth = nv.utils.availableWidth(width, container, margin),
availableHeight = nv.utils.availableHeight(height, container, margin);
nv.utils.initSVG(container);
// Setup Scales
x.domain(xDomain || d3.extent(data[0].values.map(getX).concat(forceX) ));
if (padData)
x.range(xRange || [availableWidth * .5 / data[0].values.length, availableWidth * (data[0].values.length - .5) / data[0].values.length ]);
else
x.range(xRange || [0, availableWidth]);
y.domain(yDomain || d3.extent(data[0].values.map(getY).concat(forceY) ))
.range(yRange || [availableHeight, 0]);
// If scale's domain don't have a range, slightly adjust to make one... so a chart can show a single data point
if (x.domain()[0] === x.domain()[1])
x.domain()[0] ?
x.domain([x.domain()[0] - x.domain()[0] * 0.01, x.domain()[1] + x.domain()[1] * 0.01])
: x.domain([-1,1]);
if (y.domain()[0] === y.domain()[1])
y.domain()[0] ?
y.domain([y.domain()[0] + y.domain()[0] * 0.01, y.domain()[1] - y.domain()[1] * 0.01])
: y.domain([-1,1]);
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-historicalBar-' + id).data([data[0].values]);
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-historicalBar-' + id);
var defsEnter = wrapEnter.append('defs');
var gEnter = wrapEnter.append('g');
var g = wrap.select('g');
gEnter.append('g').attr('class', 'nv-bars');
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
container
.on('click', function(d,i) {
dispatch.chartClick({
data: d,
index: i,
pos: d3.event,
id: id
});
});
defsEnter.append('clipPath')
.attr('id', 'nv-chart-clip-path-' + id)
.append('rect');
wrap.select('#nv-chart-clip-path-' + id + ' rect')
.attr('width', availableWidth)
.attr('height', availableHeight);
g.attr('clip-path', clipEdge ? 'url(#nv-chart-clip-path-' + id + ')' : '');
var bars = wrap.select('.nv-bars').selectAll('.nv-bar')
.data(function(d) { return d }, function(d,i) {return getX(d,i)});
bars.exit().remove();
bars.enter().append('rect')
.attr('x', 0 )
.attr('y', function(d,i) { return nv.utils.NaNtoZero(y(Math.max(0, getY(d,i)))) })
.attr('height', function(d,i) { return nv.utils.NaNtoZero(Math.abs(y(getY(d,i)) - y(0))) })
.attr('transform', function(d,i) { return 'translate(' + (x(getX(d,i)) - availableWidth / data[0].values.length * .45) + ',0)'; })
.on('mouseover', function(d,i) {
if (!interactive) return;
d3.select(this).classed('hover', true);
dispatch.elementMouseover({
data: d,
index: i,
color: d3.select(this).style("fill")
});
})
.on('mouseout', function(d,i) {
if (!interactive) return;
d3.select(this).classed('hover', false);
dispatch.elementMouseout({
data: d,
index: i,
color: d3.select(this).style("fill")
});
})
.on('mousemove', function(d,i) {
if (!interactive) return;
dispatch.elementMousemove({
data: d,
index: i,
color: d3.select(this).style("fill")
});
})
.on('click', function(d,i) {
if (!interactive) return;
dispatch.elementClick({
data: d,
index: i,
color: d3.select(this).style("fill")
});
d3.event.stopPropagation();
})
.on('dblclick', function(d,i) {
if (!interactive) return;
dispatch.elementDblClick({
data: d,
index: i,
color: d3.select(this).style("fill")
});
d3.event.stopPropagation();
});
bars
.attr('fill', function(d,i) { return color(d, i); })
.attr('class', function(d,i,j) { return (getY(d,i) < 0 ? 'nv-bar negative' : 'nv-bar positive') + ' nv-bar-' + j + '-' + i })
.watchTransition(renderWatch, 'bars')
.attr('transform', function(d,i) { return 'translate(' + (x(getX(d,i)) - availableWidth / data[0].values.length * .45) + ',0)'; })
//TODO: better width calculations that don't assume always uniform data spacing;w
.attr('width', (availableWidth / data[0].values.length) * .9 );
bars.watchTransition(renderWatch, 'bars')
.attr('y', function(d,i) {
var rval = getY(d,i) < 0 ?
y(0) :
y(0) - y(getY(d,i)) < 1 ?
y(0) - 1 :
y(getY(d,i));
return nv.utils.NaNtoZero(rval);
})
.attr('height', function(d,i) { return nv.utils.NaNtoZero(Math.max(Math.abs(y(getY(d,i)) - y(0)),1)) });
});
renderWatch.renderEnd('historicalBar immediate');
return chart;
}
//Create methods to allow outside functions to highlight a specific bar.
chart.highlightPoint = function(pointIndex, isHoverOver) {
container
.select(".nv-bars .nv-bar-0-" + pointIndex)
.classed("hover", isHoverOver)
;
};
chart.clearHighlights = function() {
container
.select(".nv-bars .nv-bar.hover")
.classed("hover", false)
;
};
//============================================================
// Expose Public Variables
//------------------------------------------------------------
chart.dispatch = dispatch;
chart.options = nv.utils.optionsFunc.bind(chart);
chart._options = Object.create({}, {
// simple options, just get/set the necessary values
width: {get: function(){return width;}, set: function(_){width=_;}},
height: {get: function(){return height;}, set: function(_){height=_;}},
forceX: {get: function(){return forceX;}, set: function(_){forceX=_;}},
forceY: {get: function(){return forceY;}, set: function(_){forceY=_;}},
padData: {get: function(){return padData;}, set: function(_){padData=_;}},
x: {get: function(){return getX;}, set: function(_){getX=_;}},
y: {get: function(){return getY;}, set: function(_){getY=_;}},
xScale: {get: function(){return x;}, set: function(_){x=_;}},
yScale: {get: function(){return y;}, set: function(_){y=_;}},
xDomain: {get: function(){return xDomain;}, set: function(_){xDomain=_;}},
yDomain: {get: function(){return yDomain;}, set: function(_){yDomain=_;}},
xRange: {get: function(){return xRange;}, set: function(_){xRange=_;}},
yRange: {get: function(){return yRange;}, set: function(_){yRange=_;}},
clipEdge: {get: function(){return clipEdge;}, set: function(_){clipEdge=_;}},
id: {get: function(){return id;}, set: function(_){id=_;}},
interactive: {get: function(){return interactive;}, set: function(_){interactive=_;}},
// options that require extra logic in the setter
margin: {get: function(){return margin;}, set: function(_){
margin.top = _.top !== undefined ? _.top : margin.top;
margin.right = _.right !== undefined ? _.right : margin.right;
margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
margin.left = _.left !== undefined ? _.left : margin.left;
}},
color: {get: function(){return color;}, set: function(_){
color = nv.utils.getColor(_);
}}
});
nv.utils.initOptions(chart);
return chart;
};
nv.models.historicalBarChart = function(bar_model) {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var bars = bar_model || nv.models.historicalBar()
, xAxis = nv.models.axis()
, yAxis = nv.models.axis()
, legend = nv.models.legend()
, interactiveLayer = nv.interactiveGuideline()
, tooltip = nv.models.tooltip()
;
var margin = {top: 30, right: 90, bottom: 50, left: 90}
, color = nv.utils.defaultColor()
, width = null
, height = null
, showLegend = false
, showXAxis = true
, showYAxis = true
, rightAlignYAxis = false
, useInteractiveGuideline = false
, x
, y
, state = {}
, defaultState = null
, noData = null
, dispatch = d3.dispatch('tooltipHide', 'stateChange', 'changeState', 'renderEnd')
, transitionDuration = 250
;
xAxis.orient('bottom').tickPadding(7);
yAxis.orient( (rightAlignYAxis) ? 'right' : 'left');
tooltip
.duration(0)
.headerEnabled(false)
.valueFormatter(function(d, i) {
return yAxis.tickFormat()(d, i);
})
.headerFormatter(function(d, i) {
return xAxis.tickFormat()(d, i);
});
//============================================================
// Private Variables
//------------------------------------------------------------
var renderWatch = nv.utils.renderWatch(dispatch, 0);
function chart(selection) {
selection.each(function(data) {
renderWatch.reset();
renderWatch.models(bars);
if (showXAxis) renderWatch.models(xAxis);
if (showYAxis) renderWatch.models(yAxis);
var container = d3.select(this),
that = this;
nv.utils.initSVG(container);
var availableWidth = nv.utils.availableWidth(width, container, margin),
availableHeight = nv.utils.availableHeight(height, container, margin);
chart.update = function() { container.transition().duration(transitionDuration).call(chart) };
chart.container = this;
//set state.disabled
state.disabled = data.map(function(d) { return !!d.disabled });
if (!defaultState) {
var key;
defaultState = {};
for (key in state) {
if (state[key] instanceof Array)
defaultState[key] = state[key].slice(0);
else
defaultState[key] = state[key];
}
}
// Display noData message if there's nothing to show.
if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) {
nv.utils.noData(chart, container)
return chart;
} else {
container.selectAll('.nv-noData').remove();
}
// Setup Scales
x = bars.xScale();
y = bars.yScale();
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-historicalBarChart').data([data]);
var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-historicalBarChart').append('g');
var g = wrap.select('g');
gEnter.append('g').attr('class', 'nv-x nv-axis');
gEnter.append('g').attr('class', 'nv-y nv-axis');
gEnter.append('g').attr('class', 'nv-barsWrap');
gEnter.append('g').attr('class', 'nv-legendWrap');
gEnter.append('g').attr('class', 'nv-interactive');
// Legend
if (!showLegend) {
g.select('.nv-legendWrap').selectAll('*').remove();
} else {
legend.width(availableWidth);
g.select('.nv-legendWrap')
.datum(data)
.call(legend);
if ( margin.top != legend.height()) {
margin.top = legend.height();
availableHeight = nv.utils.availableHeight(height, container, margin);
}
wrap.select('.nv-legendWrap')
.attr('transform', 'translate(0,' + (-margin.top) +')')
}
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
if (rightAlignYAxis) {
g.select(".nv-y.nv-axis")
.attr("transform", "translate(" + availableWidth + ",0)");
}
//Set up interactive layer
if (useInteractiveGuideline) {
interactiveLayer
.width(availableWidth)
.height(availableHeight)
.margin({left:margin.left, top:margin.top})
.svgContainer(container)
.xScale(x);
wrap.select(".nv-interactive").call(interactiveLayer);
}
bars
.width(availableWidth)
.height(availableHeight)
.color(data.map(function(d,i) {
return d.color || color(d, i);
}).filter(function(d,i) { return !data[i].disabled }));
var barsWrap = g.select('.nv-barsWrap')
.datum(data.filter(function(d) { return !d.disabled }));
barsWrap.transition().call(bars);
// Setup Axes
if (showXAxis) {
xAxis
.scale(x)
._ticks( nv.utils.calcTicksX(availableWidth/100, data) )
.tickSize(-availableHeight, 0);
g.select('.nv-x.nv-axis')
.attr('transform', 'translate(0,' + y.range()[0] + ')');
g.select('.nv-x.nv-axis')
.transition()
.call(xAxis);
}
if (showYAxis) {
yAxis
.scale(y)
._ticks( nv.utils.calcTicksY(availableHeight/36, data) )
.tickSize( -availableWidth, 0);
g.select('.nv-y.nv-axis')
.transition()
.call(yAxis);
}
//============================================================
// Event Handling/Dispatching (in chart's scope)
//------------------------------------------------------------
interactiveLayer.dispatch.on('elementMousemove', function(e) {
bars.clearHighlights();
var singlePoint, pointIndex, pointXLocation, allData = [];
data
.filter(function(series, i) {
series.seriesIndex = i;
return !series.disabled;
})
.forEach(function(series,i) {
pointIndex = nv.interactiveBisect(series.values, e.pointXValue, chart.x());
bars.highlightPoint(pointIndex,true);
var point = series.values[pointIndex];
if (point === undefined) return;
if (singlePoint === undefined) singlePoint = point;
if (pointXLocation === undefined) pointXLocation = chart.xScale()(chart.x()(point,pointIndex));
allData.push({
key: series.key,
value: chart.y()(point, pointIndex),
color: color(series,series.seriesIndex),
data: series.values[pointIndex]
});
});
var xValue = xAxis.tickFormat()(chart.x()(singlePoint,pointIndex));
interactiveLayer.tooltip
.chartContainer(that.parentNode)
.valueFormatter(function(d,i) {
return yAxis.tickFormat()(d);
})
.data({
value: xValue,
index: pointIndex,
series: allData
})();
interactiveLayer.renderGuideLine(pointXLocation);
});
interactiveLayer.dispatch.on("elementMouseout",function(e) {
dispatch.tooltipHide();
bars.clearHighlights();
});
legend.dispatch.on('legendClick', function(d,i) {
d.disabled = !d.disabled;
if (!data.filter(function(d) { return !d.disabled }).length) {
data.map(function(d) {
d.disabled = false;
wrap.selectAll('.nv-series').classed('disabled', false);
return d;
});
}
state.disabled = data.map(function(d) { return !!d.disabled });
dispatch.stateChange(state);
selection.transition().call(chart);
});
legend.dispatch.on('legendDblclick', function(d) {
//Double clicking should always enable current series, and disabled all others.
data.forEach(function(d) {
d.disabled = true;
});
d.disabled = false;
state.disabled = data.map(function(d) { return !!d.disabled });
dispatch.stateChange(state);
chart.update();
});
dispatch.on('changeState', function(e) {
if (typeof e.disabled !== 'undefined') {
data.forEach(function(series,i) {
series.disabled = e.disabled[i];
});
state.disabled = e.disabled;
}
chart.update();
});
});
renderWatch.renderEnd('historicalBarChart immediate');
return chart;
}
//============================================================
// Event Handling/Dispatching (out of chart's scope)
//------------------------------------------------------------
bars.dispatch.on('elementMouseover.tooltip', function(evt) {
evt['series'] = {
key: chart.x()(evt.data),
value: chart.y()(evt.data),
color: evt.color
};
tooltip.data(evt).hidden(false);
});
bars.dispatch.on('elementMouseout.tooltip', function(evt) {
tooltip.hidden(true);
});
bars.dispatch.on('elementMousemove.tooltip', function(evt) {
tooltip();
});
//============================================================
// Expose Public Variables
//------------------------------------------------------------
// expose chart's sub-components
chart.dispatch = dispatch;
chart.bars = bars;
chart.legend = legend;
chart.xAxis = xAxis;
chart.yAxis = yAxis;
chart.interactiveLayer = interactiveLayer;
chart.tooltip = tooltip;
chart.options = nv.utils.optionsFunc.bind(chart);
chart._options = Object.create({}, {
// simple options, just get/set the necessary values
width: {get: function(){return width;}, set: function(_){width=_;}},
height: {get: function(){return height;}, set: function(_){height=_;}},
showLegend: {get: function(){return showLegend;}, set: function(_){showLegend=_;}},
showXAxis: {get: function(){return showXAxis;}, set: function(_){showXAxis=_;}},
showYAxis: {get: function(){return showYAxis;}, set: function(_){showYAxis=_;}},
defaultState: {get: function(){return defaultState;}, set: function(_){defaultState=_;}},
noData: {get: function(){return noData;}, set: function(_){noData=_;}},
// options that require extra logic in the setter
margin: {get: function(){return margin;}, set: function(_){
margin.top = _.top !== undefined ? _.top : margin.top;
margin.right = _.right !== undefined ? _.right : margin.right;
margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
margin.left = _.left !== undefined ? _.left : margin.left;
}},
color: {get: function(){return color;}, set: function(_){
color = nv.utils.getColor(_);
legend.color(color);
bars.color(color);
}},
duration: {get: function(){return transitionDuration;}, set: function(_){
transitionDuration=_;
renderWatch.reset(transitionDuration);
yAxis.duration(transitionDuration);
xAxis.duration(transitionDuration);
}},
rightAlignYAxis: {get: function(){return rightAlignYAxis;}, set: function(_){
rightAlignYAxis = _;
yAxis.orient( (_) ? 'right' : 'left');
}},
useInteractiveGuideline: {get: function(){return useInteractiveGuideline;}, set: function(_){
useInteractiveGuideline = _;
if (_ === true) {
chart.interactive(false);
}
}}
});
nv.utils.inheritOptions(chart, bars);
nv.utils.initOptions(chart);
return chart;
};
// ohlcChart is just a historical chart with ohlc bars and some tweaks
nv.models.ohlcBarChart = function() {
var chart = nv.models.historicalBarChart(nv.models.ohlcBar());
// special default tooltip since we show multiple values per x
chart.useInteractiveGuideline(true);
chart.interactiveLayer.tooltip.contentGenerator(function(data) {
// we assume only one series exists for this chart
var d = data.series[0].data;
// match line colors as defined in nv.d3.css
var color = d.open < d.close ? "2ca02c" : "d62728";
return '' +
'<h3 style="color: #' + color + '">' + data.value + '</h3>' +
'<table>' +
'<tr><td>open:</td><td>' + chart.yAxis.tickFormat()(d.open) + '</td></tr>' +
'<tr><td>close:</td><td>' + chart.yAxis.tickFormat()(d.close) + '</td></tr>' +
'<tr><td>high</td><td>' + chart.yAxis.tickFormat()(d.high) + '</td></tr>' +
'<tr><td>low:</td><td>' + chart.yAxis.tickFormat()(d.low) + '</td></tr>' +
'</table>';
});
return chart;
};
// candlestickChart is just a historical chart with candlestick bars and some tweaks
nv.models.candlestickBarChart = function() {
var chart = nv.models.historicalBarChart(nv.models.candlestickBar());
// special default tooltip since we show multiple values per x
chart.useInteractiveGuideline(true);
chart.interactiveLayer.tooltip.contentGenerator(function(data) {
// we assume only one series exists for this chart
var d = data.series[0].data;
// match line colors as defined in nv.d3.css
var color = d.open < d.close ? "2ca02c" : "d62728";
return '' +
'<h3 style="color: #' + color + '">' + data.value + '</h3>' +
'<table>' +
'<tr><td>open:</td><td>' + chart.yAxis.tickFormat()(d.open) + '</td></tr>' +
'<tr><td>close:</td><td>' + chart.yAxis.tickFormat()(d.close) + '</td></tr>' +
'<tr><td>high</td><td>' + chart.yAxis.tickFormat()(d.high) + '</td></tr>' +
'<tr><td>low:</td><td>' + chart.yAxis.tickFormat()(d.low) + '</td></tr>' +
'</table>';
});
return chart;
};
nv.models.legend = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var margin = {top: 5, right: 0, bottom: 5, left: 0}
, width = 400
, height = 20
, getKey = function(d) { return d.key }
, color = nv.utils.getColor()
, maxKeyLength = 20 //default value for key lengths
, align = true
, padding = 32 //define how much space between legend items. - recommend 32 for furious version
, rightAlign = true
, updateState = true //If true, legend will update data.disabled and trigger a 'stateChange' dispatch.
, radioButtonMode = false //If true, clicking legend items will cause it to behave like a radio button. (only one can be selected at a time)
, expanded = false
, dispatch = d3.dispatch('legendClick', 'legendDblclick', 'legendMouseover', 'legendMouseout', 'stateChange')
, vers = 'classic' //Options are "classic" and "furious"
;
function chart(selection) {
selection.each(function(data) {
var availableWidth = width - margin.left - margin.right,
container = d3.select(this);
nv.utils.initSVG(container);
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-legend').data([data]);
var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-legend').append('g');
var g = wrap.select('g');
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
var series = g.selectAll('.nv-series')
.data(function(d) {
if(vers != 'furious') return d;
return d.filter(function(n) {
return expanded ? true : !n.disengaged;
});
});
var seriesEnter = series.enter().append('g').attr('class', 'nv-series');
var seriesShape;
var versPadding;
switch(vers) {
case 'furious' :
versPadding = 23;
break;
case 'classic' :
versPadding = 20;
}
if(vers == 'classic') {
seriesEnter.append('circle')
.style('stroke-width', 2)
.attr('class','nv-legend-symbol')
.attr('r', 5);
seriesShape = series.select('.nv-legend-symbol');
} else if (vers == 'furious') {
seriesEnter.append('rect')
.style('stroke-width', 2)
.attr('class','nv-legend-symbol')
.attr('rx', 3)
.attr('ry', 3);
seriesShape = series.select('.nv-legend-symbol');
seriesEnter.append('g')
.attr('class', 'nv-check-box')
.property('innerHTML','<path d="M0.5,5 L22.5,5 L22.5,26.5 L0.5,26.5 L0.5,5 Z" class="nv-box"></path><path d="M5.5,12.8618467 L11.9185089,19.2803556 L31,0.198864511" class="nv-check"></path>')
.attr('transform', 'translate(-10,-8)scale(0.5)');
var seriesCheckbox = series.select('.nv-check-box');
seriesCheckbox.each(function(d,i) {
d3.select(this).selectAll('path')
.attr('stroke', setTextColor(d,i));
});
}
seriesEnter.append('text')
.attr('text-anchor', 'start')
.attr('class','nv-legend-text')
.attr('dy', '.32em')
.attr('dx', '8');
var seriesText = series.select('text.nv-legend-text');
series
.on('mouseover', function(d,i) {
dispatch.legendMouseover(d,i); //TODO: Make consistent with other event objects
})
.on('mouseout', function(d,i) {
dispatch.legendMouseout(d,i);
})
.on('click', function(d,i) {
dispatch.legendClick(d,i);
// make sure we re-get data in case it was modified
var data = series.data();
if (updateState) {
if(vers =='classic') {
if (radioButtonMode) {
//Radio button mode: set every series to disabled,
// and enable the clicked series.
data.forEach(function(series) { series.disabled = true});
d.disabled = false;
}
else {
d.disabled = !d.disabled;
if (data.every(function(series) { return series.disabled})) {
//the default behavior of NVD3 legends is, if every single series
// is disabled, turn all series' back on.
data.forEach(function(series) { series.disabled = false});
}
}
} else if(vers == 'furious') {
if(expanded) {
d.disengaged = !d.disengaged;
d.userDisabled = d.userDisabled == undefined ? !!d.disabled : d.userDisabled;
d.disabled = d.disengaged || d.userDisabled;
} else if (!expanded) {
d.disabled = !d.disabled;
d.userDisabled = d.disabled;
var engaged = data.filter(function(d) { return !d.disengaged; });
if (engaged.every(function(series) { return series.userDisabled })) {
//the default behavior of NVD3 legends is, if every single series
// is disabled, turn all series' back on.
data.forEach(function(series) {
series.disabled = series.userDisabled = false;
});
}
}
}
dispatch.stateChange({
disabled: data.map(function(d) { return !!d.disabled }),
disengaged: data.map(function(d) { return !!d.disengaged })
});
}
})
.on('dblclick', function(d,i) {
if(vers == 'furious' && expanded) return;
dispatch.legendDblclick(d,i);
if (updateState) {
// make sure we re-get data in case it was modified
var data = series.data();
//the default behavior of NVD3 legends, when double clicking one,
// is to set all other series' to false, and make the double clicked series enabled.
data.forEach(function(series) {
series.disabled = true;
if(vers == 'furious') series.userDisabled = series.disabled;
});
d.disabled = false;
if(vers == 'furious') d.userDisabled = d.disabled;
dispatch.stateChange({
disabled: data.map(function(d) { return !!d.disabled })
});
}
});
series.classed('nv-disabled', function(d) { return d.userDisabled });
series.exit().remove();
seriesText
.attr('fill', setTextColor)
.text(getKey);
//TODO: implement fixed-width and max-width options (max-width is especially useful with the align option)
// NEW ALIGNING CODE, TODO: clean up
var legendWidth = 0;
if (align) {
var seriesWidths = [];
series.each(function(d,i) {
var legendText;
if (getKey(d) && (getKey(d).length > maxKeyLength)) {
var trimmedKey = getKey(d).substring(0, maxKeyLength);
legendText = d3.select(this).select('text').text(trimmedKey + "...");
d3.select(this).append("svg:title").text(getKey(d));
} else {
legendText = d3.select(this).select('text');
}
var nodeTextLength;
try {
nodeTextLength = legendText.node().getComputedTextLength();
// If the legendText is display:none'd (nodeTextLength == 0), simulate an error so we approximate, instead
if(nodeTextLength <= 0) throw Error();
}
catch(e) {
nodeTextLength = nv.utils.calcApproxTextWidth(legendText);
}
seriesWidths.push(nodeTextLength + padding);
});
var seriesPerRow = 0;
var columnWidths = [];
legendWidth = 0;
while ( legendWidth < availableWidth && seriesPerRow < seriesWidths.length) {
columnWidths[seriesPerRow] = seriesWidths[seriesPerRow];
legendWidth += seriesWidths[seriesPerRow++];
}
if (seriesPerRow === 0) seriesPerRow = 1; //minimum of one series per row
while ( legendWidth > availableWidth && seriesPerRow > 1 ) {
columnWidths = [];
seriesPerRow--;
for (var k = 0; k < seriesWidths.length; k++) {
if (seriesWidths[k] > (columnWidths[k % seriesPerRow] || 0) )
columnWidths[k % seriesPerRow] = seriesWidths[k];
}
legendWidth = columnWidths.reduce(function(prev, cur, index, array) {
return prev + cur;
});
}
var xPositions = [];
for (var i = 0, curX = 0; i < seriesPerRow; i++) {
xPositions[i] = curX;
curX += columnWidths[i];
}
series
.attr('transform', function(d, i) {
return 'translate(' + xPositions[i % seriesPerRow] + ',' + (5 + Math.floor(i / seriesPerRow) * versPadding) + ')';
});
//position legend as far right as possible within the total width
if (rightAlign) {
g.attr('transform', 'translate(' + (width - margin.right - legendWidth) + ',' + margin.top + ')');
}
else {
g.attr('transform', 'translate(0' + ',' + margin.top + ')');
}
height = margin.top + margin.bottom + (Math.ceil(seriesWidths.length / seriesPerRow) * versPadding);
} else {
var ypos = 5,
newxpos = 5,
maxwidth = 0,
xpos;
series
.attr('transform', function(d, i) {
var length = d3.select(this).select('text').node().getComputedTextLength() + padding;
xpos = newxpos;
if (width < margin.left + margin.right + xpos + length) {
newxpos = xpos = 5;
ypos += versPadding;
}
newxpos += length;
if (newxpos > maxwidth) maxwidth = newxpos;
if(legendWidth < xpos + maxwidth) {
legendWidth = xpos + maxwidth;
}
return 'translate(' + xpos + ',' + ypos + ')';
});
//position legend as far right as possible within the total width
g.attr('transform', 'translate(' + (width - margin.right - maxwidth) + ',' + margin.top + ')');
height = margin.top + margin.bottom + ypos + 15;
}
if(vers == 'furious') {
// Size rectangles after text is placed
seriesShape
.attr('width', function(d,i) {
return seriesText[0][i].getComputedTextLength() + 27;
})
.attr('height', 18)
.attr('y', -9)
.attr('x', -15);
// The background for the expanded legend (UI)
gEnter.insert('rect',':first-child')
.attr('class', 'nv-legend-bg')
.attr('fill', '#eee')
// .attr('stroke', '#444')
.attr('opacity',0);
var seriesBG = g.select('.nv-legend-bg');
seriesBG
.transition().duration(300)
.attr('x', -versPadding )
.attr('width', legendWidth + versPadding - 12)
.attr('height', height + 10)
.attr('y', -margin.top - 10)
.attr('opacity', expanded ? 1 : 0);
}
seriesShape
.style('fill', setBGColor)
.style('fill-opacity', setBGOpacity)
.style('stroke', setBGColor);
});
function setTextColor(d,i) {
if(vers != 'furious') return '#000';
if(expanded) {
return d.disengaged ? '#000' : '#fff';
} else if (!expanded) {
if(!d.color) d.color = color(d,i);
return !!d.disabled ? d.color : '#fff';
}
}
function setBGColor(d,i) {
if(expanded && vers == 'furious') {
return d.disengaged ? '#eee' : d.color || color(d,i);
} else {
return d.color || color(d,i);
}
}
function setBGOpacity(d,i) {
if(expanded && vers == 'furious') {
return 1;
} else {
return !!d.disabled ? 0 : 1;
}
}
return chart;
}
//============================================================
// Expose Public Variables
//------------------------------------------------------------
chart.dispatch = dispatch;
chart.options = nv.utils.optionsFunc.bind(chart);
chart._options = Object.create({}, {
// simple options, just get/set the necessary values
width: {get: function(){return width;}, set: function(_){width=_;}},
height: {get: function(){return height;}, set: function(_){height=_;}},
key: {get: function(){return getKey;}, set: function(_){getKey=_;}},
align: {get: function(){return align;}, set: function(_){align=_;}},
maxKeyLength: {get: function(){return maxKeyLength;}, set: function(_){maxKeyLength=_;}},
rightAlign: {get: function(){return rightAlign;}, set: function(_){rightAlign=_;}},
padding: {get: function(){return padding;}, set: function(_){padding=_;}},
updateState: {get: function(){return updateState;}, set: function(_){updateState=_;}},
radioButtonMode: {get: function(){return radioButtonMode;}, set: function(_){radioButtonMode=_;}},
expanded: {get: function(){return expanded;}, set: function(_){expanded=_;}},
vers: {get: function(){return vers;}, set: function(_){vers=_;}},
// options that require extra logic in the setter
margin: {get: function(){return margin;}, set: function(_){
margin.top = _.top !== undefined ? _.top : margin.top;
margin.right = _.right !== undefined ? _.right : margin.right;
margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
margin.left = _.left !== undefined ? _.left : margin.left;
}},
color: {get: function(){return color;}, set: function(_){
color = nv.utils.getColor(_);
}}
});
nv.utils.initOptions(chart);
return chart;
};
nv.models.line = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var scatter = nv.models.scatter()
;
var margin = {top: 0, right: 0, bottom: 0, left: 0}
, width = 960
, height = 500
, container = null
, strokeWidth = 1.5
, color = nv.utils.defaultColor() // a function that returns a color
, getX = function(d) { return d.x } // accessor to get the x value from a data point
, getY = function(d) { return d.y } // accessor to get the y value from a data point
, defined = function(d,i) { return !isNaN(getY(d,i)) && getY(d,i) !== null } // allows a line to be not continuous when it is not defined
, isArea = function(d) { return d.area } // decides if a line is an area or just a line
, clipEdge = false // if true, masks lines within x and y scale
, x //can be accessed via chart.xScale()
, y //can be accessed via chart.yScale()
, interpolate = "linear" // controls the line interpolation
, duration = 250
, dispatch = d3.dispatch('elementClick', 'elementMouseover', 'elementMouseout', 'renderEnd')
;
scatter
.pointSize(16) // default size
.pointDomain([16,256]) //set to speed up calculation, needs to be unset if there is a custom size accessor
;
//============================================================
//============================================================
// Private Variables
//------------------------------------------------------------
var x0, y0 //used to store previous scales
, renderWatch = nv.utils.renderWatch(dispatch, duration)
;
//============================================================
function chart(selection) {
renderWatch.reset();
renderWatch.models(scatter);
selection.each(function(data) {
container = d3.select(this);
var availableWidth = nv.utils.availableWidth(width, container, margin),
availableHeight = nv.utils.availableHeight(height, container, margin);
nv.utils.initSVG(container);
// Setup Scales
x = scatter.xScale();
y = scatter.yScale();
x0 = x0 || x;
y0 = y0 || y;
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-line').data([data]);
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-line');
var defsEnter = wrapEnter.append('defs');
var gEnter = wrapEnter.append('g');
var g = wrap.select('g');
gEnter.append('g').attr('class', 'nv-groups');
gEnter.append('g').attr('class', 'nv-scatterWrap');
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
scatter
.width(availableWidth)
.height(availableHeight);
var scatterWrap = wrap.select('.nv-scatterWrap');
scatterWrap.call(scatter);
defsEnter.append('clipPath')
.attr('id', 'nv-edge-clip-' + scatter.id())
.append('rect');
wrap.select('#nv-edge-clip-' + scatter.id() + ' rect')
.attr('width', availableWidth)
.attr('height', (availableHeight > 0) ? availableHeight : 0);
g .attr('clip-path', clipEdge ? 'url(#nv-edge-clip-' + scatter.id() + ')' : '');
scatterWrap
.attr('clip-path', clipEdge ? 'url(#nv-edge-clip-' + scatter.id() + ')' : '');
var groups = wrap.select('.nv-groups').selectAll('.nv-group')
.data(function(d) { return d }, function(d) { return d.key });
groups.enter().append('g')
.style('stroke-opacity', 1e-6)
.style('stroke-width', function(d) { return d.strokeWidth || strokeWidth })
.style('fill-opacity', 1e-6);
groups.exit().remove();
groups
.attr('class', function(d,i) {
return (d.classed || '') + ' nv-group nv-series-' + i;
})
.classed('hover', function(d) { return d.hover })
.style('fill', function(d,i){ return color(d, i) })
.style('stroke', function(d,i){ return color(d, i)});
groups.watchTransition(renderWatch, 'line: groups')
.style('stroke-opacity', 1)
.style('fill-opacity', function(d) { return d.fillOpacity || .5});
var areaPaths = groups.selectAll('path.nv-area')
.data(function(d) { return isArea(d) ? [d] : [] }); // this is done differently than lines because I need to check if series is an area
areaPaths.enter().append('path')
.attr('class', 'nv-area')
.attr('d', function(d) {
return d3.svg.area()
.interpolate(interpolate)
.defined(defined)
.x(function(d,i) { return nv.utils.NaNtoZero(x0(getX(d,i))) })
.y0(function(d,i) { return nv.utils.NaNtoZero(y0(getY(d,i))) })
.y1(function(d,i) { return y0( y.domain()[0] <= 0 ? y.domain()[1] >= 0 ? 0 : y.domain()[1] : y.domain()[0] ) })
//.y1(function(d,i) { return y0(0) }) //assuming 0 is within y domain.. may need to tweak this
.apply(this, [d.values])
});
groups.exit().selectAll('path.nv-area')
.remove();
areaPaths.watchTransition(renderWatch, 'line: areaPaths')
.attr('d', function(d) {
return d3.svg.area()
.interpolate(interpolate)
.defined(defined)
.x(function(d,i) { return nv.utils.NaNtoZero(x(getX(d,i))) })
.y0(function(d,i) { return nv.utils.NaNtoZero(y(getY(d,i))) })
.y1(function(d,i) { return y( y.domain()[0] <= 0 ? y.domain()[1] >= 0 ? 0 : y.domain()[1] : y.domain()[0] ) })
//.y1(function(d,i) { return y0(0) }) //assuming 0 is within y domain.. may need to tweak this
.apply(this, [d.values])
});
var linePaths = groups.selectAll('path.nv-line')
.data(function(d) { return [d.values] });
linePaths.enter().append('path')
.attr('class', 'nv-line')
.attr('d',
d3.svg.line()
.interpolate(interpolate)
.defined(defined)
.x(function(d,i) { return nv.utils.NaNtoZero(x0(getX(d,i))) })
.y(function(d,i) { return nv.utils.NaNtoZero(y0(getY(d,i))) })
);
linePaths.watchTransition(renderWatch, 'line: linePaths')
.attr('d',
d3.svg.line()
.interpolate(interpolate)
.defined(defined)
.x(function(d,i) { return nv.utils.NaNtoZero(x(getX(d,i))) })
.y(function(d,i) { return nv.utils.NaNtoZero(y(getY(d,i))) })
);
//store old scales for use in transitions on update
x0 = x.copy();
y0 = y.copy();
});
renderWatch.renderEnd('line immediate');
return chart;
}
//============================================================
// Expose Public Variables
//------------------------------------------------------------
chart.dispatch = dispatch;
chart.scatter = scatter;
// Pass through events
scatter.dispatch.on('elementClick', function(){ dispatch.elementClick.apply(this, arguments); });
scatter.dispatch.on('elementMouseover', function(){ dispatch.elementMouseover.apply(this, arguments); });
scatter.dispatch.on('elementMouseout', function(){ dispatch.elementMouseout.apply(this, arguments); });
chart.options = nv.utils.optionsFunc.bind(chart);
chart._options = Object.create({}, {
// simple options, just get/set the necessary values
width: {get: function(){return width;}, set: function(_){width=_;}},
height: {get: function(){return height;}, set: function(_){height=_;}},
defined: {get: function(){return defined;}, set: function(_){defined=_;}},
interpolate: {get: function(){return interpolate;}, set: function(_){interpolate=_;}},
clipEdge: {get: function(){return clipEdge;}, set: function(_){clipEdge=_;}},
// options that require extra logic in the setter
margin: {get: function(){return margin;}, set: function(_){
margin.top = _.top !== undefined ? _.top : margin.top;
margin.right = _.right !== undefined ? _.right : margin.right;
margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
margin.left = _.left !== undefined ? _.left : margin.left;
}},
duration: {get: function(){return duration;}, set: function(_){
duration = _;
renderWatch.reset(duration);
scatter.duration(duration);
}},
isArea: {get: function(){return isArea;}, set: function(_){
isArea = d3.functor(_);
}},
x: {get: function(){return getX;}, set: function(_){
getX = _;
scatter.x(_);
}},
y: {get: function(){return getY;}, set: function(_){
getY = _;
scatter.y(_);
}},
color: {get: function(){return color;}, set: function(_){
color = nv.utils.getColor(_);
scatter.color(color);
}}
});
nv.utils.inheritOptions(chart, scatter);
nv.utils.initOptions(chart);
return chart;
};
nv.models.lineChart = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var lines = nv.models.line()
, xAxis = nv.models.axis()
, yAxis = nv.models.axis()
, legend = nv.models.legend()
, interactiveLayer = nv.interactiveGuideline()
, tooltip = nv.models.tooltip()
, focus = nv.models.focus(nv.models.line())
;
var margin = {top: 30, right: 20, bottom: 50, left: 60}
, color = nv.utils.defaultColor()
, width = null
, height = null
, showLegend = true
, legendPosition = 'top'
, showXAxis = true
, showYAxis = true
, rightAlignYAxis = false
, useInteractiveGuideline = false
, x
, y
, focusEnable = false
, state = nv.utils.state()
, defaultState = null
, noData = null
, dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState', 'renderEnd')
, duration = 250
;
// set options on sub-objects for this chart
xAxis.orient('bottom').tickPadding(7);
yAxis.orient(rightAlignYAxis ? 'right' : 'left');
lines.clipEdge(true).duration(0);
tooltip.valueFormatter(function(d, i) {
return yAxis.tickFormat()(d, i);
}).headerFormatter(function(d, i) {
return xAxis.tickFormat()(d, i);
});
interactiveLayer.tooltip.valueFormatter(function(d, i) {
return yAxis.tickFormat()(d, i);
}).headerFormatter(function(d, i) {
return xAxis.tickFormat()(d, i);
});
//============================================================
// Private Variables
//------------------------------------------------------------
var renderWatch = nv.utils.renderWatch(dispatch, duration);
var stateGetter = function(data) {
return function(){
return {
active: data.map(function(d) { return !d.disabled; })
};
};
};
var stateSetter = function(data) {
return function(state) {
if (state.active !== undefined)
data.forEach(function(series,i) {
series.disabled = !state.active[i];
});
};
};
function chart(selection) {
renderWatch.reset();
renderWatch.models(lines);
if (showXAxis) renderWatch.models(xAxis);
if (showYAxis) renderWatch.models(yAxis);
selection.each(function(data) {
var container = d3.select(this);
nv.utils.initSVG(container);
var availableWidth = nv.utils.availableWidth(width, container, margin),
availableHeight = nv.utils.availableHeight(height, container, margin) - (focusEnable ? focus.height() : 0);
chart.update = function() {
if( duration === 0 ) {
container.call( chart );
} else {
container.transition().duration(duration).call(chart);
}
};
chart.container = this;
state
.setter(stateSetter(data), chart.update)
.getter(stateGetter(data))
.update();
// DEPRECATED set state.disabled
state.disabled = data.map(function(d) { return !!d.disabled; });
if (!defaultState) {
var key;
defaultState = {};
for (key in state) {
if (state[key] instanceof Array)
defaultState[key] = state[key].slice(0);
else
defaultState[key] = state[key];
}
}
// Display noData message if there's nothing to show.
if (!data || !data.length || !data.filter(function(d) { return d.values.length; }).length) {
nv.utils.noData(chart, container);
return chart;
} else {
container.selectAll('.nv-noData').remove();
}
// Setup Scales
x = lines.xScale();
y = lines.yScale();
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-lineChart').data([data]);
var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-lineChart').append('g');
var g = wrap.select('g');
gEnter.append('g').attr('class', 'nv-legendWrap');
var focusEnter = gEnter.append('g').attr('class', 'nv-focus');
focusEnter.append('g').attr('class', 'nv-background').append('rect');
focusEnter.append('g').attr('class', 'nv-x nv-axis');
focusEnter.append('g').attr('class', 'nv-y nv-axis');
focusEnter.append('g').attr('class', 'nv-linesWrap');
focusEnter.append('g').attr('class', 'nv-interactive');
var contextEnter = gEnter.append('g').attr('class', 'nv-focusWrap');
// Legend
if (!showLegend) {
g.select('.nv-legendWrap').selectAll('*').remove();
} else {
legend.width(availableWidth);
g.select('.nv-legendWrap')
.datum(data)
.call(legend);
if (legendPosition === 'bottom') {
wrap.select('.nv-legendWrap')
.attr('transform', 'translate(0,' + availableHeight +')');
} else if (legendPosition === 'top') {
if ( margin.top != legend.height()) {
margin.top = legend.height();
availableHeight = nv.utils.availableHeight(height, container, margin) - (focusEnable ? focus.height() : 0);
}
wrap.select('.nv-legendWrap')
.attr('transform', 'translate(0,' + (-margin.top) +')');
}
}
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
if (rightAlignYAxis) {
g.select(".nv-y.nv-axis")
.attr("transform", "translate(" + availableWidth + ",0)");
}
//Set up interactive layer
if (useInteractiveGuideline) {
interactiveLayer
.width(availableWidth)
.height(availableHeight)
.margin({left:margin.left, top:margin.top})
.svgContainer(container)
.xScale(x);
wrap.select(".nv-interactive").call(interactiveLayer);
}
g.select('.nv-focus .nv-background rect')
.attr('width', availableWidth)
.attr('height', availableHeight);
lines
.width(availableWidth)
.height(availableHeight)
.color(data.map(function(d,i) {
return d.color || color(d, i);
}).filter(function(d,i) { return !data[i].disabled; }));
var linesWrap = g.select('.nv-linesWrap')
.datum(data.filter(function(d) { return !d.disabled; }));
// Setup Main (Focus) Axes
if (showXAxis) {
xAxis
.scale(x)
._ticks(nv.utils.calcTicksX(availableWidth/100, data) )
.tickSize(-availableHeight, 0);
}
if (showYAxis) {
yAxis
.scale(y)
._ticks( nv.utils.calcTicksY(availableHeight/36, data) )
.tickSize( -availableWidth, 0);
}
//============================================================
// Update Axes
//============================================================
function updateXAxis() {
if(showXAxis) {
g.select('.nv-focus .nv-x.nv-axis')
.transition()
.duration(duration)
.call(xAxis)
;
}
}
function updateYAxis() {
if(showYAxis) {
g.select('.nv-focus .nv-y.nv-axis')
.transition()
.duration(duration)
.call(yAxis)
;
}
}
g.select('.nv-focus .nv-x.nv-axis')
.attr('transform', 'translate(0,' + availableHeight + ')');
//============================================================
// Update Focus
//============================================================
if(!focusEnable) {
linesWrap.call(lines);
updateXAxis();
updateYAxis();
} else {
focus.width(availableWidth);
g.select('.nv-focusWrap')
.attr('transform', 'translate(0,' + ( availableHeight + margin.bottom + focus.margin().top) + ')')
.datum(data.filter(function(d) { return !d.disabled; }))
.call(focus);
var extent = focus.brush.empty() ? focus.xDomain() : focus.brush.extent();
if(extent !== null){
onBrush(extent);
}
}
//============================================================
// Event Handling/Dispatching (in chart's scope)
//------------------------------------------------------------
legend.dispatch.on('stateChange', function(newState) {
for (var key in newState)
state[key] = newState[key];
dispatch.stateChange(state);
chart.update();
});
interactiveLayer.dispatch.on('elementMousemove', function(e) {
lines.clearHighlights();
var singlePoint, pointIndex, pointXLocation, allData = [];
data
.filter(function(series, i) {
series.seriesIndex = i;
return !series.disabled && !series.disableTooltip;
})
.forEach(function(series,i) {
var extent = focusEnable ? (focus.brush.empty() ? focus.xScale().domain() : focus.brush.extent()) : x.domain();
var currentValues = series.values.filter(function(d,i) {
return lines.x()(d,i) >= extent[0] && lines.x()(d,i) <= extent[1];
});
pointIndex = nv.interactiveBisect(currentValues, e.pointXValue, lines.x());
var point = currentValues[pointIndex];
var pointYValue = chart.y()(point, pointIndex);
if (pointYValue !== null) {
lines.highlightPoint(series.seriesIndex, pointIndex, true);
}
if (point === undefined) return;
if (singlePoint === undefined) singlePoint = point;
if (pointXLocation === undefined) pointXLocation = chart.xScale()(chart.x()(point,pointIndex));
allData.push({
key: series.key,
value: pointYValue,
color: color(series,series.seriesIndex),
data: point
});
});
//Highlight the tooltip entry based on which point the mouse is closest to.
if (allData.length > 2) {
var yValue = chart.yScale().invert(e.mouseY);
var domainExtent = Math.abs(chart.yScale().domain()[0] - chart.yScale().domain()[1]);
var threshold = 0.03 * domainExtent;
var indexToHighlight = nv.nearestValueIndex(allData.map(function(d){return d.value;}),yValue,threshold);
if (indexToHighlight !== null)
allData[indexToHighlight].highlight = true;
}
var defaultValueFormatter = function(d,i) {
return d == null ? "N/A" : yAxis.tickFormat()(d);
};
interactiveLayer.tooltip
.chartContainer(chart.container.parentNode)
.valueFormatter(interactiveLayer.tooltip.valueFormatter() || defaultValueFormatter)
.data({
value: chart.x()( singlePoint,pointIndex ),
index: pointIndex,
series: allData
})();
interactiveLayer.renderGuideLine(pointXLocation);
});
interactiveLayer.dispatch.on('elementClick', function(e) {
var pointXLocation, allData = [];
data.filter(function(series, i) {
series.seriesIndex = i;
return !series.disabled;
}).forEach(function(series) {
var pointIndex = nv.interactiveBisect(series.values, e.pointXValue, chart.x());
var point = series.values[pointIndex];
if (typeof point === 'undefined') return;
if (typeof pointXLocation === 'undefined') pointXLocation = chart.xScale()(chart.x()(point,pointIndex));
var yPos = chart.yScale()(chart.y()(point,pointIndex));
allData.push({
point: point,
pointIndex: pointIndex,
pos: [pointXLocation, yPos],
seriesIndex: series.seriesIndex,
series: series
});
});
lines.dispatch.elementClick(allData);
});
interactiveLayer.dispatch.on("elementMouseout",function(e) {
lines.clearHighlights();
});
/* Update `main' graph on brush update. */
focus.dispatch.on("onBrush", function(extent) {
onBrush(extent);
});
dispatch.on('changeState', function(e) {
if (typeof e.disabled !== 'undefined' && data.length === e.disabled.length) {
data.forEach(function(series,i) {
series.disabled = e.disabled[i];
});
state.disabled = e.disabled;
}
chart.update();
});
//============================================================
// Functions
//------------------------------------------------------------
// Taken from crossfilter (http://square.github.com/crossfilter/)
function resizePath(d) {
var e = +(d == 'e'),
x = e ? 1 : -1,
y = availableHeight / 3;
return 'M' + (0.5 * x) + ',' + y
+ 'A6,6 0 0 ' + e + ' ' + (6.5 * x) + ',' + (y + 6)
+ 'V' + (2 * y - 6)
+ 'A6,6 0 0 ' + e + ' ' + (0.5 * x) + ',' + (2 * y)
+ 'Z'
+ 'M' + (2.5 * x) + ',' + (y + 8)
+ 'V' + (2 * y - 8)
+ 'M' + (4.5 * x) + ',' + (y + 8)
+ 'V' + (2 * y - 8);
}
function onBrush(extent) {
// Update Main (Focus)
var focusLinesWrap = g.select('.nv-focus .nv-linesWrap')
.datum(
data.filter(function(d) { return !d.disabled; })
.map(function(d,i) {
return {
key: d.key,
area: d.area,
classed: d.classed,
values: d.values.filter(function(d,i) {
return lines.x()(d,i) >= extent[0] && lines.x()(d,i) <= extent[1];
}),
disableTooltip: d.disableTooltip
};
})
);
focusLinesWrap.transition().duration(duration).call(lines);
// Update Main (Focus) Axes
updateXAxis();
updateYAxis();
}
});
renderWatch.renderEnd('lineChart immediate');
return chart;
}
//============================================================
// Event Handling/Dispatching (out of chart's scope)
//------------------------------------------------------------
lines.dispatch.on('elementMouseover.tooltip', function(evt) {
if(!evt.series.disableTooltip){
tooltip.data(evt).hidden(false);
}
});
lines.dispatch.on('elementMouseout.tooltip', function(evt) {
tooltip.hidden(true);
});
//============================================================
// Expose Public Variables
//------------------------------------------------------------
// expose chart's sub-components
chart.dispatch = dispatch;
chart.lines = lines;
chart.legend = legend;
chart.focus = focus;
chart.xAxis = xAxis;
chart.x2Axis = focus.xAxis
chart.yAxis = yAxis;
chart.y2Axis = focus.yAxis
chart.interactiveLayer = interactiveLayer;
chart.tooltip = tooltip;
chart.state = state;
chart.dispatch = dispatch;
chart.options = nv.utils.optionsFunc.bind(chart);
chart._options = Object.create({}, {
// simple options, just get/set the necessary values
width: {get: function(){return width;}, set: function(_){width=_;}},
height: {get: function(){return height;}, set: function(_){height=_;}},
showLegend: {get: function(){return showLegend;}, set: function(_){showLegend=_;}},
legendPosition: {get: function(){return legendPosition;}, set: function(_){legendPosition=_;}},
showXAxis: {get: function(){return showXAxis;}, set: function(_){showXAxis=_;}},
showYAxis: {get: function(){return showYAxis;}, set: function(_){showYAxis=_;}},
defaultState: {get: function(){return defaultState;}, set: function(_){defaultState=_;}},
noData: {get: function(){return noData;}, set: function(_){noData=_;}},
// Focus options, mostly passed onto focus model.
focusEnable: {get: function(){return focusEnable;}, set: function(_){focusEnable=_;}},
focusHeight: {get: function(){return focus.height();}, set: function(_){focus.height(_);}},
focusShowAxisX: {get: function(){return focus.showXAxis();}, set: function(_){focus.showXAxis(_);}},
focusShowAxisY: {get: function(){return focus.showYAxis();}, set: function(_){focus.showYAxis(_);}},
brushExtent: {get: function(){return focus.brushExtent();}, set: function(_){focus.brushExtent(_);}},
// options that require extra logic in the setter
focusMargin: {get: function(){return focus.margin}, set: function(_){
focus.margin.top = _.top !== undefined ? _.top : focus.margin.top;
focus.margin.right = _.right !== undefined ? _.right : focus.margin.right;
focus.margin.bottom = _.bottom !== undefined ? _.bottom : focus.margin.bottom;
focus.margin.left = _.left !== undefined ? _.left : focus.margin.left;
}},
margin: {get: function(){return margin;}, set: function(_){
margin.top = _.top !== undefined ? _.top : margin.top;
margin.right = _.right !== undefined ? _.right : margin.right;
margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
margin.left = _.left !== undefined ? _.left : margin.left;
}},
duration: {get: function(){return duration;}, set: function(_){
duration = _;
renderWatch.reset(duration);
lines.duration(duration);
focus.duration(duration);
xAxis.duration(duration);
yAxis.duration(duration);
}},
color: {get: function(){return color;}, set: function(_){
color = nv.utils.getColor(_);
legend.color(color);
lines.color(color);
focus.color(color);
}},
interpolate: {get: function(){return lines.interpolate();}, set: function(_){
lines.interpolate(_);
focus.interpolate(_);
}},
xTickFormat: {get: function(){return xAxis.tickFormat();}, set: function(_){
xAxis.tickFormat(_);
focus.xTickFormat(_);
}},
yTickFormat: {get: function(){return yAxis.tickFormat();}, set: function(_){
yAxis.tickFormat(_);
focus.yTickFormat(_);
}},
x: {get: function(){return lines.x();}, set: function(_){
lines.x(_);
focus.x(_);
}},
y: {get: function(){return lines.y();}, set: function(_){
lines.y(_);
focus.y(_);
}},
rightAlignYAxis: {get: function(){return rightAlignYAxis;}, set: function(_){
rightAlignYAxis = _;
yAxis.orient( rightAlignYAxis ? 'right' : 'left');
}},
useInteractiveGuideline: {get: function(){return useInteractiveGuideline;}, set: function(_){
useInteractiveGuideline = _;
if (useInteractiveGuideline) {
lines.interactive(false);
lines.useVoronoi(false);
}
}}
});
nv.utils.inheritOptions(chart, lines);
nv.utils.initOptions(chart);
return chart;
};
nv.models.lineWithFocusChart = function() {
return nv.models.lineChart()
.margin({ bottom: 30 })
.focusEnable( true );
};nv.models.linePlusBarChart = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var lines = nv.models.line()
, lines2 = nv.models.line()
, bars = nv.models.historicalBar()
, bars2 = nv.models.historicalBar()
, xAxis = nv.models.axis()
, x2Axis = nv.models.axis()
, y1Axis = nv.models.axis()
, y2Axis = nv.models.axis()
, y3Axis = nv.models.axis()
, y4Axis = nv.models.axis()
, legend = nv.models.legend()
, brush = d3.svg.brush()
, tooltip = nv.models.tooltip()
;
var margin = {top: 30, right: 30, bottom: 30, left: 60}
, margin2 = {top: 0, right: 30, bottom: 20, left: 60}
, width = null
, height = null
, getX = function(d) { return d.x }
, getY = function(d) { return d.y }
, color = nv.utils.defaultColor()
, showLegend = true
, focusEnable = true
, focusShowAxisY = false
, focusShowAxisX = true
, focusHeight = 50
, extent
, brushExtent = null
, x
, x2
, y1
, y2
, y3
, y4
, noData = null
, dispatch = d3.dispatch('brush', 'stateChange', 'changeState')
, transitionDuration = 0
, state = nv.utils.state()
, defaultState = null
, legendLeftAxisHint = ' (left axis)'
, legendRightAxisHint = ' (right axis)'
, switchYAxisOrder = false
;
lines.clipEdge(true);
lines2.interactive(false);
// We don't want any points emitted for the focus chart's scatter graph.
lines2.pointActive(function(d) { return false });
xAxis.orient('bottom').tickPadding(5);
y1Axis.orient('left');
y2Axis.orient('right');
x2Axis.orient('bottom').tickPadding(5);
y3Axis.orient('left');
y4Axis.orient('right');
tooltip.headerEnabled(true).headerFormatter(function(d, i) {
return xAxis.tickFormat()(d, i);
});
//============================================================
// Private Variables
//------------------------------------------------------------
var getBarsAxis = function() {
return !switchYAxisOrder
? { main: y2Axis, focus: y4Axis }
: { main: y1Axis, focus: y3Axis }
}
var getLinesAxis = function() {
return !switchYAxisOrder
? { main: y1Axis, focus: y3Axis }
: { main: y2Axis, focus: y4Axis }
}
var stateGetter = function(data) {
return function(){
return {
active: data.map(function(d) { return !d.disabled })
};
}
};
var stateSetter = function(data) {
return function(state) {
if (state.active !== undefined)
data.forEach(function(series,i) {
series.disabled = !state.active[i];
});
}
};
var allDisabled = function(data) {
return data.every(function(series) {
return series.disabled;
});
}
function chart(selection) {
selection.each(function(data) {
var container = d3.select(this),
that = this;
nv.utils.initSVG(container);
var availableWidth = nv.utils.availableWidth(width, container, margin),
availableHeight1 = nv.utils.availableHeight(height, container, margin)
- (focusEnable ? focusHeight : 0),
availableHeight2 = focusHeight - margin2.top - margin2.bottom;
chart.update = function() { container.transition().duration(transitionDuration).call(chart); };
chart.container = this;
state
.setter(stateSetter(data), chart.update)
.getter(stateGetter(data))
.update();
// DEPRECATED set state.disableddisabled
state.disabled = data.map(function(d) { return !!d.disabled });
if (!defaultState) {
var key;
defaultState = {};
for (key in state) {
if (state[key] instanceof Array)
defaultState[key] = state[key].slice(0);
else
defaultState[key] = state[key];
}
}
// Display No Data message if there's nothing to show.
if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) {
nv.utils.noData(chart, container)
return chart;
} else {
container.selectAll('.nv-noData').remove();
}
// Setup Scales
var dataBars = data.filter(function(d) { return !d.disabled && d.bar });
var dataLines = data.filter(function(d) { return !d.bar }); // removed the !d.disabled clause here to fix Issue #240
if (dataBars.length && !switchYAxisOrder) {
x = bars.xScale();
} else {
x = lines.xScale();
}
x2 = x2Axis.scale();
// select the scales and series based on the position of the yAxis
y1 = switchYAxisOrder ? lines.yScale() : bars.yScale();
y2 = switchYAxisOrder ? bars.yScale() : lines.yScale();
y3 = switchYAxisOrder ? lines2.yScale() : bars2.yScale();
y4 = switchYAxisOrder ? bars2.yScale() : lines2.yScale();
var series1 = data
.filter(function(d) { return !d.disabled && (switchYAxisOrder ? !d.bar : d.bar) })
.map(function(d) {
return d.values.map(function(d,i) {
return { x: getX(d,i), y: getY(d,i) }
})
});
var series2 = data
.filter(function(d) { return !d.disabled && (switchYAxisOrder ? d.bar : !d.bar) })
.map(function(d) {
return d.values.map(function(d,i) {
return { x: getX(d,i), y: getY(d,i) }
})
});
x.range([0, availableWidth]);
x2 .domain(d3.extent(d3.merge(series1.concat(series2)), function(d) { return d.x } ))
.range([0, availableWidth]);
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-linePlusBar').data([data]);
var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-linePlusBar').append('g');
var g = wrap.select('g');
gEnter.append('g').attr('class', 'nv-legendWrap');
// this is the main chart
var focusEnter = gEnter.append('g').attr('class', 'nv-focus');
focusEnter.append('g').attr('class', 'nv-x nv-axis');
focusEnter.append('g').attr('class', 'nv-y1 nv-axis');
focusEnter.append('g').attr('class', 'nv-y2 nv-axis');
focusEnter.append('g').attr('class', 'nv-barsWrap');
focusEnter.append('g').attr('class', 'nv-linesWrap');
// context chart is where you can focus in
var contextEnter = gEnter.append('g').attr('class', 'nv-context');
contextEnter.append('g').attr('class', 'nv-x nv-axis');
contextEnter.append('g').attr('class', 'nv-y1 nv-axis');
contextEnter.append('g').attr('class', 'nv-y2 nv-axis');
contextEnter.append('g').attr('class', 'nv-barsWrap');
contextEnter.append('g').attr('class', 'nv-linesWrap');
contextEnter.append('g').attr('class', 'nv-brushBackground');
contextEnter.append('g').attr('class', 'nv-x nv-brush');
//============================================================
// Legend
//------------------------------------------------------------
if (!showLegend) {
g.select('.nv-legendWrap').selectAll('*').remove();
} else {
var legendWidth = legend.align() ? availableWidth / 2 : availableWidth;
var legendXPosition = legend.align() ? legendWidth : 0;
legend.width(legendWidth);
g.select('.nv-legendWrap')
.datum(data.map(function(series) {
series.originalKey = series.originalKey === undefined ? series.key : series.originalKey;
if(switchYAxisOrder) {
series.key = series.originalKey + (series.bar ? legendRightAxisHint : legendLeftAxisHint);
} else {
series.key = series.originalKey + (series.bar ? legendLeftAxisHint : legendRightAxisHint);
}
return series;
}))
.call(legend);
if ( margin.top != legend.height()) {
margin.top = legend.height();
// FIXME: shouldn't this be "- (focusEnabled ? focusHeight : 0)"?
availableHeight1 = nv.utils.availableHeight(height, container, margin) - focusHeight;
}
g.select('.nv-legendWrap')
.attr('transform', 'translate(' + legendXPosition + ',' + (-margin.top) +')');
}
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
//============================================================
// Context chart (focus chart) components
//------------------------------------------------------------
// hide or show the focus context chart
g.select('.nv-context').style('display', focusEnable ? 'initial' : 'none');
bars2
.width(availableWidth)
.height(availableHeight2)
.color(data.map(function (d, i) {
return d.color || color(d, i);
}).filter(function (d, i) {
return !data[i].disabled && data[i].bar
}));
lines2
.width(availableWidth)
.height(availableHeight2)
.color(data.map(function (d, i) {
return d.color || color(d, i);
}).filter(function (d, i) {
return !data[i].disabled && !data[i].bar
}));
var bars2Wrap = g.select('.nv-context .nv-barsWrap')
.datum(dataBars.length ? dataBars : [
{values: []}
]);
var lines2Wrap = g.select('.nv-context .nv-linesWrap')
.datum(allDisabled(dataLines) ?
[{values: []}] :
dataLines.filter(function(dataLine) {
return !dataLine.disabled;
}));
g.select('.nv-context')
.attr('transform', 'translate(0,' + ( availableHeight1 + margin.bottom + margin2.top) + ')');
bars2Wrap.transition().call(bars2);
lines2Wrap.transition().call(lines2);
// context (focus chart) axis controls
if (focusShowAxisX) {
x2Axis
._ticks( nv.utils.calcTicksX(availableWidth / 100, data))
.tickSize(-availableHeight2, 0);
g.select('.nv-context .nv-x.nv-axis')
.attr('transform', 'translate(0,' + y3.range()[0] + ')');
g.select('.nv-context .nv-x.nv-axis').transition()
.call(x2Axis);
}
if (focusShowAxisY) {
y3Axis
.scale(y3)
._ticks( availableHeight2 / 36 )
.tickSize( -availableWidth, 0);
y4Axis
.scale(y4)
._ticks( availableHeight2 / 36 )
.tickSize(dataBars.length ? 0 : -availableWidth, 0); // Show the y2 rules only if y1 has none
g.select('.nv-context .nv-y3.nv-axis')
.style('opacity', dataBars.length ? 1 : 0)
.attr('transform', 'translate(0,' + x2.range()[0] + ')');
g.select('.nv-context .nv-y2.nv-axis')
.style('opacity', dataLines.length ? 1 : 0)
.attr('transform', 'translate(' + x2.range()[1] + ',0)');
g.select('.nv-context .nv-y1.nv-axis').transition()
.call(y3Axis);
g.select('.nv-context .nv-y2.nv-axis').transition()
.call(y4Axis);
}
// Setup Brush
brush.x(x2).on('brush', onBrush);
if (brushExtent) brush.extent(brushExtent);
var brushBG = g.select('.nv-brushBackground').selectAll('g')
.data([brushExtent || brush.extent()]);
var brushBGenter = brushBG.enter()
.append('g');
brushBGenter.append('rect')
.attr('class', 'left')
.attr('x', 0)
.attr('y', 0)
.attr('height', availableHeight2);
brushBGenter.append('rect')
.attr('class', 'right')
.attr('x', 0)
.attr('y', 0)
.attr('height', availableHeight2);
var gBrush = g.select('.nv-x.nv-brush')
.call(brush);
gBrush.selectAll('rect')
//.attr('y', -5)
.attr('height', availableHeight2);
gBrush.selectAll('.resize').append('path').attr('d', resizePath);
//============================================================
// Event Handling/Dispatching (in chart's scope)
//------------------------------------------------------------
legend.dispatch.on('stateChange', function(newState) {
for (var key in newState)
state[key] = newState[key];
dispatch.stateChange(state);
chart.update();
});
// Update chart from a state object passed to event handler
dispatch.on('changeState', function(e) {
if (typeof e.disabled !== 'undefined') {
data.forEach(function(series,i) {
series.disabled = e.disabled[i];
});
state.disabled = e.disabled;
}
chart.update();
});
//============================================================
// Functions
//------------------------------------------------------------
// Taken from crossfilter (http://square.github.com/crossfilter/)
function resizePath(d) {
var e = +(d == 'e'),
x = e ? 1 : -1,
y = availableHeight2 / 3;
return 'M' + (.5 * x) + ',' + y
+ 'A6,6 0 0 ' + e + ' ' + (6.5 * x) + ',' + (y + 6)
+ 'V' + (2 * y - 6)
+ 'A6,6 0 0 ' + e + ' ' + (.5 * x) + ',' + (2 * y)
+ 'Z'
+ 'M' + (2.5 * x) + ',' + (y + 8)
+ 'V' + (2 * y - 8)
+ 'M' + (4.5 * x) + ',' + (y + 8)
+ 'V' + (2 * y - 8);
}
function updateBrushBG() {
if (!brush.empty()) brush.extent(brushExtent);
brushBG
.data([brush.empty() ? x2.domain() : brushExtent])
.each(function(d,i) {
var leftWidth = x2(d[0]) - x2.range()[0],
rightWidth = x2.range()[1] - x2(d[1]);
d3.select(this).select('.left')
.attr('width', leftWidth < 0 ? 0 : leftWidth);
d3.select(this).select('.right')
.attr('x', x2(d[1]))
.attr('width', rightWidth < 0 ? 0 : rightWidth);
});
}
function onBrush() {
brushExtent = brush.empty() ? null : brush.extent();
extent = brush.empty() ? x2.domain() : brush.extent();
dispatch.brush({extent: extent, brush: brush});
updateBrushBG();
// Prepare Main (Focus) Bars and Lines
bars
.width(availableWidth)
.height(availableHeight1)
.color(data.map(function(d,i) {
return d.color || color(d, i);
}).filter(function(d,i) { return !data[i].disabled && data[i].bar }));
lines
.width(availableWidth)
.height(availableHeight1)
.color(data.map(function(d,i) {
return d.color || color(d, i);
}).filter(function(d,i) { return !data[i].disabled && !data[i].bar }));
var focusBarsWrap = g.select('.nv-focus .nv-barsWrap')
.datum(!dataBars.length ? [{values:[]}] :
dataBars
.map(function(d,i) {
return {
key: d.key,
values: d.values.filter(function(d,i) {
return bars.x()(d,i) >= extent[0] && bars.x()(d,i) <= extent[1];
})
}
})
);
var focusLinesWrap = g.select('.nv-focus .nv-linesWrap')
.datum(allDisabled(dataLines) ? [{values:[]}] :
dataLines
.filter(function(dataLine) { return !dataLine.disabled; })
.map(function(d,i) {
return {
area: d.area,
fillOpacity: d.fillOpacity,
key: d.key,
values: d.values.filter(function(d,i) {
return lines.x()(d,i) >= extent[0] && lines.x()(d,i) <= extent[1];
})
}
})
);
// Update Main (Focus) X Axis
if (dataBars.length && !switchYAxisOrder) {
x = bars.xScale();
} else {
x = lines.xScale();
}
xAxis
.scale(x)
._ticks( nv.utils.calcTicksX(availableWidth/100, data) )
.tickSize(-availableHeight1, 0);
xAxis.domain([Math.ceil(extent[0]), Math.floor(extent[1])]);
g.select('.nv-x.nv-axis').transition().duration(transitionDuration)
.call(xAxis);
// Update Main (Focus) Bars and Lines
focusBarsWrap.transition().duration(transitionDuration).call(bars);
focusLinesWrap.transition().duration(transitionDuration).call(lines);
// Setup and Update Main (Focus) Y Axes
g.select('.nv-focus .nv-x.nv-axis')
.attr('transform', 'translate(0,' + y1.range()[0] + ')');
y1Axis
.scale(y1)
._ticks( nv.utils.calcTicksY(availableHeight1/36, data) )
.tickSize(-availableWidth, 0);
y2Axis
.scale(y2)
._ticks( nv.utils.calcTicksY(availableHeight1/36, data) );
// Show the y2 rules only if y1 has none
if(!switchYAxisOrder) {
y2Axis.tickSize(dataBars.length ? 0 : -availableWidth, 0);
} else {
y2Axis.tickSize(dataLines.length ? 0 : -availableWidth, 0);
}
// Calculate opacity of the axis
var barsOpacity = dataBars.length ? 1 : 0;
var linesOpacity = dataLines.length && !allDisabled(dataLines) ? 1 : 0;
var y1Opacity = switchYAxisOrder ? linesOpacity : barsOpacity;
var y2Opacity = switchYAxisOrder ? barsOpacity : linesOpacity;
g.select('.nv-focus .nv-y1.nv-axis')
.style('opacity', y1Opacity);
g.select('.nv-focus .nv-y2.nv-axis')
.style('opacity', y2Opacity)
.attr('transform', 'translate(' + x.range()[1] + ',0)');
g.select('.nv-focus .nv-y1.nv-axis').transition().duration(transitionDuration)
.call(y1Axis);
g.select('.nv-focus .nv-y2.nv-axis').transition().duration(transitionDuration)
.call(y2Axis);
}
onBrush();
});
return chart;
}
//============================================================
// Event Handling/Dispatching (out of chart's scope)
//------------------------------------------------------------
lines.dispatch.on('elementMouseover.tooltip', function(evt) {
tooltip
.duration(100)
.valueFormatter(function(d, i) {
return getLinesAxis().main.tickFormat()(d, i);
})
.data(evt)
.hidden(false);
});
lines.dispatch.on('elementMouseout.tooltip', function(evt) {
tooltip.hidden(true)
});
bars.dispatch.on('elementMouseover.tooltip', function(evt) {
evt.value = chart.x()(evt.data);
evt['series'] = {
value: chart.y()(evt.data),
color: evt.color
};
tooltip
.duration(0)
.valueFormatter(function(d, i) {
return getBarsAxis().main.tickFormat()(d, i);
})
.data(evt)
.hidden(false);
});
bars.dispatch.on('elementMouseout.tooltip', function(evt) {
tooltip.hidden(true);
});
bars.dispatch.on('elementMousemove.tooltip', function(evt) {
tooltip();
});
//============================================================
//============================================================
// Expose Public Variables
//------------------------------------------------------------
// expose chart's sub-components
chart.dispatch = dispatch;
chart.legend = legend;
chart.lines = lines;
chart.lines2 = lines2;
chart.bars = bars;
chart.bars2 = bars2;
chart.xAxis = xAxis;
chart.x2Axis = x2Axis;
chart.y1Axis = y1Axis;
chart.y2Axis = y2Axis;
chart.y3Axis = y3Axis;
chart.y4Axis = y4Axis;
chart.tooltip = tooltip;
chart.options = nv.utils.optionsFunc.bind(chart);
chart._options = Object.create({}, {
// simple options, just get/set the necessary values
width: {get: function(){return width;}, set: function(_){width=_;}},
height: {get: function(){return height;}, set: function(_){height=_;}},
showLegend: {get: function(){return showLegend;}, set: function(_){showLegend=_;}},
brushExtent: {get: function(){return brushExtent;}, set: function(_){brushExtent=_;}},
noData: {get: function(){return noData;}, set: function(_){noData=_;}},
focusEnable: {get: function(){return focusEnable;}, set: function(_){focusEnable=_;}},
focusHeight: {get: function(){return focusHeight;}, set: function(_){focusHeight=_;}},
focusShowAxisX: {get: function(){return focusShowAxisX;}, set: function(_){focusShowAxisX=_;}},
focusShowAxisY: {get: function(){return focusShowAxisY;}, set: function(_){focusShowAxisY=_;}},
legendLeftAxisHint: {get: function(){return legendLeftAxisHint;}, set: function(_){legendLeftAxisHint=_;}},
legendRightAxisHint: {get: function(){return legendRightAxisHint;}, set: function(_){legendRightAxisHint=_;}},
// options that require extra logic in the setter
margin: {get: function(){return margin;}, set: function(_){
margin.top = _.top !== undefined ? _.top : margin.top;
margin.right = _.right !== undefined ? _.right : margin.right;
margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
margin.left = _.left !== undefined ? _.left : margin.left;
}},
focusMargin: {get: function(){return margin2;}, set: function(_){
margin2.top = _.top !== undefined ? _.top : margin2.top;
margin2.right = _.right !== undefined ? _.right : margin2.right;
margin2.bottom = _.bottom !== undefined ? _.bottom : margin2.bottom;
margin2.left = _.left !== undefined ? _.left : margin2.left;
}},
duration: {get: function(){return transitionDuration;}, set: function(_){
transitionDuration = _;
}},
color: {get: function(){return color;}, set: function(_){
color = nv.utils.getColor(_);
legend.color(color);
}},
x: {get: function(){return getX;}, set: function(_){
getX = _;
lines.x(_);
lines2.x(_);
bars.x(_);
bars2.x(_);
}},
y: {get: function(){return getY;}, set: function(_){
getY = _;
lines.y(_);
lines2.y(_);
bars.y(_);
bars2.y(_);
}},
switchYAxisOrder: {get: function(){return switchYAxisOrder;}, set: function(_){
// Switch the tick format for the yAxis
if(switchYAxisOrder !== _) {
var y1 = y1Axis;
y1Axis = y2Axis;
y2Axis = y1;
var y3 = y3Axis;
y3Axis = y4Axis;
y4Axis = y3;
}
switchYAxisOrder=_;
y1Axis.orient('left');
y2Axis.orient('right');
y3Axis.orient('left');
y4Axis.orient('right');
}}
});
nv.utils.inheritOptions(chart, lines);
nv.utils.initOptions(chart);
return chart;
};
nv.models.multiBar = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var margin = {top: 0, right: 0, bottom: 0, left: 0}
, width = 960
, height = 500
, x = d3.scale.ordinal()
, y = d3.scale.linear()
, id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one
, container = null
, getX = function(d) { return d.x }
, getY = function(d) { return d.y }
, forceY = [0] // 0 is forced by default.. this makes sense for the majority of bar graphs... user can always do chart.forceY([]) to remove
, clipEdge = true
, stacked = false
, stackOffset = 'zero' // options include 'silhouette', 'wiggle', 'expand', 'zero', or a custom function
, color = nv.utils.defaultColor()
, hideable = false
, barColor = null // adding the ability to set the color for each rather than the whole group
, disabled // used in conjunction with barColor to communicate from multiBarHorizontalChart what series are disabled
, duration = 500
, xDomain
, yDomain
, xRange
, yRange
, groupSpacing = 0.1
, fillOpacity = 0.75
, dispatch = d3.dispatch('chartClick', 'elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout', 'elementMousemove', 'renderEnd')
;
//============================================================
// Private Variables
//------------------------------------------------------------
var x0, y0 //used to store previous scales
, renderWatch = nv.utils.renderWatch(dispatch, duration)
;
var last_datalength = 0;
function chart(selection) {
renderWatch.reset();
selection.each(function(data) {
var availableWidth = width - margin.left - margin.right,
availableHeight = height - margin.top - margin.bottom;
container = d3.select(this);
nv.utils.initSVG(container);
var nonStackableCount = 0;
// This function defines the requirements for render complete
var endFn = function(d, i) {
if (d.series === data.length - 1 && i === data[0].values.length - 1)
return true;
return false;
};
if(hideable && data.length) hideable = [{
values: data[0].values.map(function(d) {
return {
x: d.x,
y: 0,
series: d.series,
size: 0.01
};}
)}];
if (stacked) {
var parsed = d3.layout.stack()
.offset(stackOffset)
.values(function(d){ return d.values })
.y(getY)
(!data.length && hideable ? hideable : data);
parsed.forEach(function(series, i){
// if series is non-stackable, use un-parsed data
if (series.nonStackable) {
data[i].nonStackableSeries = nonStackableCount++;
parsed[i] = data[i];
} else {
// don't stack this seires on top of the nonStackable seriees
if (i > 0 && parsed[i - 1].nonStackable){
parsed[i].values.map(function(d,j){
d.y0 -= parsed[i - 1].values[j].y;
d.y1 = d.y0 + d.y;
});
}
}
});
data = parsed;
}
//add series index and key to each data point for reference
data.forEach(function(series, i) {
series.values.forEach(function(point) {
point.series = i;
point.key = series.key;
});
});
// HACK for negative value stacking
if (stacked && data.length > 0) {
data[0].values.map(function(d,i) {
var posBase = 0, negBase = 0;
data.map(function(d, idx) {
if (!data[idx].nonStackable) {
var f = d.values[i]
f.size = Math.abs(f.y);
if (f.y<0) {
f.y1 = negBase;
negBase = negBase - f.size;
} else
{
f.y1 = f.size + posBase;
posBase = posBase + f.size;
}
}
});
});
}
// Setup Scales
// remap and flatten the data for use in calculating the scales' domains
var seriesData = (xDomain && yDomain) ? [] : // if we know xDomain and yDomain, no need to calculate
data.map(function(d, idx) {
return d.values.map(function(d,i) {
return { x: getX(d,i), y: getY(d,i), y0: d.y0, y1: d.y1, idx:idx }
})
});
x.domain(xDomain || d3.merge(seriesData).map(function(d) { return d.x }))
.rangeBands(xRange || [0, availableWidth], groupSpacing);
y.domain(yDomain || d3.extent(d3.merge(seriesData).map(function(d) {
var domain = d.y;
// increase the domain range if this series is stackable
if (stacked && !data[d.idx].nonStackable) {
if (d.y > 0){
domain = d.y1
} else {
domain = d.y1 + d.y
}
}
return domain;
}).concat(forceY)))
.range(yRange || [availableHeight, 0]);
// If scale's domain don't have a range, slightly adjust to make one... so a chart can show a single data point
if (x.domain()[0] === x.domain()[1])
x.domain()[0] ?
x.domain([x.domain()[0] - x.domain()[0] * 0.01, x.domain()[1] + x.domain()[1] * 0.01])
: x.domain([-1,1]);
if (y.domain()[0] === y.domain()[1])
y.domain()[0] ?
y.domain([y.domain()[0] + y.domain()[0] * 0.01, y.domain()[1] - y.domain()[1] * 0.01])
: y.domain([-1,1]);
x0 = x0 || x;
y0 = y0 || y;
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-multibar').data([data]);
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-multibar');
var defsEnter = wrapEnter.append('defs');
var gEnter = wrapEnter.append('g');
var g = wrap.select('g');
gEnter.append('g').attr('class', 'nv-groups');
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
defsEnter.append('clipPath')
.attr('id', 'nv-edge-clip-' + id)
.append('rect');
wrap.select('#nv-edge-clip-' + id + ' rect')
.attr('width', availableWidth)
.attr('height', availableHeight);
g.attr('clip-path', clipEdge ? 'url(#nv-edge-clip-' + id + ')' : '');
var groups = wrap.select('.nv-groups').selectAll('.nv-group')
.data(function(d) { return d }, function(d,i) { return i });
groups.enter().append('g')
.style('stroke-opacity', 1e-6)
.style('fill-opacity', 1e-6);
var exitTransition = renderWatch
.transition(groups.exit().selectAll('rect.nv-bar'), 'multibarExit', Math.min(100, duration))
.attr('y', function(d, i, j) {
var yVal = y0(0) || 0;
if (stacked) {
if (data[d.series] && !data[d.series].nonStackable) {
yVal = y0(d.y0);
}
}
return yVal;
})
.attr('height', 0)
.remove();
if (exitTransition.delay)
exitTransition.delay(function(d,i) {
var delay = i * (duration / (last_datalength + 1)) - i;
return delay;
});
groups
.attr('class', function(d,i) { return 'nv-group nv-series-' + i })
.classed('hover', function(d) { return d.hover })
.style('fill', function(d,i){ return color(d, i) })
.style('stroke', function(d,i){ return color(d, i) });
groups
.style('stroke-opacity', 1)
.style('fill-opacity', fillOpacity);
var bars = groups.selectAll('rect.nv-bar')
.data(function(d) { return (hideable && !data.length) ? hideable.values : d.values });
bars.exit().remove();
var barsEnter = bars.enter().append('rect')
.attr('class', function(d,i) { return getY(d,i) < 0 ? 'nv-bar negative' : 'nv-bar positive'})
.attr('x', function(d,i,j) {
return stacked && !data[j].nonStackable ? 0 : (j * x.rangeBand() / data.length )
})
.attr('y', function(d,i,j) { return y0(stacked && !data[j].nonStackable ? d.y0 : 0) || 0 })
.attr('height', 0)
.attr('width', function(d,i,j) { return x.rangeBand() / (stacked && !data[j].nonStackable ? 1 : data.length) })
.attr('transform', function(d,i) { return 'translate(' + x(getX(d,i)) + ',0)'; })
;
bars
.style('fill', function(d,i,j){ return color(d, j, i); })
.style('stroke', function(d,i,j){ return color(d, j, i); })
.on('mouseover', function(d,i) { //TODO: figure out why j works above, but not here
d3.select(this).classed('hover', true);
dispatch.elementMouseover({
data: d,
index: i,
color: d3.select(this).style("fill")
});
})
.on('mouseout', function(d,i) {
d3.select(this).classed('hover', false);
dispatch.elementMouseout({
data: d,
index: i,
color: d3.select(this).style("fill")
});
})
.on('mousemove', function(d,i) {
dispatch.elementMousemove({
data: d,
index: i,
color: d3.select(this).style("fill")
});
})
.on('click', function(d,i) {
var element = this;
dispatch.elementClick({
data: d,
index: i,
color: d3.select(this).style("fill"),
event: d3.event,
element: element
});
d3.event.stopPropagation();
})
.on('dblclick', function(d,i) {
dispatch.elementDblClick({
data: d,
index: i,
color: d3.select(this).style("fill")
});
d3.event.stopPropagation();
});
bars
.attr('class', function(d,i) { return getY(d,i) < 0 ? 'nv-bar negative' : 'nv-bar positive'})
.attr('transform', function(d,i) { return 'translate(' + x(getX(d,i)) + ',0)'; })
if (barColor) {
if (!disabled) disabled = data.map(function() { return true });
bars
.style('fill', function(d,i,j) { return d3.rgb(barColor(d,i)).darker( disabled.map(function(d,i) { return i }).filter(function(d,i){ return !disabled[i] })[j] ).toString(); })
.style('stroke', function(d,i,j) { return d3.rgb(barColor(d,i)).darker( disabled.map(function(d,i) { return i }).filter(function(d,i){ return !disabled[i] })[j] ).toString(); });
}
var barSelection =
bars.watchTransition(renderWatch, 'multibar', Math.min(250, duration))
.delay(function(d,i) {
return i * duration / data[0].values.length;
});
if (stacked){
barSelection
.attr('y', function(d,i,j) {
var yVal = 0;
// if stackable, stack it on top of the previous series
if (!data[j].nonStackable) {
yVal = y(d.y1);
} else {
if (getY(d,i) < 0){
yVal = y(0);
} else {
if (y(0) - y(getY(d,i)) < -1){
yVal = y(0) - 1;
} else {
yVal = y(getY(d, i)) || 0;
}
}
}
return yVal;
})
.attr('height', function(d,i,j) {
if (!data[j].nonStackable) {
return Math.max(Math.abs(y(d.y+d.y0) - y(d.y0)), 0);
} else {
return Math.max(Math.abs(y(getY(d,i)) - y(0)), 0) || 0;
}
})
.attr('x', function(d,i,j) {
var width = 0;
if (data[j].nonStackable) {
width = d.series * x.rangeBand() / data.length;
if (data.length !== nonStackableCount){
width = data[j].nonStackableSeries * x.rangeBand()/(nonStackableCount*2);
}
}
return width;
})
.attr('width', function(d,i,j){
if (!data[j].nonStackable) {
return x.rangeBand();
} else {
// if all series are nonStacable, take the full width
var width = (x.rangeBand() / nonStackableCount);
// otherwise, nonStackable graph will be only taking the half-width
// of the x rangeBand
if (data.length !== nonStackableCount) {
width = x.rangeBand()/(nonStackableCount*2);
}
return width;
}
});
}
else {
barSelection
.attr('x', function(d,i) {
return d.series * x.rangeBand() / data.length;
})
.attr('width', x.rangeBand() / data.length)
.attr('y', function(d,i) {
return getY(d,i) < 0 ?
y(0) :
y(0) - y(getY(d,i)) < 1 ?
y(0) - 1 :
y(getY(d,i)) || 0;
})
.attr('height', function(d,i) {
return Math.max(Math.abs(y(getY(d,i)) - y(0)),1) || 0;
});
}
//store old scales for use in transitions on update
x0 = x.copy();
y0 = y.copy();
// keep track of the last data value length for transition calculations
if (data[0] && data[0].values) {
last_datalength = data[0].values.length;
}
});
renderWatch.renderEnd('multibar immediate');
return chart;
}
//============================================================
// Expose Public Variables
//------------------------------------------------------------
chart.dispatch = dispatch;
chart.options = nv.utils.optionsFunc.bind(chart);
chart._options = Object.create({}, {
// simple options, just get/set the necessary values
width: {get: function(){return width;}, set: function(_){width=_;}},
height: {get: function(){return height;}, set: function(_){height=_;}},
x: {get: function(){return getX;}, set: function(_){getX=_;}},
y: {get: function(){return getY;}, set: function(_){getY=_;}},
xScale: {get: function(){return x;}, set: function(_){x=_;}},
yScale: {get: function(){return y;}, set: function(_){y=_;}},
xDomain: {get: function(){return xDomain;}, set: function(_){xDomain=_;}},
yDomain: {get: function(){return yDomain;}, set: function(_){yDomain=_;}},
xRange: {get: function(){return xRange;}, set: function(_){xRange=_;}},
yRange: {get: function(){return yRange;}, set: function(_){yRange=_;}},
forceY: {get: function(){return forceY;}, set: function(_){forceY=_;}},
stacked: {get: function(){return stacked;}, set: function(_){stacked=_;}},
stackOffset: {get: function(){return stackOffset;}, set: function(_){stackOffset=_;}},
clipEdge: {get: function(){return clipEdge;}, set: function(_){clipEdge=_;}},
disabled: {get: function(){return disabled;}, set: function(_){disabled=_;}},
id: {get: function(){return id;}, set: function(_){id=_;}},
hideable: {get: function(){return hideable;}, set: function(_){hideable=_;}},
groupSpacing:{get: function(){return groupSpacing;}, set: function(_){groupSpacing=_;}},
fillOpacity: {get: function(){return fillOpacity;}, set: function(_){fillOpacity=_;}},
// options that require extra logic in the setter
margin: {get: function(){return margin;}, set: function(_){
margin.top = _.top !== undefined ? _.top : margin.top;
margin.right = _.right !== undefined ? _.right : margin.right;
margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
margin.left = _.left !== undefined ? _.left : margin.left;
}},
duration: {get: function(){return duration;}, set: function(_){
duration = _;
renderWatch.reset(duration);
}},
color: {get: function(){return color;}, set: function(_){
color = nv.utils.getColor(_);
}},
barColor: {get: function(){return barColor;}, set: function(_){
barColor = _ ? nv.utils.getColor(_) : null;
}}
});
nv.utils.initOptions(chart);
return chart;
};
nv.models.multiBarChart = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var multibar = nv.models.multiBar()
, xAxis = nv.models.axis()
, yAxis = nv.models.axis()
, interactiveLayer = nv.interactiveGuideline()
, legend = nv.models.legend()
, controls = nv.models.legend()
, tooltip = nv.models.tooltip()
;
var margin = {top: 30, right: 20, bottom: 50, left: 60}
, width = null
, height = null
, color = nv.utils.defaultColor()
, showControls = true
, controlLabels = {}
, showLegend = true
, showXAxis = true
, showYAxis = true
, rightAlignYAxis = false
, reduceXTicks = true // if false a tick will show for every data point
, staggerLabels = false
, wrapLabels = false
, rotateLabels = 0
, x //can be accessed via chart.xScale()
, y //can be accessed via chart.yScale()
, state = nv.utils.state()
, defaultState = null
, noData = null
, dispatch = d3.dispatch('stateChange', 'changeState', 'renderEnd')
, controlWidth = function() { return showControls ? 180 : 0 }
, duration = 250
, useInteractiveGuideline = false
;
state.stacked = false // DEPRECATED Maintained for backward compatibility
multibar.stacked(false);
xAxis
.orient('bottom')
.tickPadding(7)
.showMaxMin(false)
.tickFormat(function(d) { return d })
;
yAxis
.orient((rightAlignYAxis) ? 'right' : 'left')
.tickFormat(d3.format(',.1f'))
;
tooltip
.duration(0)
.valueFormatter(function(d, i) {
return yAxis.tickFormat()(d, i);
})
.headerFormatter(function(d, i) {
return xAxis.tickFormat()(d, i);
});
controls.updateState(false);
//============================================================
// Private Variables
//------------------------------------------------------------
var renderWatch = nv.utils.renderWatch(dispatch);
var stacked = false;
var stateGetter = function(data) {
return function(){
return {
active: data.map(function(d) { return !d.disabled }),
stacked: stacked
};
}
};
var stateSetter = function(data) {
return function(state) {
if (state.stacked !== undefined)
stacked = state.stacked;
if (state.active !== undefined)
data.forEach(function(series,i) {
series.disabled = !state.active[i];
});
}
};
function chart(selection) {
renderWatch.reset();
renderWatch.models(multibar);
if (showXAxis) renderWatch.models(xAxis);
if (showYAxis) renderWatch.models(yAxis);
selection.each(function(data) {
var container = d3.select(this),
that = this;
nv.utils.initSVG(container);
var availableWidth = nv.utils.availableWidth(width, container, margin),
availableHeight = nv.utils.availableHeight(height, container, margin);
chart.update = function() {
if (duration === 0)
container.call(chart);
else
container.transition()
.duration(duration)
.call(chart);
};
chart.container = this;
state
.setter(stateSetter(data), chart.update)
.getter(stateGetter(data))
.update();
// DEPRECATED set state.disableddisabled
state.disabled = data.map(function(d) { return !!d.disabled });
if (!defaultState) {
var key;
defaultState = {};
for (key in state) {
if (state[key] instanceof Array)
defaultState[key] = state[key].slice(0);
else
defaultState[key] = state[key];
}
}
// Display noData message if there's nothing to show.
if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) {
nv.utils.noData(chart, container)
return chart;
} else {
container.selectAll('.nv-noData').remove();
}
// Setup Scales
x = multibar.xScale();
y = multibar.yScale();
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-multiBarWithLegend').data([data]);
var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-multiBarWithLegend').append('g');
var g = wrap.select('g');
gEnter.append('g').attr('class', 'nv-x nv-axis');
gEnter.append('g').attr('class', 'nv-y nv-axis');
gEnter.append('g').attr('class', 'nv-barsWrap');
gEnter.append('g').attr('class', 'nv-legendWrap');
gEnter.append('g').attr('class', 'nv-controlsWrap');
gEnter.append('g').attr('class', 'nv-interactive');
// Legend
if (!showLegend) {
g.select('.nv-legendWrap').selectAll('*').remove();
} else {
legend.width(availableWidth - controlWidth());
g.select('.nv-legendWrap')
.datum(data)
.call(legend);
if ( margin.top != legend.height()) {
margin.top = legend.height();
availableHeight = nv.utils.availableHeight(height, container, margin);
}
g.select('.nv-legendWrap')
.attr('transform', 'translate(' + controlWidth() + ',' + (-margin.top) +')');
}
// Controls
if (!showControls) {
g.select('.nv-controlsWrap').selectAll('*').remove();
} else {
var controlsData = [
{ key: controlLabels.grouped || 'Grouped', disabled: multibar.stacked() },
{ key: controlLabels.stacked || 'Stacked', disabled: !multibar.stacked() }
];
controls.width(controlWidth()).color(['#444', '#444', '#444']);
g.select('.nv-controlsWrap')
.datum(controlsData)
.attr('transform', 'translate(0,' + (-margin.top) +')')
.call(controls);
}
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
if (rightAlignYAxis) {
g.select(".nv-y.nv-axis")
.attr("transform", "translate(" + availableWidth + ",0)");
}
// Main Chart Component(s)
multibar
.disabled(data.map(function(series) { return series.disabled }))
.width(availableWidth)
.height(availableHeight)
.color(data.map(function(d,i) {
return d.color || color(d, i);
}).filter(function(d,i) { return !data[i].disabled }));
var barsWrap = g.select('.nv-barsWrap')
.datum(data.filter(function(d) { return !d.disabled }));
barsWrap.call(multibar);
// Setup Axes
if (showXAxis) {
xAxis
.scale(x)
._ticks( nv.utils.calcTicksX(availableWidth/100, data) )
.tickSize(-availableHeight, 0);
g.select('.nv-x.nv-axis')
.attr('transform', 'translate(0,' + y.range()[0] + ')');
g.select('.nv-x.nv-axis')
.call(xAxis);
var xTicks = g.select('.nv-x.nv-axis > g').selectAll('g');
xTicks
.selectAll('line, text')
.style('opacity', 1)
if (staggerLabels) {
var getTranslate = function(x,y) {
return "translate(" + x + "," + y + ")";
};
var staggerUp = 5, staggerDown = 17; //pixels to stagger by
// Issue #140
xTicks
.selectAll("text")
.attr('transform', function(d,i,j) {
return getTranslate(0, (j % 2 == 0 ? staggerUp : staggerDown));
});
var totalInBetweenTicks = d3.selectAll(".nv-x.nv-axis .nv-wrap g g text")[0].length;
g.selectAll(".nv-x.nv-axis .nv-axisMaxMin text")
.attr("transform", function(d,i) {
return getTranslate(0, (i === 0 || totalInBetweenTicks % 2 !== 0) ? staggerDown : staggerUp);
});
}
if (wrapLabels) {
g.selectAll('.tick text')
.call(nv.utils.wrapTicks, chart.xAxis.rangeBand())
}
if (reduceXTicks)
xTicks
.filter(function(d,i) {
return i % Math.ceil(data[0].values.length / (availableWidth / 100)) !== 0;
})
.selectAll('text, line')
.style('opacity', 0);
if(rotateLabels)
xTicks
.selectAll('.tick text')
.attr('transform', 'rotate(' + rotateLabels + ' 0,0)')
.style('text-anchor', rotateLabels > 0 ? 'start' : 'end');
g.select('.nv-x.nv-axis').selectAll('g.nv-axisMaxMin text')
.style('opacity', 1);
}
if (showYAxis) {
yAxis
.scale(y)
._ticks( nv.utils.calcTicksY(availableHeight/36, data) )
.tickSize( -availableWidth, 0);
g.select('.nv-y.nv-axis')
.call(yAxis);
}
//Set up interactive layer
if (useInteractiveGuideline) {
interactiveLayer
.width(availableWidth)
.height(availableHeight)
.margin({left:margin.left, top:margin.top})
.svgContainer(container)
.xScale(x);
wrap.select(".nv-interactive").call(interactiveLayer);
}
//============================================================
// Event Handling/Dispatching (in chart's scope)
//------------------------------------------------------------
legend.dispatch.on('stateChange', function(newState) {
for (var key in newState)
state[key] = newState[key];
dispatch.stateChange(state);
chart.update();
});
controls.dispatch.on('legendClick', function(d,i) {
if (!d.disabled) return;
controlsData = controlsData.map(function(s) {
s.disabled = true;
return s;
});
d.disabled = false;
switch (d.key) {
case 'Grouped':
case controlLabels.grouped:
multibar.stacked(false);
break;
case 'Stacked':
case controlLabels.stacked:
multibar.stacked(true);
break;
}
state.stacked = multibar.stacked();
dispatch.stateChange(state);
chart.update();
});
// Update chart from a state object passed to event handler
dispatch.on('changeState', function(e) {
if (typeof e.disabled !== 'undefined') {
data.forEach(function(series,i) {
series.disabled = e.disabled[i];
});
state.disabled = e.disabled;
}
if (typeof e.stacked !== 'undefined') {
multibar.stacked(e.stacked);
state.stacked = e.stacked;
stacked = e.stacked;
}
chart.update();
});
if (useInteractiveGuideline) {
interactiveLayer.dispatch.on('elementMousemove', function(e) {
if (e.pointXValue == undefined) return;
var singlePoint, pointIndex, pointXLocation, xValue, allData = [];
data
.filter(function(series, i) {
series.seriesIndex = i;
return !series.disabled;
})
.forEach(function(series,i) {
pointIndex = x.domain().indexOf(e.pointXValue)
var point = series.values[pointIndex];
if (point === undefined) return;
xValue = point.x;
if (singlePoint === undefined) singlePoint = point;
if (pointXLocation === undefined) pointXLocation = e.mouseX
allData.push({
key: series.key,
value: chart.y()(point, pointIndex),
color: color(series,series.seriesIndex),
data: series.values[pointIndex]
});
});
interactiveLayer.tooltip
.chartContainer(that.parentNode)
.data({
value: xValue,
index: pointIndex,
series: allData
})();
interactiveLayer.renderGuideLine(pointXLocation);
});
interactiveLayer.dispatch.on("elementMouseout",function(e) {
interactiveLayer.tooltip.hidden(true);
});
}
else {
multibar.dispatch.on('elementMouseover.tooltip', function(evt) {
evt.value = chart.x()(evt.data);
evt['series'] = {
key: evt.data.key,
value: chart.y()(evt.data),
color: evt.color
};
tooltip.data(evt).hidden(false);
});
multibar.dispatch.on('elementMouseout.tooltip', function(evt) {
tooltip.hidden(true);
});
multibar.dispatch.on('elementMousemove.tooltip', function(evt) {
tooltip();
});
}
});
renderWatch.renderEnd('multibarchart immediate');
return chart;
}
//============================================================
// Expose Public Variables
//------------------------------------------------------------
// expose chart's sub-components
chart.dispatch = dispatch;
chart.multibar = multibar;
chart.legend = legend;
chart.controls = controls;
chart.xAxis = xAxis;
chart.yAxis = yAxis;
chart.state = state;
chart.tooltip = tooltip;
chart.interactiveLayer = interactiveLayer;
chart.options = nv.utils.optionsFunc.bind(chart);
chart._options = Object.create({}, {
// simple options, just get/set the necessary values
width: {get: function(){return width;}, set: function(_){width=_;}},
height: {get: function(){return height;}, set: function(_){height=_;}},
showLegend: {get: function(){return showLegend;}, set: function(_){showLegend=_;}},
showControls: {get: function(){return showControls;}, set: function(_){showControls=_;}},
controlLabels: {get: function(){return controlLabels;}, set: function(_){controlLabels=_;}},
showXAxis: {get: function(){return showXAxis;}, set: function(_){showXAxis=_;}},
showYAxis: {get: function(){return showYAxis;}, set: function(_){showYAxis=_;}},
defaultState: {get: function(){return defaultState;}, set: function(_){defaultState=_;}},
noData: {get: function(){return noData;}, set: function(_){noData=_;}},
reduceXTicks: {get: function(){return reduceXTicks;}, set: function(_){reduceXTicks=_;}},
rotateLabels: {get: function(){return rotateLabels;}, set: function(_){rotateLabels=_;}},
staggerLabels: {get: function(){return staggerLabels;}, set: function(_){staggerLabels=_;}},
wrapLabels: {get: function(){return wrapLabels;}, set: function(_){wrapLabels=!!_;}},
// options that require extra logic in the setter
margin: {get: function(){return margin;}, set: function(_){
margin.top = _.top !== undefined ? _.top : margin.top;
margin.right = _.right !== undefined ? _.right : margin.right;
margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
margin.left = _.left !== undefined ? _.left : margin.left;
}},
duration: {get: function(){return duration;}, set: function(_){
duration = _;
multibar.duration(duration);
xAxis.duration(duration);
yAxis.duration(duration);
renderWatch.reset(duration);
}},
color: {get: function(){return color;}, set: function(_){
color = nv.utils.getColor(_);
legend.color(color);
}},
rightAlignYAxis: {get: function(){return rightAlignYAxis;}, set: function(_){
rightAlignYAxis = _;
yAxis.orient( rightAlignYAxis ? 'right' : 'left');
}},
useInteractiveGuideline: {get: function(){return useInteractiveGuideline;}, set: function(_){
useInteractiveGuideline = _;
}},
barColor: {get: function(){return multibar.barColor;}, set: function(_){
multibar.barColor(_);
legend.color(function(d,i) {return d3.rgb('#ccc').darker(i * 1.5).toString();})
}}
});
nv.utils.inheritOptions(chart, multibar);
nv.utils.initOptions(chart);
return chart;
};
nv.models.multiBarHorizontal = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var margin = {top: 0, right: 0, bottom: 0, left: 0}
, width = 960
, height = 500
, id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one
, container = null
, x = d3.scale.ordinal()
, y = d3.scale.linear()
, getX = function(d) { return d.x }
, getY = function(d) { return d.y }
, getYerr = function(d) { return d.yErr }
, forceY = [0] // 0 is forced by default.. this makes sense for the majority of bar graphs... user can always do chart.forceY([]) to remove
, color = nv.utils.defaultColor()
, barColor = null // adding the ability to set the color for each rather than the whole group
, disabled // used in conjunction with barColor to communicate from multiBarHorizontalChart what series are disabled
, stacked = false
, showValues = false
, showBarLabels = false
, valuePadding = 60
, groupSpacing = 0.1
, fillOpacity = 0.75
, valueFormat = d3.format(',.2f')
, delay = 1200
, xDomain
, yDomain
, xRange
, yRange
, duration = 250
, dispatch = d3.dispatch('chartClick', 'elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout', 'elementMousemove', 'renderEnd')
;
//============================================================
// Private Variables
//------------------------------------------------------------
var x0, y0; //used to store previous scales
var renderWatch = nv.utils.renderWatch(dispatch, duration);
function chart(selection) {
renderWatch.reset();
selection.each(function(data) {
var availableWidth = width - margin.left - margin.right,
availableHeight = height - margin.top - margin.bottom;
container = d3.select(this);
nv.utils.initSVG(container);
if (stacked)
data = d3.layout.stack()
.offset('zero')
.values(function(d){ return d.values })
.y(getY)
(data);
//add series index and key to each data point for reference
data.forEach(function(series, i) {
series.values.forEach(function(point) {
point.series = i;
point.key = series.key;
});
});
// HACK for negative value stacking
if (stacked)
data[0].values.map(function(d,i) {
var posBase = 0, negBase = 0;
data.map(function(d) {
var f = d.values[i]
f.size = Math.abs(f.y);
if (f.y<0) {
f.y1 = negBase - f.size;
negBase = negBase - f.size;
} else
{
f.y1 = posBase;
posBase = posBase + f.size;
}
});
});
// Setup Scales
// remap and flatten the data for use in calculating the scales' domains
var seriesData = (xDomain && yDomain) ? [] : // if we know xDomain and yDomain, no need to calculate
data.map(function(d) {
return d.values.map(function(d,i) {
return { x: getX(d,i), y: getY(d,i), y0: d.y0, y1: d.y1 }
})
});
x.domain(xDomain || d3.merge(seriesData).map(function(d) { return d.x }))
.rangeBands(xRange || [0, availableHeight], groupSpacing);
y.domain(yDomain || d3.extent(d3.merge(seriesData).map(function(d) { return stacked ? (d.y > 0 ? d.y1 + d.y : d.y1 ) : d.y }).concat(forceY)))
if (showValues && !stacked)
y.range(yRange || [(y.domain()[0] < 0 ? valuePadding : 0), availableWidth - (y.domain()[1] > 0 ? valuePadding : 0) ]);
else
y.range(yRange || [0, availableWidth]);
x0 = x0 || x;
y0 = y0 || d3.scale.linear().domain(y.domain()).range([y(0),y(0)]);
// Setup containers and skeleton of chart
var wrap = d3.select(this).selectAll('g.nv-wrap.nv-multibarHorizontal').data([data]);
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-multibarHorizontal');
var defsEnter = wrapEnter.append('defs');
var gEnter = wrapEnter.append('g');
var g = wrap.select('g');
gEnter.append('g').attr('class', 'nv-groups');
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
var groups = wrap.select('.nv-groups').selectAll('.nv-group')
.data(function(d) { return d }, function(d,i) { return i });
groups.enter().append('g')
.style('stroke-opacity', 1e-6)
.style('fill-opacity', 1e-6);
groups.exit().watchTransition(renderWatch, 'multibarhorizontal: exit groups')
.style('stroke-opacity', 1e-6)
.style('fill-opacity', 1e-6)
.remove();
groups
.attr('class', function(d,i) { return 'nv-group nv-series-' + i })
.classed('hover', function(d) { return d.hover })
.style('fill', function(d,i){ return color(d, i) })
.style('stroke', function(d,i){ return color(d, i) });
groups.watchTransition(renderWatch, 'multibarhorizontal: groups')
.style('stroke-opacity', 1)
.style('fill-opacity', fillOpacity);
var bars = groups.selectAll('g.nv-bar')
.data(function(d) { return d.values });
bars.exit().remove();
var barsEnter = bars.enter().append('g')
.attr('transform', function(d,i,j) {
return 'translate(' + y0(stacked ? d.y0 : 0) + ',' + (stacked ? 0 : (j * x.rangeBand() / data.length ) + x(getX(d,i))) + ')'
});
barsEnter.append('rect')
.attr('width', 0)
.attr('height', x.rangeBand() / (stacked ? 1 : data.length) )
bars
.on('mouseover', function(d,i) { //TODO: figure out why j works above, but not here
d3.select(this).classed('hover', true);
dispatch.elementMouseover({
data: d,
index: i,
color: d3.select(this).style("fill")
});
})
.on('mouseout', function(d,i) {
d3.select(this).classed('hover', false);
dispatch.elementMouseout({
data: d,
index: i,
color: d3.select(this).style("fill")
});
})
.on('mouseout', function(d,i) {
dispatch.elementMouseout({
data: d,
index: i,
color: d3.select(this).style("fill")
});
})
.on('mousemove', function(d,i) {
dispatch.elementMousemove({
data: d,
index: i,
color: d3.select(this).style("fill")
});
})
.on('click', function(d,i) {
var element = this;
dispatch.elementClick({
data: d,
index: i,
color: d3.select(this).style("fill"),
event: d3.event,
element: element
});
d3.event.stopPropagation();
})
.on('dblclick', function(d,i) {
dispatch.elementDblClick({
data: d,
index: i,
color: d3.select(this).style("fill")
});
d3.event.stopPropagation();
});
if (getYerr(data[0],0)) {
barsEnter.append('polyline');
bars.select('polyline')
.attr('fill', 'none')
.attr('points', function(d,i) {
var xerr = getYerr(d,i)
, mid = 0.8 * x.rangeBand() / ((stacked ? 1 : data.length) * 2);
xerr = xerr.length ? xerr : [-Math.abs(xerr), Math.abs(xerr)];
xerr = xerr.map(function(e) { return y(e) - y(0); });
var a = [[xerr[0],-mid], [xerr[0],mid], [xerr[0],0], [xerr[1],0], [xerr[1],-mid], [xerr[1],mid]];
return a.map(function (path) { return path.join(',') }).join(' ');
})
.attr('transform', function(d,i) {
var mid = x.rangeBand() / ((stacked ? 1 : data.length) * 2);
return 'translate(' + (getY(d,i) < 0 ? 0 : y(getY(d,i)) - y(0)) + ', ' + mid + ')'
});
}
barsEnter.append('text');
if (showValues && !stacked) {
bars.select('text')
.attr('text-anchor', function(d,i) { return getY(d,i) < 0 ? 'end' : 'start' })
.attr('y', x.rangeBand() / (data.length * 2))
.attr('dy', '.32em')
.text(function(d,i) {
var t = valueFormat(getY(d,i))
, yerr = getYerr(d,i);
if (yerr === undefined)
return t;
if (!yerr.length)
return t + '±' + valueFormat(Math.abs(yerr));
return t + '+' + valueFormat(Math.abs(yerr[1])) + '-' + valueFormat(Math.abs(yerr[0]));
});
bars.watchTransition(renderWatch, 'multibarhorizontal: bars')
.select('text')
.attr('x', function(d,i) { return getY(d,i) < 0 ? -4 : y(getY(d,i)) - y(0) + 4 })
} else {
bars.selectAll('text').text('');
}
if (showBarLabels && !stacked) {
barsEnter.append('text').classed('nv-bar-label',true);
bars.select('text.nv-bar-label')
.attr('text-anchor', function(d,i) { return getY(d,i) < 0 ? 'start' : 'end' })
.attr('y', x.rangeBand() / (data.length * 2))
.attr('dy', '.32em')
.text(function(d,i) { return getX(d,i) });
bars.watchTransition(renderWatch, 'multibarhorizontal: bars')
.select('text.nv-bar-label')
.attr('x', function(d,i) { return getY(d,i) < 0 ? y(0) - y(getY(d,i)) + 4 : -4 });
}
else {
bars.selectAll('text.nv-bar-label').text('');
}
bars
.attr('class', function(d,i) { return getY(d,i) < 0 ? 'nv-bar negative' : 'nv-bar positive'})
if (barColor) {
if (!disabled) disabled = data.map(function() { return true });
bars
.style('fill', function(d,i,j) { return d3.rgb(barColor(d,i)).darker( disabled.map(function(d,i) { return i }).filter(function(d,i){ return !disabled[i] })[j] ).toString(); })
.style('stroke', function(d,i,j) { return d3.rgb(barColor(d,i)).darker( disabled.map(function(d,i) { return i }).filter(function(d,i){ return !disabled[i] })[j] ).toString(); });
}
if (stacked)
bars.watchTransition(renderWatch, 'multibarhorizontal: bars')
.attr('transform', function(d,i) {
return 'translate(' + y(d.y1) + ',' + x(getX(d,i)) + ')'
})
.select('rect')
.attr('width', function(d,i) {
return Math.abs(y(getY(d,i) + d.y0) - y(d.y0)) || 0
})
.attr('height', x.rangeBand() );
else
bars.watchTransition(renderWatch, 'multibarhorizontal: bars')
.attr('transform', function(d,i) {
//TODO: stacked must be all positive or all negative, not both?
return 'translate(' +
(getY(d,i) < 0 ? y(getY(d,i)) : y(0))
+ ',' +
(d.series * x.rangeBand() / data.length
+
x(getX(d,i)) )
+ ')'
})
.select('rect')
.attr('height', x.rangeBand() / data.length )
.attr('width', function(d,i) {
return Math.max(Math.abs(y(getY(d,i)) - y(0)),1) || 0
});
//store old scales for use in transitions on update
x0 = x.copy();
y0 = y.copy();
});
renderWatch.renderEnd('multibarHorizontal immediate');
return chart;
}
//============================================================
// Expose Public Variables
//------------------------------------------------------------
chart.dispatch = dispatch;
chart.options = nv.utils.optionsFunc.bind(chart);
chart._options = Object.create({}, {
// simple options, just get/set the necessary values
width: {get: function(){return width;}, set: function(_){width=_;}},
height: {get: function(){return height;}, set: function(_){height=_;}},
x: {get: function(){return getX;}, set: function(_){getX=_;}},
y: {get: function(){return getY;}, set: function(_){getY=_;}},
yErr: {get: function(){return getYerr;}, set: function(_){getYerr=_;}},
xScale: {get: function(){return x;}, set: function(_){x=_;}},
yScale: {get: function(){return y;}, set: function(_){y=_;}},
xDomain: {get: function(){return xDomain;}, set: function(_){xDomain=_;}},
yDomain: {get: function(){return yDomain;}, set: function(_){yDomain=_;}},
xRange: {get: function(){return xRange;}, set: function(_){xRange=_;}},
yRange: {get: function(){return yRange;}, set: function(_){yRange=_;}},
forceY: {get: function(){return forceY;}, set: function(_){forceY=_;}},
stacked: {get: function(){return stacked;}, set: function(_){stacked=_;}},
showValues: {get: function(){return showValues;}, set: function(_){showValues=_;}},
// this shows the group name, seems pointless?
//showBarLabels: {get: function(){return showBarLabels;}, set: function(_){showBarLabels=_;}},
disabled: {get: function(){return disabled;}, set: function(_){disabled=_;}},
id: {get: function(){return id;}, set: function(_){id=_;}},
valueFormat: {get: function(){return valueFormat;}, set: function(_){valueFormat=_;}},
valuePadding: {get: function(){return valuePadding;}, set: function(_){valuePadding=_;}},
groupSpacing: {get: function(){return groupSpacing;}, set: function(_){groupSpacing=_;}},
fillOpacity: {get: function(){return fillOpacity;}, set: function(_){fillOpacity=_;}},
// options that require extra logic in the setter
margin: {get: function(){return margin;}, set: function(_){
margin.top = _.top !== undefined ? _.top : margin.top;
margin.right = _.right !== undefined ? _.right : margin.right;
margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
margin.left = _.left !== undefined ? _.left : margin.left;
}},
duration: {get: function(){return duration;}, set: function(_){
duration = _;
renderWatch.reset(duration);
}},
color: {get: function(){return color;}, set: function(_){
color = nv.utils.getColor(_);
}},
barColor: {get: function(){return barColor;}, set: function(_){
barColor = _ ? nv.utils.getColor(_) : null;
}}
});
nv.utils.initOptions(chart);
return chart;
};
nv.models.multiBarHorizontalChart = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var multibar = nv.models.multiBarHorizontal()
, xAxis = nv.models.axis()
, yAxis = nv.models.axis()
, legend = nv.models.legend().height(30)
, controls = nv.models.legend().height(30)
, tooltip = nv.models.tooltip()
;
var margin = {top: 30, right: 20, bottom: 50, left: 60}
, width = null
, height = null
, color = nv.utils.defaultColor()
, showControls = true
, controlLabels = {}
, showLegend = true
, showXAxis = true
, showYAxis = true
, stacked = false
, x //can be accessed via chart.xScale()
, y //can be accessed via chart.yScale()
, state = nv.utils.state()
, defaultState = null
, noData = null
, dispatch = d3.dispatch('stateChange', 'changeState','renderEnd')
, controlWidth = function() { return showControls ? 180 : 0 }
, duration = 250
;
state.stacked = false; // DEPRECATED Maintained for backward compatibility
multibar.stacked(stacked);
xAxis
.orient('left')
.tickPadding(5)
.showMaxMin(false)
.tickFormat(function(d) { return d })
;
yAxis
.orient('bottom')
.tickFormat(d3.format(',.1f'))
;
tooltip
.duration(0)
.valueFormatter(function(d, i) {
return yAxis.tickFormat()(d, i);
})
.headerFormatter(function(d, i) {
return xAxis.tickFormat()(d, i);
});
controls.updateState(false);
//============================================================
// Private Variables
//------------------------------------------------------------
var stateGetter = function(data) {
return function(){
return {
active: data.map(function(d) { return !d.disabled }),
stacked: stacked
};
}
};
var stateSetter = function(data) {
return function(state) {
if (state.stacked !== undefined)
stacked = state.stacked;
if (state.active !== undefined)
data.forEach(function(series,i) {
series.disabled = !state.active[i];
});
}
};
var renderWatch = nv.utils.renderWatch(dispatch, duration);
function chart(selection) {
renderWatch.reset();
renderWatch.models(multibar);
if (showXAxis) renderWatch.models(xAxis);
if (showYAxis) renderWatch.models(yAxis);
selection.each(function(data) {
var container = d3.select(this),
that = this;
nv.utils.initSVG(container);
var availableWidth = nv.utils.availableWidth(width, container, margin),
availableHeight = nv.utils.availableHeight(height, container, margin);
chart.update = function() { container.transition().duration(duration).call(chart) };
chart.container = this;
stacked = multibar.stacked();
state
.setter(stateSetter(data), chart.update)
.getter(stateGetter(data))
.update();
// DEPRECATED set state.disableddisabled
state.disabled = data.map(function(d) { return !!d.disabled });
if (!defaultState) {
var key;
defaultState = {};
for (key in state) {
if (state[key] instanceof Array)
defaultState[key] = state[key].slice(0);
else
defaultState[key] = state[key];
}
}
// Display No Data message if there's nothing to show.
if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) {
nv.utils.noData(chart, container)
return chart;
} else {
container.selectAll('.nv-noData').remove();
}
// Setup Scales
x = multibar.xScale();
y = multibar.yScale().clamp(true);
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-multiBarHorizontalChart').data([data]);
var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-multiBarHorizontalChart').append('g');
var g = wrap.select('g');
gEnter.append('g').attr('class', 'nv-x nv-axis');
gEnter.append('g').attr('class', 'nv-y nv-axis')
.append('g').attr('class', 'nv-zeroLine')
.append('line');
gEnter.append('g').attr('class', 'nv-barsWrap');
gEnter.append('g').attr('class', 'nv-legendWrap');
gEnter.append('g').attr('class', 'nv-controlsWrap');
// Legend
if (!showLegend) {
g.select('.nv-legendWrap').selectAll('*').remove();
} else {
legend.width(availableWidth - controlWidth());
g.select('.nv-legendWrap')
.datum(data)
.call(legend);
if ( margin.top != legend.height()) {
margin.top = legend.height();
availableHeight = nv.utils.availableHeight(height, container, margin);
}
g.select('.nv-legendWrap')
.attr('transform', 'translate(' + controlWidth() + ',' + (-margin.top) +')');
}
// Controls
if (!showControls) {
g.select('.nv-controlsWrap').selectAll('*').remove();
} else {
var controlsData = [
{ key: controlLabels.grouped || 'Grouped', disabled: multibar.stacked() },
{ key: controlLabels.stacked || 'Stacked', disabled: !multibar.stacked() }
];
controls.width(controlWidth()).color(['#444', '#444', '#444']);
g.select('.nv-controlsWrap')
.datum(controlsData)
.attr('transform', 'translate(0,' + (-margin.top) +')')
.call(controls);
}
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
// Main Chart Component(s)
multibar
.disabled(data.map(function(series) { return series.disabled }))
.width(availableWidth)
.height(availableHeight)
.color(data.map(function(d,i) {
return d.color || color(d, i);
}).filter(function(d,i) { return !data[i].disabled }));
var barsWrap = g.select('.nv-barsWrap')
.datum(data.filter(function(d) { return !d.disabled }));
barsWrap.transition().call(multibar);
// Setup Axes
if (showXAxis) {
xAxis
.scale(x)
._ticks( nv.utils.calcTicksY(availableHeight/24, data) )
.tickSize(-availableWidth, 0);
g.select('.nv-x.nv-axis').call(xAxis);
var xTicks = g.select('.nv-x.nv-axis').selectAll('g');
xTicks
.selectAll('line, text');
}
if (showYAxis) {
yAxis
.scale(y)
._ticks( nv.utils.calcTicksX(availableWidth/100, data) )
.tickSize( -availableHeight, 0);
g.select('.nv-y.nv-axis')
.attr('transform', 'translate(0,' + availableHeight + ')');
g.select('.nv-y.nv-axis').call(yAxis);
}
// Zero line
g.select(".nv-zeroLine line")
.attr("x1", y(0))
.attr("x2", y(0))
.attr("y1", 0)
.attr("y2", -availableHeight)
;
//============================================================
// Event Handling/Dispatching (in chart's scope)
//------------------------------------------------------------
legend.dispatch.on('stateChange', function(newState) {
for (var key in newState)
state[key] = newState[key];
dispatch.stateChange(state);
chart.update();
});
controls.dispatch.on('legendClick', function(d,i) {
if (!d.disabled) return;
controlsData = controlsData.map(function(s) {
s.disabled = true;
return s;
});
d.disabled = false;
switch (d.key) {
case 'Grouped':
case controlLabels.grouped:
multibar.stacked(false);
break;
case 'Stacked':
case controlLabels.stacked:
multibar.stacked(true);
break;
}
state.stacked = multibar.stacked();
dispatch.stateChange(state);
stacked = multibar.stacked();
chart.update();
});
// Update chart from a state object passed to event handler
dispatch.on('changeState', function(e) {
if (typeof e.disabled !== 'undefined') {
data.forEach(function(series,i) {
series.disabled = e.disabled[i];
});
state.disabled = e.disabled;
}
if (typeof e.stacked !== 'undefined') {
multibar.stacked(e.stacked);
state.stacked = e.stacked;
stacked = e.stacked;
}
chart.update();
});
});
renderWatch.renderEnd('multibar horizontal chart immediate');
return chart;
}
//============================================================
// Event Handling/Dispatching (out of chart's scope)
//------------------------------------------------------------
multibar.dispatch.on('elementMouseover.tooltip', function(evt) {
evt.value = chart.x()(evt.data);
evt['series'] = {
key: evt.data.key,
value: chart.y()(evt.data),
color: evt.color
};
tooltip.data(evt).hidden(false);
});
multibar.dispatch.on('elementMouseout.tooltip', function(evt) {
tooltip.hidden(true);
});
multibar.dispatch.on('elementMousemove.tooltip', function(evt) {
tooltip();
});
//============================================================
// Expose Public Variables
//------------------------------------------------------------
// expose chart's sub-components
chart.dispatch = dispatch;
chart.multibar = multibar;
chart.legend = legend;
chart.controls = controls;
chart.xAxis = xAxis;
chart.yAxis = yAxis;
chart.state = state;
chart.tooltip = tooltip;
chart.options = nv.utils.optionsFunc.bind(chart);
chart._options = Object.create({}, {
// simple options, just get/set the necessary values
width: {get: function(){return width;}, set: function(_){width=_;}},
height: {get: function(){return height;}, set: function(_){height=_;}},
showLegend: {get: function(){return showLegend;}, set: function(_){showLegend=_;}},
showControls: {get: function(){return showControls;}, set: function(_){showControls=_;}},
controlLabels: {get: function(){return controlLabels;}, set: function(_){controlLabels=_;}},
showXAxis: {get: function(){return showXAxis;}, set: function(_){showXAxis=_;}},
showYAxis: {get: function(){return showYAxis;}, set: function(_){showYAxis=_;}},
defaultState: {get: function(){return defaultState;}, set: function(_){defaultState=_;}},
noData: {get: function(){return noData;}, set: function(_){noData=_;}},
// options that require extra logic in the setter
margin: {get: function(){return margin;}, set: function(_){
margin.top = _.top !== undefined ? _.top : margin.top;
margin.right = _.right !== undefined ? _.right : margin.right;
margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
margin.left = _.left !== undefined ? _.left : margin.left;
}},
duration: {get: function(){return duration;}, set: function(_){
duration = _;
renderWatch.reset(duration);
multibar.duration(duration);
xAxis.duration(duration);
yAxis.duration(duration);
}},
color: {get: function(){return color;}, set: function(_){
color = nv.utils.getColor(_);
legend.color(color);
}},
barColor: {get: function(){return multibar.barColor;}, set: function(_){
multibar.barColor(_);
legend.color(function(d,i) {return d3.rgb('#ccc').darker(i * 1.5).toString();})
}}
});
nv.utils.inheritOptions(chart, multibar);
nv.utils.initOptions(chart);
return chart;
};
nv.models.multiChart = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var margin = {top: 30, right: 20, bottom: 50, left: 60},
color = nv.utils.defaultColor(),
width = null,
height = null,
showLegend = true,
noData = null,
yDomain1,
yDomain2,
getX = function(d) { return d.x },
getY = function(d) { return d.y},
interpolate = 'linear',
useVoronoi = true,
interactiveLayer = nv.interactiveGuideline(),
useInteractiveGuideline = false,
legendRightAxisHint = ' (right axis)'
;
//============================================================
// Private Variables
//------------------------------------------------------------
var x = d3.scale.linear(),
yScale1 = d3.scale.linear(),
yScale2 = d3.scale.linear(),
lines1 = nv.models.line().yScale(yScale1),
lines2 = nv.models.line().yScale(yScale2),
scatters1 = nv.models.scatter().yScale(yScale1),
scatters2 = nv.models.scatter().yScale(yScale2),
bars1 = nv.models.multiBar().stacked(false).yScale(yScale1),
bars2 = nv.models.multiBar().stacked(false).yScale(yScale2),
stack1 = nv.models.stackedArea().yScale(yScale1),
stack2 = nv.models.stackedArea().yScale(yScale2),
xAxis = nv.models.axis().scale(x).orient('bottom').tickPadding(5),
yAxis1 = nv.models.axis().scale(yScale1).orient('left'),
yAxis2 = nv.models.axis().scale(yScale2).orient('right'),
legend = nv.models.legend().height(30),
tooltip = nv.models.tooltip(),
dispatch = d3.dispatch();
var charts = [lines1, lines2, scatters1, scatters2, bars1, bars2, stack1, stack2];
function chart(selection) {
selection.each(function(data) {
var container = d3.select(this),
that = this;
nv.utils.initSVG(container);
chart.update = function() { container.transition().call(chart); };
chart.container = this;
var availableWidth = nv.utils.availableWidth(width, container, margin),
availableHeight = nv.utils.availableHeight(height, container, margin);
var dataLines1 = data.filter(function(d) {return d.type == 'line' && d.yAxis == 1});
var dataLines2 = data.filter(function(d) {return d.type == 'line' && d.yAxis == 2});
var dataScatters1 = data.filter(function(d) {return d.type == 'scatter' && d.yAxis == 1});
var dataScatters2 = data.filter(function(d) {return d.type == 'scatter' && d.yAxis == 2});
var dataBars1 = data.filter(function(d) {return d.type == 'bar' && d.yAxis == 1});
var dataBars2 = data.filter(function(d) {return d.type == 'bar' && d.yAxis == 2});
var dataStack1 = data.filter(function(d) {return d.type == 'area' && d.yAxis == 1});
var dataStack2 = data.filter(function(d) {return d.type == 'area' && d.yAxis == 2});
// Display noData message if there's nothing to show.
if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) {
nv.utils.noData(chart, container);
return chart;
} else {
container.selectAll('.nv-noData').remove();
}
var series1 = data.filter(function(d) {return !d.disabled && d.yAxis == 1})
.map(function(d) {
return d.values.map(function(d,i) {
return { x: getX(d), y: getY(d) }
})
});
var series2 = data.filter(function(d) {return !d.disabled && d.yAxis == 2})
.map(function(d) {
return d.values.map(function(d,i) {
return { x: getX(d), y: getY(d) }
})
});
x .domain(d3.extent(d3.merge(series1.concat(series2)), function(d) { return d.x }))
.range([0, availableWidth]);
var wrap = container.selectAll('g.wrap.multiChart').data([data]);
var gEnter = wrap.enter().append('g').attr('class', 'wrap nvd3 multiChart').append('g');
gEnter.append('g').attr('class', 'nv-x nv-axis');
gEnter.append('g').attr('class', 'nv-y1 nv-axis');
gEnter.append('g').attr('class', 'nv-y2 nv-axis');
gEnter.append('g').attr('class', 'stack1Wrap');
gEnter.append('g').attr('class', 'stack2Wrap');
gEnter.append('g').attr('class', 'bars1Wrap');
gEnter.append('g').attr('class', 'bars2Wrap');
gEnter.append('g').attr('class', 'scatters1Wrap');
gEnter.append('g').attr('class', 'scatters2Wrap');
gEnter.append('g').attr('class', 'lines1Wrap');
gEnter.append('g').attr('class', 'lines2Wrap');
gEnter.append('g').attr('class', 'legendWrap');
gEnter.append('g').attr('class', 'nv-interactive');
var g = wrap.select('g');
var color_array = data.map(function(d,i) {
return data[i].color || color(d, i);
});
// Legend
if (!showLegend) {
g.select('.legendWrap').selectAll('*').remove();
} else {
var legendWidth = legend.align() ? availableWidth / 2 : availableWidth;
var legendXPosition = legend.align() ? legendWidth : 0;
legend.width(legendWidth);
legend.color(color_array);
g.select('.legendWrap')
.datum(data.map(function(series) {
series.originalKey = series.originalKey === undefined ? series.key : series.originalKey;
series.key = series.originalKey + (series.yAxis == 1 ? '' : legendRightAxisHint);
return series;
}))
.call(legend);
if ( margin.top != legend.height()) {
margin.top = legend.height();
availableHeight = nv.utils.availableHeight(height, container, margin);
}
g.select('.legendWrap')
.attr('transform', 'translate(' + legendXPosition + ',' + (-margin.top) +')');
}
lines1
.width(availableWidth)
.height(availableHeight)
.interpolate(interpolate)
.color(color_array.filter(function(d,i) { return !data[i].disabled && data[i].yAxis == 1 && data[i].type == 'line'}));
lines2
.width(availableWidth)
.height(availableHeight)
.interpolate(interpolate)
.color(color_array.filter(function(d,i) { return !data[i].disabled && data[i].yAxis == 2 && data[i].type == 'line'}));
scatters1
.width(availableWidth)
.height(availableHeight)
.color(color_array.filter(function(d,i) { return !data[i].disabled && data[i].yAxis == 1 && data[i].type == 'scatter'}));
scatters2
.width(availableWidth)
.height(availableHeight)
.color(color_array.filter(function(d,i) { return !data[i].disabled && data[i].yAxis == 2 && data[i].type == 'scatter'}));
bars1
.width(availableWidth)
.height(availableHeight)
.color(color_array.filter(function(d,i) { return !data[i].disabled && data[i].yAxis == 1 && data[i].type == 'bar'}));
bars2
.width(availableWidth)
.height(availableHeight)
.color(color_array.filter(function(d,i) { return !data[i].disabled && data[i].yAxis == 2 && data[i].type == 'bar'}));
stack1
.width(availableWidth)
.height(availableHeight)
.interpolate(interpolate)
.color(color_array.filter(function(d,i) { return !data[i].disabled && data[i].yAxis == 1 && data[i].type == 'area'}));
stack2
.width(availableWidth)
.height(availableHeight)
.interpolate(interpolate)
.color(color_array.filter(function(d,i) { return !data[i].disabled && data[i].yAxis == 2 && data[i].type == 'area'}));
g.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
var lines1Wrap = g.select('.lines1Wrap')
.datum(dataLines1.filter(function(d){return !d.disabled}));
var scatters1Wrap = g.select('.scatters1Wrap')
.datum(dataScatters1.filter(function(d){return !d.disabled}));
var bars1Wrap = g.select('.bars1Wrap')
.datum(dataBars1.filter(function(d){return !d.disabled}));
var stack1Wrap = g.select('.stack1Wrap')
.datum(dataStack1.filter(function(d){return !d.disabled}));
var lines2Wrap = g.select('.lines2Wrap')
.datum(dataLines2.filter(function(d){return !d.disabled}));
var scatters2Wrap = g.select('.scatters2Wrap')
.datum(dataScatters2.filter(function(d){return !d.disabled}));
var bars2Wrap = g.select('.bars2Wrap')
.datum(dataBars2.filter(function(d){return !d.disabled}));
var stack2Wrap = g.select('.stack2Wrap')
.datum(dataStack2.filter(function(d){return !d.disabled}));
var extraValue1 = dataStack1.length ? dataStack1.map(function(a){return a.values}).reduce(function(a,b){
return a.map(function(aVal,i){return {x: aVal.x, y: aVal.y + b[i].y}})
}).concat([{x:0, y:0}]) : [];
var extraValue2 = dataStack2.length ? dataStack2.map(function(a){return a.values}).reduce(function(a,b){
return a.map(function(aVal,i){return {x: aVal.x, y: aVal.y + b[i].y}})
}).concat([{x:0, y:0}]) : [];
yScale1 .domain(yDomain1 || d3.extent(d3.merge(series1).concat(extraValue1), function(d) { return d.y } ))
.range([0, availableHeight]);
yScale2 .domain(yDomain2 || d3.extent(d3.merge(series2).concat(extraValue2), function(d) { return d.y } ))
.range([0, availableHeight]);
lines1.yDomain(yScale1.domain());
scatters1.yDomain(yScale1.domain());
bars1.yDomain(yScale1.domain());
stack1.yDomain(yScale1.domain());
lines2.yDomain(yScale2.domain());
scatters2.yDomain(yScale2.domain());
bars2.yDomain(yScale2.domain());
stack2.yDomain(yScale2.domain());
if(dataStack1.length){d3.transition(stack1Wrap).call(stack1);}
if(dataStack2.length){d3.transition(stack2Wrap).call(stack2);}
if(dataBars1.length){d3.transition(bars1Wrap).call(bars1);}
if(dataBars2.length){d3.transition(bars2Wrap).call(bars2);}
if(dataLines1.length){d3.transition(lines1Wrap).call(lines1);}
if(dataLines2.length){d3.transition(lines2Wrap).call(lines2);}
if(dataScatters1.length){d3.transition(scatters1Wrap).call(scatters1);}
if(dataScatters2.length){d3.transition(scatters2Wrap).call(scatters2);}
xAxis
._ticks( nv.utils.calcTicksX(availableWidth/100, data) )
.tickSize(-availableHeight, 0);
g.select('.nv-x.nv-axis')
.attr('transform', 'translate(0,' + availableHeight + ')');
d3.transition(g.select('.nv-x.nv-axis'))
.call(xAxis);
yAxis1
._ticks( nv.utils.calcTicksY(availableHeight/36, data) )
.tickSize( -availableWidth, 0);
d3.transition(g.select('.nv-y1.nv-axis'))
.call(yAxis1);
yAxis2
._ticks( nv.utils.calcTicksY(availableHeight/36, data) )
.tickSize( -availableWidth, 0);
d3.transition(g.select('.nv-y2.nv-axis'))
.call(yAxis2);
g.select('.nv-y1.nv-axis')
.classed('nv-disabled', series1.length ? false : true)
.attr('transform', 'translate(' + x.range()[0] + ',0)');
g.select('.nv-y2.nv-axis')
.classed('nv-disabled', series2.length ? false : true)
.attr('transform', 'translate(' + x.range()[1] + ',0)');
legend.dispatch.on('stateChange', function(newState) {
chart.update();
});
if(useInteractiveGuideline){
interactiveLayer
.width(availableWidth)
.height(availableHeight)
.margin({left:margin.left, top:margin.top})
.svgContainer(container)
.xScale(x);
wrap.select(".nv-interactive").call(interactiveLayer);
}
//============================================================
// Event Handling/Dispatching
//------------------------------------------------------------
function mouseover_line(evt) {
var yaxis = data[evt.seriesIndex].yAxis === 2 ? yAxis2 : yAxis1;
evt.value = evt.point.x;
evt.series = {
value: evt.point.y,
color: evt.point.color,
key: evt.series.key
};
tooltip
.duration(0)
.headerFormatter(function(d, i) {
return xAxis.tickFormat()(d, i);
})
.valueFormatter(function(d, i) {
return yaxis.tickFormat()(d, i);
})
.data(evt)
.hidden(false);
}
function mouseover_scatter(evt) {
var yaxis = data[evt.seriesIndex].yAxis === 2 ? yAxis2 : yAxis1;
evt.value = evt.point.x;
evt.series = {
value: evt.point.y,
color: evt.point.color,
key: evt.series.key
};
tooltip
.duration(100)
.headerFormatter(function(d, i) {
return xAxis.tickFormat()(d, i);
})
.valueFormatter(function(d, i) {
return yaxis.tickFormat()(d, i);
})
.data(evt)
.hidden(false);
}
function mouseover_stack(evt) {
var yaxis = data[evt.seriesIndex].yAxis === 2 ? yAxis2 : yAxis1;
evt.point['x'] = stack1.x()(evt.point);
evt.point['y'] = stack1.y()(evt.point);
tooltip
.duration(0)
.headerFormatter(function(d, i) {
return xAxis.tickFormat()(d, i);
})
.valueFormatter(function(d, i) {
return yaxis.tickFormat()(d, i);
})
.data(evt)
.hidden(false);
}
function mouseover_bar(evt) {
var yaxis = data[evt.data.series].yAxis === 2 ? yAxis2 : yAxis1;
evt.value = bars1.x()(evt.data);
evt['series'] = {
value: bars1.y()(evt.data),
color: evt.color,
key: evt.data.key
};
tooltip
.duration(0)
.headerFormatter(function(d, i) {
return xAxis.tickFormat()(d, i);
})
.valueFormatter(function(d, i) {
return yaxis.tickFormat()(d, i);
})
.data(evt)
.hidden(false);
}
function clearHighlights() {
for(var i=0, il=charts.length; i < il; i++){
var chart = charts[i];
try {
chart.clearHighlights();
} catch(e){}
}
}
function highlightPoint(serieIndex, pointIndex, b){
for(var i=0, il=charts.length; i < il; i++){
var chart = charts[i];
try {
chart.highlightPoint(serieIndex, pointIndex, b);
} catch(e){}
}
}
if(useInteractiveGuideline){
interactiveLayer.dispatch.on('elementMousemove', function(e) {
clearHighlights();
var singlePoint, pointIndex, pointXLocation, allData = [];
data
.filter(function(series, i) {
series.seriesIndex = i;
return !series.disabled;
})
.forEach(function(series,i) {
var extent = x.domain();
var currentValues = series.values.filter(function(d,i) {
return chart.x()(d,i) >= extent[0] && chart.x()(d,i) <= extent[1];
});
pointIndex = nv.interactiveBisect(currentValues, e.pointXValue, chart.x());
var point = currentValues[pointIndex];
var pointYValue = chart.y()(point, pointIndex);
if (pointYValue !== null) {
highlightPoint(i, pointIndex, true);
}
if (point === undefined) return;
if (singlePoint === undefined) singlePoint = point;
if (pointXLocation === undefined) pointXLocation = x(chart.x()(point,pointIndex));
allData.push({
key: series.key,
value: pointYValue,
color: color(series,series.seriesIndex),
data: point,
yAxis: series.yAxis == 2 ? yAxis2 : yAxis1
});
});
interactiveLayer.tooltip
.chartContainer(chart.container.parentNode)
.headerFormatter(function(d, i) {
return xAxis.tickFormat()(d, i);
})
.valueFormatter(function(d,i) {
var yAxis = allData[i].yAxis;
return d === null ? "N/A" : yAxis.tickFormat()(d);
})
.data({
value: chart.x()( singlePoint,pointIndex ),
index: pointIndex,
series: allData
})();
interactiveLayer.renderGuideLine(pointXLocation);
});
interactiveLayer.dispatch.on("elementMouseout",function(e) {
clearHighlights();
});
} else {
lines1.dispatch.on('elementMouseover.tooltip', mouseover_line);
lines2.dispatch.on('elementMouseover.tooltip', mouseover_line);
lines1.dispatch.on('elementMouseout.tooltip', function(evt) {
tooltip.hidden(true)
});
lines2.dispatch.on('elementMouseout.tooltip', function(evt) {
tooltip.hidden(true)
});
scatters1.dispatch.on('elementMouseover.tooltip', mouseover_scatter);
scatters2.dispatch.on('elementMouseover.tooltip', mouseover_scatter);
scatters1.dispatch.on('elementMouseout.tooltip', function(evt) {
tooltip.hidden(true)
});
scatters2.dispatch.on('elementMouseout.tooltip', function(evt) {
tooltip.hidden(true)
});
stack1.dispatch.on('elementMouseover.tooltip', mouseover_stack);
stack2.dispatch.on('elementMouseover.tooltip', mouseover_stack);
stack1.dispatch.on('elementMouseout.tooltip', function(evt) {
tooltip.hidden(true)
});
stack2.dispatch.on('elementMouseout.tooltip', function(evt) {
tooltip.hidden(true)
});
bars1.dispatch.on('elementMouseover.tooltip', mouseover_bar);
bars2.dispatch.on('elementMouseover.tooltip', mouseover_bar);
bars1.dispatch.on('elementMouseout.tooltip', function(evt) {
tooltip.hidden(true);
});
bars2.dispatch.on('elementMouseout.tooltip', function(evt) {
tooltip.hidden(true);
});
bars1.dispatch.on('elementMousemove.tooltip', function(evt) {
tooltip();
});
bars2.dispatch.on('elementMousemove.tooltip', function(evt) {
tooltip();
});
}
});
return chart;
}
//============================================================
// Global getters and setters
//------------------------------------------------------------
chart.dispatch = dispatch;
chart.legend = legend;
chart.lines1 = lines1;
chart.lines2 = lines2;
chart.scatters1 = scatters1;
chart.scatters2 = scatters2;
chart.bars1 = bars1;
chart.bars2 = bars2;
chart.stack1 = stack1;
chart.stack2 = stack2;
chart.xAxis = xAxis;
chart.yAxis1 = yAxis1;
chart.yAxis2 = yAxis2;
chart.tooltip = tooltip;
chart.interactiveLayer = interactiveLayer;
chart.options = nv.utils.optionsFunc.bind(chart);
chart._options = Object.create({}, {
// simple options, just get/set the necessary values
width: {get: function(){return width;}, set: function(_){width=_;}},
height: {get: function(){return height;}, set: function(_){height=_;}},
showLegend: {get: function(){return showLegend;}, set: function(_){showLegend=_;}},
yDomain1: {get: function(){return yDomain1;}, set: function(_){yDomain1=_;}},
yDomain2: {get: function(){return yDomain2;}, set: function(_){yDomain2=_;}},
noData: {get: function(){return noData;}, set: function(_){noData=_;}},
interpolate: {get: function(){return interpolate;}, set: function(_){interpolate=_;}},
legendRightAxisHint: {get: function(){return legendRightAxisHint;}, set: function(_){legendRightAxisHint=_;}},
// options that require extra logic in the setter
margin: {get: function(){return margin;}, set: function(_){
margin.top = _.top !== undefined ? _.top : margin.top;
margin.right = _.right !== undefined ? _.right : margin.right;
margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
margin.left = _.left !== undefined ? _.left : margin.left;
}},
color: {get: function(){return color;}, set: function(_){
color = nv.utils.getColor(_);
}},
x: {get: function(){return getX;}, set: function(_){
getX = _;
lines1.x(_);
lines2.x(_);
scatters1.x(_);
scatters2.x(_);
bars1.x(_);
bars2.x(_);
stack1.x(_);
stack2.x(_);
}},
y: {get: function(){return getY;}, set: function(_){
getY = _;
lines1.y(_);
lines2.y(_);
scatters1.y(_);
scatters2.y(_);
stack1.y(_);
stack2.y(_);
bars1.y(_);
bars2.y(_);
}},
useVoronoi: {get: function(){return useVoronoi;}, set: function(_){
useVoronoi=_;
lines1.useVoronoi(_);
lines2.useVoronoi(_);
stack1.useVoronoi(_);
stack2.useVoronoi(_);
}},
useInteractiveGuideline: {get: function(){return useInteractiveGuideline;}, set: function(_){
useInteractiveGuideline = _;
if (useInteractiveGuideline) {
lines1.interactive(false);
lines1.useVoronoi(false);
lines2.interactive(false);
lines2.useVoronoi(false);
stack1.interactive(false);
stack1.useVoronoi(false);
stack2.interactive(false);
stack2.useVoronoi(false);
scatters1.interactive(false);
scatters2.interactive(false);
}
}}
});
nv.utils.initOptions(chart);
return chart;
};
nv.models.ohlcBar = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var margin = {top: 0, right: 0, bottom: 0, left: 0}
, width = null
, height = null
, id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one
, container = null
, x = d3.scale.linear()
, y = d3.scale.linear()
, getX = function(d) { return d.x }
, getY = function(d) { return d.y }
, getOpen = function(d) { return d.open }
, getClose = function(d) { return d.close }
, getHigh = function(d) { return d.high }
, getLow = function(d) { return d.low }
, forceX = []
, forceY = []
, padData = false // If true, adds half a data points width to front and back, for lining up a line chart with a bar chart
, clipEdge = true
, color = nv.utils.defaultColor()
, interactive = false
, xDomain
, yDomain
, xRange
, yRange
, dispatch = d3.dispatch('stateChange', 'changeState', 'renderEnd', 'chartClick', 'elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout', 'elementMousemove')
;
//============================================================
// Private Variables
//------------------------------------------------------------
function chart(selection) {
selection.each(function(data) {
container = d3.select(this);
var availableWidth = nv.utils.availableWidth(width, container, margin),
availableHeight = nv.utils.availableHeight(height, container, margin);
nv.utils.initSVG(container);
// ohlc bar width.
var w = (availableWidth / data[0].values.length) * .9;
// Setup Scales
x.domain(xDomain || d3.extent(data[0].values.map(getX).concat(forceX) ));
if (padData)
x.range(xRange || [availableWidth * .5 / data[0].values.length, availableWidth * (data[0].values.length - .5) / data[0].values.length ]);
else
x.range(xRange || [5 + w/2, availableWidth - w/2 - 5]);
y.domain(yDomain || [
d3.min(data[0].values.map(getLow).concat(forceY)),
d3.max(data[0].values.map(getHigh).concat(forceY))
]
).range(yRange || [availableHeight, 0]);
// If scale's domain don't have a range, slightly adjust to make one... so a chart can show a single data point
if (x.domain()[0] === x.domain()[1])
x.domain()[0] ?
x.domain([x.domain()[0] - x.domain()[0] * 0.01, x.domain()[1] + x.domain()[1] * 0.01])
: x.domain([-1,1]);
if (y.domain()[0] === y.domain()[1])
y.domain()[0] ?
y.domain([y.domain()[0] + y.domain()[0] * 0.01, y.domain()[1] - y.domain()[1] * 0.01])
: y.domain([-1,1]);
// Setup containers and skeleton of chart
var wrap = d3.select(this).selectAll('g.nv-wrap.nv-ohlcBar').data([data[0].values]);
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-ohlcBar');
var defsEnter = wrapEnter.append('defs');
var gEnter = wrapEnter.append('g');
var g = wrap.select('g');
gEnter.append('g').attr('class', 'nv-ticks');
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
container
.on('click', function(d,i) {
dispatch.chartClick({
data: d,
index: i,
pos: d3.event,
id: id
});
});
defsEnter.append('clipPath')
.attr('id', 'nv-chart-clip-path-' + id)
.append('rect');
wrap.select('#nv-chart-clip-path-' + id + ' rect')
.attr('width', availableWidth)
.attr('height', availableHeight);
g .attr('clip-path', clipEdge ? 'url(#nv-chart-clip-path-' + id + ')' : '');
var ticks = wrap.select('.nv-ticks').selectAll('.nv-tick')
.data(function(d) { return d });
ticks.exit().remove();
ticks.enter().append('path')
.attr('class', function(d,i,j) { return (getOpen(d,i) > getClose(d,i) ? 'nv-tick negative' : 'nv-tick positive') + ' nv-tick-' + j + '-' + i })
.attr('d', function(d,i) {
return 'm0,0l0,'
+ (y(getOpen(d,i))
- y(getHigh(d,i)))
+ 'l'
+ (-w/2)
+ ',0l'
+ (w/2)
+ ',0l0,'
+ (y(getLow(d,i)) - y(getOpen(d,i)))
+ 'l0,'
+ (y(getClose(d,i))
- y(getLow(d,i)))
+ 'l'
+ (w/2)
+ ',0l'
+ (-w/2)
+ ',0z';
})
.attr('transform', function(d,i) { return 'translate(' + x(getX(d,i)) + ',' + y(getHigh(d,i)) + ')'; })
.attr('fill', function(d,i) { return color[0]; })
.attr('stroke', function(d,i) { return color[0]; })
.attr('x', 0 )
.attr('y', function(d,i) { return y(Math.max(0, getY(d,i))) })
.attr('height', function(d,i) { return Math.abs(y(getY(d,i)) - y(0)) });
// the bar colors are controlled by CSS currently
ticks.attr('class', function(d,i,j) {
return (getOpen(d,i) > getClose(d,i) ? 'nv-tick negative' : 'nv-tick positive') + ' nv-tick-' + j + '-' + i;
});
d3.transition(ticks)
.attr('transform', function(d,i) { return 'translate(' + x(getX(d,i)) + ',' + y(getHigh(d,i)) + ')'; })
.attr('d', function(d,i) {
var w = (availableWidth / data[0].values.length) * .9;
return 'm0,0l0,'
+ (y(getOpen(d,i))
- y(getHigh(d,i)))
+ 'l'
+ (-w/2)
+ ',0l'
+ (w/2)
+ ',0l0,'
+ (y(getLow(d,i))
- y(getOpen(d,i)))
+ 'l0,'
+ (y(getClose(d,i))
- y(getLow(d,i)))
+ 'l'
+ (w/2)
+ ',0l'
+ (-w/2)
+ ',0z';
});
});
return chart;
}
//Create methods to allow outside functions to highlight a specific bar.
chart.highlightPoint = function(pointIndex, isHoverOver) {
chart.clearHighlights();
container.select(".nv-ohlcBar .nv-tick-0-" + pointIndex)
.classed("hover", isHoverOver)
;
};
chart.clearHighlights = function() {
container.select(".nv-ohlcBar .nv-tick.hover")
.classed("hover", false)
;
};
//============================================================
// Expose Public Variables
//------------------------------------------------------------
chart.dispatch = dispatch;
chart.options = nv.utils.optionsFunc.bind(chart);
chart._options = Object.create({}, {
// simple options, just get/set the necessary values
width: {get: function(){return width;}, set: function(_){width=_;}},
height: {get: function(){return height;}, set: function(_){height=_;}},
xScale: {get: function(){return x;}, set: function(_){x=_;}},
yScale: {get: function(){return y;}, set: function(_){y=_;}},
xDomain: {get: function(){return xDomain;}, set: function(_){xDomain=_;}},
yDomain: {get: function(){return yDomain;}, set: function(_){yDomain=_;}},
xRange: {get: function(){return xRange;}, set: function(_){xRange=_;}},
yRange: {get: function(){return yRange;}, set: function(_){yRange=_;}},
forceX: {get: function(){return forceX;}, set: function(_){forceX=_;}},
forceY: {get: function(){return forceY;}, set: function(_){forceY=_;}},
padData: {get: function(){return padData;}, set: function(_){padData=_;}},
clipEdge: {get: function(){return clipEdge;}, set: function(_){clipEdge=_;}},
id: {get: function(){return id;}, set: function(_){id=_;}},
interactive: {get: function(){return interactive;}, set: function(_){interactive=_;}},
x: {get: function(){return getX;}, set: function(_){getX=_;}},
y: {get: function(){return getY;}, set: function(_){getY=_;}},
open: {get: function(){return getOpen();}, set: function(_){getOpen=_;}},
close: {get: function(){return getClose();}, set: function(_){getClose=_;}},
high: {get: function(){return getHigh;}, set: function(_){getHigh=_;}},
low: {get: function(){return getLow;}, set: function(_){getLow=_;}},
// options that require extra logic in the setter
margin: {get: function(){return margin;}, set: function(_){
margin.top = _.top != undefined ? _.top : margin.top;
margin.right = _.right != undefined ? _.right : margin.right;
margin.bottom = _.bottom != undefined ? _.bottom : margin.bottom;
margin.left = _.left != undefined ? _.left : margin.left;
}},
color: {get: function(){return color;}, set: function(_){
color = nv.utils.getColor(_);
}}
});
nv.utils.initOptions(chart);
return chart;
};
// Code adapted from Jason Davies' "Parallel Coordinates"
// http://bl.ocks.org/jasondavies/1341281
nv.models.parallelCoordinates = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var margin = {top: 30, right: 0, bottom: 10, left: 0}
, width = null
, height = null
, availableWidth = null
, availableHeight = null
, x = d3.scale.ordinal()
, y = {}
, undefinedValuesLabel = "undefined values"
, dimensionData = []
, enabledDimensions = []
, dimensionNames = []
, displayBrush = true
, color = nv.utils.defaultColor()
, filters = []
, active = []
, dragging = []
, axisWithUndefinedValues = []
, lineTension = 1
, foreground
, background
, dimensions
, line = d3.svg.line()
, axis = d3.svg.axis()
, dispatch = d3.dispatch('brushstart', 'brush', 'brushEnd', 'dimensionsOrder', "stateChange", 'elementClick', 'elementMouseover', 'elementMouseout', 'elementMousemove', 'renderEnd', 'activeChanged')
;
//============================================================
// Private Variables
//------------------------------------------------------------
var renderWatch = nv.utils.renderWatch(dispatch);
function chart(selection) {
renderWatch.reset();
selection.each(function(data) {
var container = d3.select(this);
availableWidth = nv.utils.availableWidth(width, container, margin);
availableHeight = nv.utils.availableHeight(height, container, margin);
nv.utils.initSVG(container);
//Convert old data to new format (name, values)
if (data[0].values === undefined) {
var newData = [];
data.forEach(function (d) {
var val = {};
var key = Object.keys(d);
key.forEach(function (k) { if (k !== "name") val[k] = d[k] });
newData.push({ key: d.name, values: val });
});
data = newData;
}
var dataValues = data.map(function (d) {return d.values});
if (active.length === 0) {
active = data;
}; //set all active before first brush call
dimensionNames = dimensionData.sort(function (a, b) { return a.currentPosition - b.currentPosition; }).map(function (d) { return d.key });
enabledDimensions = dimensionData.filter(function (d) { return !d.disabled; });
// Setup Scales
x.rangePoints([0, availableWidth], 1).domain(enabledDimensions.map(function (d) { return d.key; }));
//Set as true if all values on an axis are missing.
// Extract the list of dimensions and create a scale for each.
var oldDomainMaxValue = {};
var displayMissingValuesline = false;
var currentTicks = [];
dimensionNames.forEach(function(d) {
var extent = d3.extent(dataValues, function (p) { return +p[d]; });
var min = extent[0];
var max = extent[1];
var onlyUndefinedValues = false;
//If there is no values to display on an axis, set the extent to 0
if (isNaN(min) || isNaN(max)) {
onlyUndefinedValues = true;
min = 0;
max = 0;
}
//Scale axis if there is only one value
if (min === max) {
min = min - 1;
max = max + 1;
}
var f = filters.filter(function (k) { return k.dimension == d; });
if (f.length !== 0) {
//If there is only NaN values, keep the existing domain.
if (onlyUndefinedValues) {
min = y[d].domain()[0];
max = y[d].domain()[1];
}
//If the brush extent is > max (< min), keep the extent value.
else if (!f[0].hasOnlyNaN && displayBrush) {
min = min > f[0].extent[0] ? f[0].extent[0] : min;
max = max < f[0].extent[1] ? f[0].extent[1] : max;
}
//If there is NaN values brushed be sure the brush extent is on the domain.
else if (f[0].hasNaN) {
max = max < f[0].extent[1] ? f[0].extent[1] : max;
oldDomainMaxValue[d] = y[d].domain()[1];
displayMissingValuesline = true;
}
}
//Use 90% of (availableHeight - 12) for the axis range, 12 reprensenting the space necessary to display "undefined values" text.
//The remaining 10% are used to display the missingValue line.
y[d] = d3.scale.linear()
.domain([min, max])
.range([(availableHeight - 12) * 0.9, 0]);
axisWithUndefinedValues = [];
y[d].brush = d3.svg.brush().y(y[d]).on('brushstart', brushstart).on('brush', brush).on('brushend', brushend);
});
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-parallelCoordinates').data([data]);
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-parallelCoordinates');
var gEnter = wrapEnter.append('g');
var g = wrap.select('g');
gEnter.append('g').attr('class', 'nv-parallelCoordinates background');
gEnter.append('g').attr('class', 'nv-parallelCoordinates foreground');
gEnter.append('g').attr('class', 'nv-parallelCoordinates missingValuesline');
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
line.interpolate('cardinal').tension(lineTension);
axis.orient('left');
var axisDrag = d3.behavior.drag()
.on('dragstart', dragStart)
.on('drag', dragMove)
.on('dragend', dragEnd);
//Add missing value line at the bottom of the chart
var missingValuesline, missingValueslineText;
var step = x.range()[1] - x.range()[0];
if (!isNaN(step)) {
var lineData = [0 + step / 2, availableHeight - 12, availableWidth - step / 2, availableHeight - 12];
missingValuesline = wrap.select('.missingValuesline').selectAll('line').data([lineData]);
missingValuesline.enter().append('line');
missingValuesline.exit().remove();
missingValuesline.attr("x1", function(d) { return d[0]; })
.attr("y1", function(d) { return d[1]; })
.attr("x2", function(d) { return d[2]; })
.attr("y2", function(d) { return d[3]; });
//Add the text "undefined values" under the missing value line
missingValueslineText = wrap.select('.missingValuesline').selectAll('text').data([undefinedValuesLabel]);
missingValueslineText.append('text').data([undefinedValuesLabel]);
missingValueslineText.enter().append('text');
missingValueslineText.exit().remove();
missingValueslineText.attr("y", availableHeight)
//To have the text right align with the missingValues line, substract 92 representing the text size.
.attr("x", availableWidth - 92 - step / 2)
.text(function(d) { return d; });
}
// Add grey background lines for context.
background = wrap.select('.background').selectAll('path').data(data);
background.enter().append('path');
background.exit().remove();
background.attr('d', path);
// Add blue foreground lines for focus.
foreground = wrap.select('.foreground').selectAll('path').data(data);
foreground.enter().append('path')
foreground.exit().remove();
foreground.attr('d', path)
.style("stroke-width", function (d, i) {
if (isNaN(d.strokeWidth)) { d.strokeWidth = 1;} return d.strokeWidth;})
.attr('stroke', function (d, i) { return d.color || color(d, i); });
foreground.on("mouseover", function (d, i) {
d3.select(this).classed('hover', true).style("stroke-width", d.strokeWidth + 2 + "px").style("stroke-opacity", 1);
dispatch.elementMouseover({
label: d.name,
color: d.color || color(d, i),
values: d.values,
dimensions: enabledDimensions
});
});
foreground.on("mouseout", function (d, i) {
d3.select(this).classed('hover', false).style("stroke-width", d.strokeWidth + "px").style("stroke-opacity", 0.7);
dispatch.elementMouseout({
label: d.name,
index: i
});
});
foreground.on('mousemove', function (d, i) {
dispatch.elementMousemove();
});
foreground.on('click', function (d) {
dispatch.elementClick({
id: d.id
});
});
// Add a group element for each dimension.
dimensions = g.selectAll('.dimension').data(enabledDimensions);
var dimensionsEnter = dimensions.enter().append('g').attr('class', 'nv-parallelCoordinates dimension');
dimensions.attr('transform', function(d) { return 'translate(' + x(d.key) + ',0)'; });
dimensionsEnter.append('g').attr('class', 'nv-axis');
// Add an axis and title.
dimensionsEnter.append('text')
.attr('class', 'nv-label')
.style("cursor", "move")
.attr('dy', '-1em')
.attr('text-anchor', 'middle')
.on("mouseover", function(d, i) {
dispatch.elementMouseover({
label: d.tooltip || d.key,
color: d.color
});
})
.on("mouseout", function(d, i) {
dispatch.elementMouseout({
label: d.tooltip
});
})
.on('mousemove', function (d, i) {
dispatch.elementMousemove();
})
.call(axisDrag);
dimensionsEnter.append('g').attr('class', 'nv-brushBackground');
dimensions.exit().remove();
dimensions.select('.nv-label').text(function (d) { return d.key });
// Add and store a brush for each axis.
restoreBrush(displayBrush);
var actives = dimensionNames.filter(function (p) { return !y[p].brush.empty(); }),
extents = actives.map(function (p) { return y[p].brush.extent(); });
var formerActive = active.slice(0);
//Restore active values
active = [];
foreground.style("display", function (d) {
var isActive = actives.every(function (p, i) {
if ((isNaN(d.values[p]) || isNaN(parseFloat(d.values[p]))) && extents[i][0] == y[p].brush.y().domain()[0]) {
return true;
}
return (extents[i][0] <= d.values[p] && d.values[p] <= extents[i][1]) && !isNaN(parseFloat(d.values[p]));
});
if (isActive)
active.push(d);
return !isActive ? "none" : null;
});
if (filters.length > 0 || !nv.utils.arrayEquals(active, formerActive)) {
dispatch.activeChanged(active);
}
// Returns the path for a given data point.
function path(d) {
return line(enabledDimensions.map(function (p) {
//If value if missing, put the value on the missing value line
if (isNaN(d.values[p.key]) || isNaN(parseFloat(d.values[p.key])) || displayMissingValuesline) {
var domain = y[p.key].domain();
var range = y[p.key].range();
var min = domain[0] - (domain[1] - domain[0]) / 9;
//If it's not already the case, allow brush to select undefined values
if (axisWithUndefinedValues.indexOf(p.key) < 0) {
var newscale = d3.scale.linear().domain([min, domain[1]]).range([availableHeight - 12, range[1]]);
y[p.key].brush.y(newscale);
axisWithUndefinedValues.push(p.key);
}
if (isNaN(d.values[p.key]) || isNaN(parseFloat(d.values[p.key]))) {
return [x(p.key), y[p.key](min)];
}
}
//If parallelCoordinate contain missing values show the missing values line otherwise, hide it.
if (missingValuesline !== undefined) {
if (axisWithUndefinedValues.length > 0 || displayMissingValuesline) {
missingValuesline.style("display", "inline");
missingValueslineText.style("display", "inline");
} else {
missingValuesline.style("display", "none");
missingValueslineText.style("display", "none");
}
}
return [x(p.key), y[p.key](d.values[p.key])];
}));
}
function restoreBrush(visible) {
filters.forEach(function (f) {
//If filter brushed NaN values, keep the brush on the bottom of the axis.
var brushDomain = y[f.dimension].brush.y().domain();
if (f.hasOnlyNaN) {
f.extent[1] = (y[f.dimension].domain()[1] - brushDomain[0]) * (f.extent[1] - f.extent[0]) / (oldDomainMaxValue[f.dimension] - f.extent[0]) + brushDomain[0];
}
if (f.hasNaN) {
f.extent[0] = brushDomain[0];
}
if (visible)
y[f.dimension].brush.extent(f.extent);
});
dimensions.select('.nv-brushBackground')
.each(function (d) {
d3.select(this).call(y[d.key].brush);
})
.selectAll('rect')
.attr('x', -8)
.attr('width', 16);
updateTicks();
}
// Handles a brush event, toggling the display of foreground lines.
function brushstart() {
//If brush aren't visible, show it before brushing again.
if (displayBrush === false) {
displayBrush = true;
restoreBrush(true);
}
}
// Handles a brush event, toggling the display of foreground lines.
function brush() {
actives = dimensionNames.filter(function (p) { return !y[p].brush.empty(); });
extents = actives.map(function(p) { return y[p].brush.extent(); });
filters = []; //erase current filters
actives.forEach(function(d,i) {
filters[i] = {
dimension: d,
extent: extents[i],
hasNaN: false,
hasOnlyNaN: false
}
});
active = []; //erase current active list
foreground.style('display', function(d) {
var isActive = actives.every(function(p, i) {
if ((isNaN(d.values[p]) || isNaN(parseFloat(d.values[p]))) && extents[i][0] == y[p].brush.y().domain()[0]) return true;
return (extents[i][0] <= d.values[p] && d.values[p] <= extents[i][1]) && !isNaN(parseFloat(d.values[p]));
});
if (isActive) active.push(d);
return isActive ? null : 'none';
});
updateTicks();
dispatch.brush({
filters: filters,
active: active
});
}
function brushend() {
var hasActiveBrush = actives.length > 0 ? true : false;
filters.forEach(function (f) {
if (f.extent[0] === y[f.dimension].brush.y().domain()[0] && axisWithUndefinedValues.indexOf(f.dimension) >= 0)
f.hasNaN = true;
if (f.extent[1] < y[f.dimension].domain()[0])
f.hasOnlyNaN = true;
});
dispatch.brushEnd(active, hasActiveBrush);
}
function updateTicks() {
dimensions.select('.nv-axis')
.each(function (d, i) {
var f = filters.filter(function (k) { return k.dimension == d.key; });
currentTicks[d.key] = y[d.key].domain();
//If brush are available, display brush extent
if (f.length != 0 && displayBrush)
{
currentTicks[d.key] = [];
if (f[0].extent[1] > y[d.key].domain()[0])
currentTicks[d.key] = [f[0].extent[1]];
if (f[0].extent[0] >= y[d.key].domain()[0])
currentTicks[d.key].push(f[0].extent[0]);
}
d3.select(this).call(axis.scale(y[d.key]).tickFormat(d.format).tickValues(currentTicks[d.key]));
});
}
function dragStart(d) {
dragging[d.key] = this.parentNode.__origin__ = x(d.key);
background.attr("visibility", "hidden");
}
function dragMove(d) {
dragging[d.key] = Math.min(availableWidth, Math.max(0, this.parentNode.__origin__ += d3.event.x));
foreground.attr("d", path);
enabledDimensions.sort(function (a, b) { return dimensionPosition(a.key) - dimensionPosition(b.key); });
enabledDimensions.forEach(function (d, i) { return d.currentPosition = i; });
x.domain(enabledDimensions.map(function (d) { return d.key; }));
dimensions.attr("transform", function(d) { return "translate(" + dimensionPosition(d.key) + ")"; });
}
function dragEnd(d, i) {
delete this.parentNode.__origin__;
delete dragging[d.key];
d3.select(this.parentNode).attr("transform", "translate(" + x(d.key) + ")");
foreground
.attr("d", path);
background
.attr("d", path)
.attr("visibility", null);
dispatch.dimensionsOrder(enabledDimensions);
}
function dimensionPosition(d) {
var v = dragging[d];
return v == null ? x(d) : v;
}
});
return chart;
}
//============================================================
// Expose Public Variables
//------------------------------------------------------------
chart.dispatch = dispatch;
chart.options = nv.utils.optionsFunc.bind(chart);
chart._options = Object.create({}, {
// simple options, just get/set the necessary values
width: {get: function(){return width;}, set: function(_){width= _;}},
height: {get: function(){return height;}, set: function(_){height= _;}},
dimensionData: { get: function () { return dimensionData; }, set: function (_) { dimensionData = _; } },
displayBrush: { get: function () { return displayBrush; }, set: function (_) { displayBrush = _; } },
filters: { get: function () { return filters; }, set: function (_) { filters = _; } },
active: { get: function () { return active; }, set: function (_) { active = _; } },
lineTension: {get: function(){return lineTension;}, set: function(_){lineTension = _;}},
undefinedValuesLabel : {get: function(){return undefinedValuesLabel;}, set: function(_){undefinedValuesLabel=_;}},
// deprecated options
dimensions: {get: function () { return dimensionData.map(function (d){return d.key}); }, set: function (_) {
// deprecated after 1.8.1
nv.deprecated('dimensions', 'use dimensionData instead');
if (dimensionData.length === 0) {
_.forEach(function (k) { dimensionData.push({ key: k }) })
} else {
_.forEach(function (k, i) { dimensionData[i].key= k })
}
}},
dimensionNames: {get: function () { return dimensionData.map(function (d){return d.key}); }, set: function (_) {
// deprecated after 1.8.1
nv.deprecated('dimensionNames', 'use dimensionData instead');
dimensionNames = [];
if (dimensionData.length === 0) {
_.forEach(function (k) { dimensionData.push({ key: k }) })
} else {
_.forEach(function (k, i) { dimensionData[i].key = k })
}
}},
dimensionFormats: {get: function () { return dimensionData.map(function (d) { return d.format }); }, set: function (_) {
// deprecated after 1.8.1
nv.deprecated('dimensionFormats', 'use dimensionData instead');
if (dimensionData.length === 0) {
_.forEach(function (f) { dimensionData.push({ format: f }) })
} else {
_.forEach(function (f, i) { dimensionData[i].format = f })
}
}},
// options that require extra logic in the setter
margin: {get: function(){return margin;}, set: function(_){
margin.top = _.top !== undefined ? _.top : margin.top;
margin.right = _.right !== undefined ? _.right : margin.right;
margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
margin.left = _.left !== undefined ? _.left : margin.left;
}},
color: {get: function(){return color;}, set: function(_){
color = nv.utils.getColor(_);
}}
});
nv.utils.initOptions(chart);
return chart;
};
nv.models.parallelCoordinatesChart = function () {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var parallelCoordinates = nv.models.parallelCoordinates()
var legend = nv.models.legend()
var tooltip = nv.models.tooltip();
var dimensionTooltip = nv.models.tooltip();
var margin = { top: 0, right: 0, bottom: 0, left: 0 }
, width = null
, height = null
, showLegend = true
, color = nv.utils.defaultColor()
, state = nv.utils.state()
, dimensionData = []
, displayBrush = true
, defaultState = null
, noData = null
, nanValue = "undefined"
, dispatch = d3.dispatch('dimensionsOrder', 'brushEnd', 'stateChange', 'changeState', 'renderEnd')
, controlWidth = function () { return showControls ? 180 : 0 }
;
//============================================================
//============================================================
// Private Variables
//------------------------------------------------------------
var renderWatch = nv.utils.renderWatch(dispatch);
var stateGetter = function(data) {
return function() {
return {
active: data.map(function(d) { return !d.disabled })
};
}
};
var stateSetter = function(data) {
return function(state) {
if(state.active !== undefined) {
data.forEach(function(series, i) {
series.disabled = !state.active[i];
});
}
}
};
tooltip.contentGenerator(function(data) {
var str = '<table><thead><tr><td class="legend-color-guide"><div style="background-color:' + data.color + '"></div></td><td><strong>' + data.key + '</strong></td></tr></thead>';
if(data.series.length !== 0)
{
str = str + '<tbody><tr><td height ="10px"></td></tr>';
data.series.forEach(function(d){
str = str + '<tr><td class="legend-color-guide"><div style="background-color:' + d.color + '"></div></td><td class="key">' + d.key + '</td><td class="value">' + d.value + '</td></tr>';
});
str = str + '</tbody>';
}
str = str + '</table>';
return str;
});
//============================================================
// Chart function
//------------------------------------------------------------
function chart(selection) {
renderWatch.reset();
renderWatch.models(parallelCoordinates);
selection.each(function(data) {
var container = d3.select(this);
nv.utils.initSVG(container);
var that = this;
var availableWidth = nv.utils.availableWidth(width, container, margin),
availableHeight = nv.utils.availableHeight(height, container, margin);
chart.update = function() { container.call(chart); };
chart.container = this;
state.setter(stateSetter(dimensionData), chart.update)
.getter(stateGetter(dimensionData))
.update();
//set state.disabled
state.disabled = dimensionData.map(function (d) { return !!d.disabled });
//Keep dimensions position in memory
dimensionData = dimensionData.map(function (d) {d.disabled = !!d.disabled; return d});
dimensionData.forEach(function (d, i) {
d.originalPosition = isNaN(d.originalPosition) ? i : d.originalPosition;
d.currentPosition = isNaN(d.currentPosition) ? i : d.currentPosition;
});
if (!defaultState) {
var key;
defaultState = {};
for(key in state) {
if(state[key] instanceof Array)
defaultState[key] = state[key].slice(0);
else
defaultState[key] = state[key];
}
}
// Display No Data message if there's nothing to show.
if(!data || !data.length) {
nv.utils.noData(chart, container);
return chart;
} else {
container.selectAll('.nv-noData').remove();
}
//------------------------------------------------------------
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-parallelCoordinatesChart').data([data]);
var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-parallelCoordinatesChart').append('g');
var g = wrap.select('g');
gEnter.append('g').attr('class', 'nv-parallelCoordinatesWrap');
gEnter.append('g').attr('class', 'nv-legendWrap');
g.select("rect")
.attr("width", availableWidth)
.attr("height", (availableHeight > 0) ? availableHeight : 0);
// Legend
if (!showLegend) {
g.select('.nv-legendWrap').selectAll('*').remove();
} else {
legend.width(availableWidth)
.color(function (d) { return "rgb(188,190,192)"; });
g.select('.nv-legendWrap')
.datum(dimensionData.sort(function (a, b) { return a.originalPosition - b.originalPosition; }))
.call(legend);
if (margin.top != legend.height()) {
margin.top = legend.height();
availableHeight = nv.utils.availableHeight(height, container, margin);
}
wrap.select('.nv-legendWrap')
.attr('transform', 'translate( 0 ,' + (-margin.top) + ')');
}
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
// Main Chart Component(s)
parallelCoordinates
.width(availableWidth)
.height(availableHeight)
.dimensionData(dimensionData)
.displayBrush(displayBrush);
var parallelCoordinatesWrap = g.select('.nv-parallelCoordinatesWrap ')
.datum(data);
parallelCoordinatesWrap.transition().call(parallelCoordinates);
//============================================================
// Event Handling/Dispatching (in chart's scope)
//------------------------------------------------------------
//Display reset brush button
parallelCoordinates.dispatch.on('brushEnd', function (active, hasActiveBrush) {
if (hasActiveBrush) {
displayBrush = true;
dispatch.brushEnd(active);
} else {
displayBrush = false;
}
});
legend.dispatch.on('stateChange', function(newState) {
for(var key in newState) {
state[key] = newState[key];
}
dispatch.stateChange(state);
chart.update();
});
//Update dimensions order and display reset sorting button
parallelCoordinates.dispatch.on('dimensionsOrder', function (e) {
dimensionData.sort(function (a, b) { return a.currentPosition - b.currentPosition; });
var isSorted = false;
dimensionData.forEach(function (d, i) {
d.currentPosition = i;
if (d.currentPosition !== d.originalPosition)
isSorted = true;
});
dispatch.dimensionsOrder(dimensionData, isSorted);
});
// Update chart from a state object passed to event handler
dispatch.on('changeState', function (e) {
if (typeof e.disabled !== 'undefined') {
dimensionData.forEach(function (series, i) {
series.disabled = e.disabled[i];
});
state.disabled = e.disabled;
}
chart.update();
});
});
renderWatch.renderEnd('parraleleCoordinateChart immediate');
return chart;
}
//============================================================
// Event Handling/Dispatching (out of chart's scope)
//------------------------------------------------------------
parallelCoordinates.dispatch.on('elementMouseover.tooltip', function (evt) {
var tp = {
key: evt.label,
color: evt.color,
series: []
}
if(evt.values){
Object.keys(evt.values).forEach(function (d) {
var dim = evt.dimensions.filter(function (dd) {return dd.key === d;})[0];
if(dim){
var v;
if (isNaN(evt.values[d]) || isNaN(parseFloat(evt.values[d]))) {
v = nanValue;
} else {
v = dim.format(evt.values[d]);
}
tp.series.push({ idx: dim.currentPosition, key: d, value: v, color: dim.color });
}
});
tp.series.sort(function(a,b) {return a.idx - b.idx});
}
tooltip.data(tp).hidden(false);
});
parallelCoordinates.dispatch.on('elementMouseout.tooltip', function(evt) {
tooltip.hidden(true)
});
parallelCoordinates.dispatch.on('elementMousemove.tooltip', function () {
tooltip();
});
//============================================================
// Expose Public Variables
//------------------------------------------------------------
// expose chart's sub-components
chart.dispatch = dispatch;
chart.parallelCoordinates = parallelCoordinates;
chart.legend = legend;
chart.tooltip = tooltip;
chart.options = nv.utils.optionsFunc.bind(chart);
chart._options = Object.create({}, {
// simple options, just get/set the necessary values
width: { get: function () { return width; }, set: function (_) { width = _; } },
height: { get: function () { return height; }, set: function (_) { height = _; } },
showLegend: { get: function () { return showLegend; }, set: function (_) { showLegend = _; } },
defaultState: { get: function () { return defaultState; }, set: function (_) { defaultState = _; } },
dimensionData: { get: function () { return dimensionData; }, set: function (_) { dimensionData = _; } },
displayBrush: { get: function () { return displayBrush; }, set: function (_) { displayBrush = _; } },
noData: { get: function () { return noData; }, set: function (_) { noData = _; } },
nanValue: { get: function () { return nanValue; }, set: function (_) { nanValue = _; } },
// options that require extra logic in the setter
margin: {
get: function () { return margin; },
set: function (_) {
margin.top = _.top !== undefined ? _.top : margin.top;
margin.right = _.right !== undefined ? _.right : margin.right;
margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
margin.left = _.left !== undefined ? _.left : margin.left;
}
},
color: {get: function(){return color;}, set: function(_){
color = nv.utils.getColor(_);
legend.color(color);
parallelCoordinates.color(color);
}}
});
nv.utils.inheritOptions(chart, parallelCoordinates);
nv.utils.initOptions(chart);
return chart;
};
nv.models.pie = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var margin = {top: 0, right: 0, bottom: 0, left: 0}
, width = 500
, height = 500
, getX = function(d) { return d.x }
, getY = function(d) { return d.y }
, id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one
, container = null
, color = nv.utils.defaultColor()
, valueFormat = d3.format(',.2f')
, showLabels = true
, labelsOutside = false
, labelType = "key"
, labelThreshold = .02 //if slice percentage is under this, don't show label
, donut = false
, title = false
, growOnHover = true
, titleOffset = 0
, labelSunbeamLayout = false
, startAngle = false
, padAngle = false
, endAngle = false
, cornerRadius = 0
, donutRatio = 0.5
, arcsRadius = []
, dispatch = d3.dispatch('chartClick', 'elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout', 'elementMousemove', 'renderEnd')
;
var arcs = [];
var arcsOver = [];
//============================================================
// chart function
//------------------------------------------------------------
var renderWatch = nv.utils.renderWatch(dispatch);
function chart(selection) {
renderWatch.reset();
selection.each(function(data) {
var availableWidth = width - margin.left - margin.right
, availableHeight = height - margin.top - margin.bottom
, radius = Math.min(availableWidth, availableHeight) / 2
, arcsRadiusOuter = []
, arcsRadiusInner = []
;
container = d3.select(this)
if (arcsRadius.length === 0) {
var outer = radius - radius / 5;
var inner = donutRatio * radius;
for (var i = 0; i < data[0].length; i++) {
arcsRadiusOuter.push(outer);
arcsRadiusInner.push(inner);
}
} else {
if(growOnHover){
arcsRadiusOuter = arcsRadius.map(function (d) { return (d.outer - d.outer / 5) * radius; });
arcsRadiusInner = arcsRadius.map(function (d) { return (d.inner - d.inner / 5) * radius; });
donutRatio = d3.min(arcsRadius.map(function (d) { return (d.inner - d.inner / 5); }));
} else {
arcsRadiusOuter = arcsRadius.map(function (d) { return d.outer * radius; });
arcsRadiusInner = arcsRadius.map(function (d) { return d.inner * radius; });
donutRatio = d3.min(arcsRadius.map(function (d) { return d.inner; }));
}
}
nv.utils.initSVG(container);
// Setup containers and skeleton of chart
var wrap = container.selectAll('.nv-wrap.nv-pie').data(data);
var wrapEnter = wrap.enter().append('g').attr('class','nvd3 nv-wrap nv-pie nv-chart-' + id);
var gEnter = wrapEnter.append('g');
var g = wrap.select('g');
var g_pie = gEnter.append('g').attr('class', 'nv-pie');
gEnter.append('g').attr('class', 'nv-pieLabels');
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
g.select('.nv-pie').attr('transform', 'translate(' + availableWidth / 2 + ',' + availableHeight / 2 + ')');
g.select('.nv-pieLabels').attr('transform', 'translate(' + availableWidth / 2 + ',' + availableHeight / 2 + ')');
//
container.on('click', function(d,i) {
dispatch.chartClick({
data: d,
index: i,
pos: d3.event,
id: id
});
});
arcs = [];
arcsOver = [];
for (var i = 0; i < data[0].length; i++) {
var arc = d3.svg.arc().outerRadius(arcsRadiusOuter[i]);
var arcOver = d3.svg.arc().outerRadius(arcsRadiusOuter[i] + 5);
if (startAngle !== false) {
arc.startAngle(startAngle);
arcOver.startAngle(startAngle);
}
if (endAngle !== false) {
arc.endAngle(endAngle);
arcOver.endAngle(endAngle);
}
if (donut) {
arc.innerRadius(arcsRadiusInner[i]);
arcOver.innerRadius(arcsRadiusInner[i]);
}
if (arc.cornerRadius && cornerRadius) {
arc.cornerRadius(cornerRadius);
arcOver.cornerRadius(cornerRadius);
}
arcs.push(arc);
arcsOver.push(arcOver);
}
// Setup the Pie chart and choose the data element
var pie = d3.layout.pie()
.sort(null)
.value(function(d) { return d.disabled ? 0 : getY(d) });
// padAngle added in d3 3.5
if (pie.padAngle && padAngle) {
pie.padAngle(padAngle);
}
// if title is specified and donut, put it in the middle
if (donut && title) {
g_pie.append("text").attr('class', 'nv-pie-title');
wrap.select('.nv-pie-title')
.style("text-anchor", "middle")
.text(function (d) {
return title;
})
.style("font-size", (Math.min(availableWidth, availableHeight)) * donutRatio * 2 / (title.length + 2) + "px")
.attr("dy", "0.35em") // trick to vertically center text
.attr('transform', function(d, i) {
return 'translate(0, '+ titleOffset + ')';
});
}
var slices = wrap.select('.nv-pie').selectAll('.nv-slice').data(pie);
var pieLabels = wrap.select('.nv-pieLabels').selectAll('.nv-label').data(pie);
slices.exit().remove();
pieLabels.exit().remove();
var ae = slices.enter().append('g');
ae.attr('class', 'nv-slice');
ae.on('mouseover', function(d, i) {
d3.select(this).classed('hover', true);
if (growOnHover) {
d3.select(this).select("path").transition()
.duration(70)
.attr("d", arcsOver[i]);
}
dispatch.elementMouseover({
data: d.data,
index: i,
color: d3.select(this).style("fill"),
percent: (d.endAngle - d.startAngle) / (2 * Math.PI)
});
});
ae.on('mouseout', function(d, i) {
d3.select(this).classed('hover', false);
if (growOnHover) {
d3.select(this).select("path").transition()
.duration(50)
.attr("d", arcs[i]);
}
dispatch.elementMouseout({data: d.data, index: i});
});
ae.on('mousemove', function(d, i) {
dispatch.elementMousemove({data: d.data, index: i});
});
ae.on('click', function(d, i) {
var element = this;
dispatch.elementClick({
data: d.data,
index: i,
color: d3.select(this).style("fill"),
event: d3.event,
element: element
});
});
ae.on('dblclick', function(d, i) {
dispatch.elementDblClick({
data: d.data,
index: i,
color: d3.select(this).style("fill")
});
});
slices.attr('fill', function(d,i) { return color(d.data, i); });
slices.attr('stroke', function(d,i) { return color(d.data, i); });
var paths = ae.append('path').each(function(d) {
this._current = d;
});
slices.select('path')
.transition()
.attr('d', function (d, i) { return arcs[i](d); })
.attrTween('d', arcTween);
if (showLabels) {
// This does the normal label
var labelsArc = [];
for (var i = 0; i < data[0].length; i++) {
labelsArc.push(arcs[i]);
if (labelsOutside) {
if (donut) {
labelsArc[i] = d3.svg.arc().outerRadius(arcs[i].outerRadius());
if (startAngle !== false) labelsArc[i].startAngle(startAngle);
if (endAngle !== false) labelsArc[i].endAngle(endAngle);
}
} else if (!donut) {
labelsArc[i].innerRadius(0);
}
}
pieLabels.enter().append("g").classed("nv-label",true).each(function(d,i) {
var group = d3.select(this);
group.attr('transform', function (d, i) {
if (labelSunbeamLayout) {
d.outerRadius = arcsRadiusOuter[i] + 10; // Set Outer Coordinate
d.innerRadius = arcsRadiusOuter[i] + 15; // Set Inner Coordinate
var rotateAngle = (d.startAngle + d.endAngle) / 2 * (180 / Math.PI);
if ((d.startAngle + d.endAngle) / 2 < Math.PI) {
rotateAngle -= 90;
} else {
rotateAngle += 90;
}
return 'translate(' + labelsArc[i].centroid(d) + ') rotate(' + rotateAngle + ')';
} else {
d.outerRadius = radius + 10; // Set Outer Coordinate
d.innerRadius = radius + 15; // Set Inner Coordinate
return 'translate(' + labelsArc[i].centroid(d) + ')'
}
});
group.append('rect')
.style('stroke', '#fff')
.style('fill', '#fff')
.attr("rx", 3)
.attr("ry", 3);
group.append('text')
.style('text-anchor', labelSunbeamLayout ? ((d.startAngle + d.endAngle) / 2 < Math.PI ? 'start' : 'end') : 'middle') //center the text on it's origin or begin/end if orthogonal aligned
.style('fill', '#000')
});
var labelLocationHash = {};
var avgHeight = 14;
var avgWidth = 140;
var createHashKey = function(coordinates) {
return Math.floor(coordinates[0]/avgWidth) * avgWidth + ',' + Math.floor(coordinates[1]/avgHeight) * avgHeight;
};
var getSlicePercentage = function(d) {
return (d.endAngle - d.startAngle) / (2 * Math.PI);
};
pieLabels.watchTransition(renderWatch, 'pie labels').attr('transform', function (d, i) {
if (labelSunbeamLayout) {
d.outerRadius = arcsRadiusOuter[i] + 10; // Set Outer Coordinate
d.innerRadius = arcsRadiusOuter[i] + 15; // Set Inner Coordinate
var rotateAngle = (d.startAngle + d.endAngle) / 2 * (180 / Math.PI);
if ((d.startAngle + d.endAngle) / 2 < Math.PI) {
rotateAngle -= 90;
} else {
rotateAngle += 90;
}
return 'translate(' + labelsArc[i].centroid(d) + ') rotate(' + rotateAngle + ')';
} else {
d.outerRadius = radius + 10; // Set Outer Coordinate
d.innerRadius = radius + 15; // Set Inner Coordinate
/*
Overlapping pie labels are not good. What this attempts to do is, prevent overlapping.
Each label location is hashed, and if a hash collision occurs, we assume an overlap.
Adjust the label's y-position to remove the overlap.
*/
var center = labelsArc[i].centroid(d);
var percent = getSlicePercentage(d);
if (d.value && percent >= labelThreshold) {
var hashKey = createHashKey(center);
if (labelLocationHash[hashKey]) {
center[1] -= avgHeight;
}
labelLocationHash[createHashKey(center)] = true;
}
return 'translate(' + center + ')'
}
});
pieLabels.select(".nv-label text")
.style('text-anchor', function(d,i) {
//center the text on it's origin or begin/end if orthogonal aligned
return labelSunbeamLayout ? ((d.startAngle + d.endAngle) / 2 < Math.PI ? 'start' : 'end') : 'middle';
})
.text(function(d, i) {
var percent = getSlicePercentage(d);
var label = '';
if (!d.value || percent < labelThreshold) return '';
if(typeof labelType === 'function') {
label = labelType(d, i, {
'key': getX(d.data),
'value': getY(d.data),
'percent': valueFormat(percent)
});
} else {
switch (labelType) {
case 'key':
label = getX(d.data);
break;
case 'value':
label = valueFormat(getY(d.data));
break;
case 'percent':
label = d3.format('%')(percent);
break;
}
}
return label;
})
;
}
// Computes the angle of an arc, converting from radians to degrees.
function angle(d) {
var a = (d.startAngle + d.endAngle) * 90 / Math.PI - 90;
return a > 90 ? a - 180 : a;
}
function arcTween(a, idx) {
a.endAngle = isNaN(a.endAngle) ? 0 : a.endAngle;
a.startAngle = isNaN(a.startAngle) ? 0 : a.startAngle;
if (!donut) a.innerRadius = 0;
var i = d3.interpolate(this._current, a);
this._current = i(0);
return function (t) {
return arcs[idx](i(t));
};
}
});
renderWatch.renderEnd('pie immediate');
return chart;
}
//============================================================
// Expose Public Variables
//------------------------------------------------------------
chart.dispatch = dispatch;
chart.options = nv.utils.optionsFunc.bind(chart);
chart._options = Object.create({}, {
// simple options, just get/set the necessary values
arcsRadius: { get: function () { return arcsRadius; }, set: function (_) { arcsRadius = _; } },
width: {get: function(){return width;}, set: function(_){width=_;}},
height: {get: function(){return height;}, set: function(_){height=_;}},
showLabels: {get: function(){return showLabels;}, set: function(_){showLabels=_;}},
title: {get: function(){return title;}, set: function(_){title=_;}},
titleOffset: {get: function(){return titleOffset;}, set: function(_){titleOffset=_;}},
labelThreshold: {get: function(){return labelThreshold;}, set: function(_){labelThreshold=_;}},
valueFormat: {get: function(){return valueFormat;}, set: function(_){valueFormat=_;}},
x: {get: function(){return getX;}, set: function(_){getX=_;}},
id: {get: function(){return id;}, set: function(_){id=_;}},
endAngle: {get: function(){return endAngle;}, set: function(_){endAngle=_;}},
startAngle: {get: function(){return startAngle;}, set: function(_){startAngle=_;}},
padAngle: {get: function(){return padAngle;}, set: function(_){padAngle=_;}},
cornerRadius: {get: function(){return cornerRadius;}, set: function(_){cornerRadius=_;}},
donutRatio: {get: function(){return donutRatio;}, set: function(_){donutRatio=_;}},
labelsOutside: {get: function(){return labelsOutside;}, set: function(_){labelsOutside=_;}},
labelSunbeamLayout: {get: function(){return labelSunbeamLayout;}, set: function(_){labelSunbeamLayout=_;}},
donut: {get: function(){return donut;}, set: function(_){donut=_;}},
growOnHover: {get: function(){return growOnHover;}, set: function(_){growOnHover=_;}},
// depreciated after 1.7.1
pieLabelsOutside: {get: function(){return labelsOutside;}, set: function(_){
labelsOutside=_;
nv.deprecated('pieLabelsOutside', 'use labelsOutside instead');
}},
// depreciated after 1.7.1
donutLabelsOutside: {get: function(){return labelsOutside;}, set: function(_){
labelsOutside=_;
nv.deprecated('donutLabelsOutside', 'use labelsOutside instead');
}},
// deprecated after 1.7.1
labelFormat: {get: function(){ return valueFormat;}, set: function(_) {
valueFormat=_;
nv.deprecated('labelFormat','use valueFormat instead');
}},
// options that require extra logic in the setter
margin: {get: function(){return margin;}, set: function(_){
margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
}},
y: {get: function(){return getY;}, set: function(_){
getY=d3.functor(_);
}},
color: {get: function(){return color;}, set: function(_){
color=nv.utils.getColor(_);
}},
labelType: {get: function(){return labelType;}, set: function(_){
labelType= _ || 'key';
}}
});
nv.utils.initOptions(chart);
return chart;
};
nv.models.pieChart = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var pie = nv.models.pie();
var legend = nv.models.legend();
var tooltip = nv.models.tooltip();
var margin = {top: 30, right: 20, bottom: 20, left: 20}
, width = null
, height = null
, showTooltipPercent = false
, showLegend = true
, legendPosition = "top"
, color = nv.utils.defaultColor()
, state = nv.utils.state()
, defaultState = null
, noData = null
, duration = 250
, dispatch = d3.dispatch('stateChange', 'changeState','renderEnd')
;
tooltip
.duration(0)
.headerEnabled(false)
.valueFormatter(function(d, i) {
return pie.valueFormat()(d, i);
});
//============================================================
// Private Variables
//------------------------------------------------------------
var renderWatch = nv.utils.renderWatch(dispatch);
var stateGetter = function(data) {
return function(){
return {
active: data.map(function(d) { return !d.disabled })
};
}
};
var stateSetter = function(data) {
return function(state) {
if (state.active !== undefined) {
data.forEach(function (series, i) {
series.disabled = !state.active[i];
});
}
}
};
//============================================================
// Chart function
//------------------------------------------------------------
function chart(selection) {
renderWatch.reset();
renderWatch.models(pie);
selection.each(function(data) {
var container = d3.select(this);
nv.utils.initSVG(container);
var that = this;
var availableWidth = nv.utils.availableWidth(width, container, margin),
availableHeight = nv.utils.availableHeight(height, container, margin);
chart.update = function() { container.transition().call(chart); };
chart.container = this;
state.setter(stateSetter(data), chart.update)
.getter(stateGetter(data))
.update();
//set state.disabled
state.disabled = data.map(function(d) { return !!d.disabled });
if (!defaultState) {
var key;
defaultState = {};
for (key in state) {
if (state[key] instanceof Array)
defaultState[key] = state[key].slice(0);
else
defaultState[key] = state[key];
}
}
// Display No Data message if there's nothing to show.
if (!data || !data.length) {
nv.utils.noData(chart, container);
return chart;
} else {
container.selectAll('.nv-noData').remove();
}
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-pieChart').data([data]);
var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-pieChart').append('g');
var g = wrap.select('g');
gEnter.append('g').attr('class', 'nv-pieWrap');
gEnter.append('g').attr('class', 'nv-legendWrap');
// Legend
if (!showLegend) {
g.select('.nv-legendWrap').selectAll('*').remove();
} else {
if (legendPosition === "top") {
legend.width( availableWidth ).key(pie.x());
wrap.select('.nv-legendWrap')
.datum(data)
.call(legend);
if ( margin.top != legend.height()) {
margin.top = legend.height();
availableHeight = nv.utils.availableHeight(height, container, margin);
}
wrap.select('.nv-legendWrap')
.attr('transform', 'translate(0,' + (-margin.top) +')');
} else if (legendPosition === "right") {
var legendWidth = nv.models.legend().width();
if (availableWidth / 2 < legendWidth) {
legendWidth = (availableWidth / 2)
}
legend.height(availableHeight).key(pie.x());
legend.width(legendWidth);
availableWidth -= legend.width();
wrap.select('.nv-legendWrap')
.datum(data)
.call(legend)
.attr('transform', 'translate(' + (availableWidth) +',0)');
}
}
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
// Main Chart Component(s)
pie.width(availableWidth).height(availableHeight);
var pieWrap = g.select('.nv-pieWrap').datum([data]);
d3.transition(pieWrap).call(pie);
//============================================================
// Event Handling/Dispatching (in chart's scope)
//------------------------------------------------------------
legend.dispatch.on('stateChange', function(newState) {
for (var key in newState) {
state[key] = newState[key];
}
dispatch.stateChange(state);
chart.update();
});
// Update chart from a state object passed to event handler
dispatch.on('changeState', function(e) {
if (typeof e.disabled !== 'undefined') {
data.forEach(function(series,i) {
series.disabled = e.disabled[i];
});
state.disabled = e.disabled;
}
chart.update();
});
});
renderWatch.renderEnd('pieChart immediate');
return chart;
}
//============================================================
// Event Handling/Dispatching (out of chart's scope)
//------------------------------------------------------------
pie.dispatch.on('elementMouseover.tooltip', function(evt) {
evt['series'] = {
key: chart.x()(evt.data),
value: chart.y()(evt.data),
color: evt.color,
percent: evt.percent
};
if (!showTooltipPercent) {
delete evt.percent;
delete evt.series.percent;
}
tooltip.data(evt).hidden(false);
});
pie.dispatch.on('elementMouseout.tooltip', function(evt) {
tooltip.hidden(true);
});
pie.dispatch.on('elementMousemove.tooltip', function(evt) {
tooltip();
});
//============================================================
// Expose Public Variables
//------------------------------------------------------------
// expose chart's sub-components
chart.legend = legend;
chart.dispatch = dispatch;
chart.pie = pie;
chart.tooltip = tooltip;
chart.options = nv.utils.optionsFunc.bind(chart);
// use Object get/set functionality to map between vars and chart functions
chart._options = Object.create({}, {
// simple options, just get/set the necessary values
width: {get: function(){return width;}, set: function(_){width=_;}},
height: {get: function(){return height;}, set: function(_){height=_;}},
noData: {get: function(){return noData;}, set: function(_){noData=_;}},
showTooltipPercent: {get: function(){return showTooltipPercent;}, set: function(_){showTooltipPercent=_;}},
showLegend: {get: function(){return showLegend;}, set: function(_){showLegend=_;}},
legendPosition: {get: function(){return legendPosition;}, set: function(_){legendPosition=_;}},
defaultState: {get: function(){return defaultState;}, set: function(_){defaultState=_;}},
// options that require extra logic in the setter
color: {get: function(){return color;}, set: function(_){
color = _;
legend.color(color);
pie.color(color);
}},
duration: {get: function(){return duration;}, set: function(_){
duration = _;
renderWatch.reset(duration);
}},
margin: {get: function(){return margin;}, set: function(_){
margin.top = _.top !== undefined ? _.top : margin.top;
margin.right = _.right !== undefined ? _.right : margin.right;
margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
margin.left = _.left !== undefined ? _.left : margin.left;
}}
});
nv.utils.inheritOptions(chart, pie);
nv.utils.initOptions(chart);
return chart;
};
nv.models.scatter = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var margin = {top: 0, right: 0, bottom: 0, left: 0}
, width = null
, height = null
, color = nv.utils.defaultColor() // chooses color
, id = Math.floor(Math.random() * 100000) //Create semi-unique ID incase user doesn't select one
, container = null
, x = d3.scale.linear()
, y = d3.scale.linear()
, z = d3.scale.linear() //linear because d3.svg.shape.size is treated as area
, getX = function(d) { return d.x } // accessor to get the x value
, getY = function(d) { return d.y } // accessor to get the y value
, getSize = function(d) { return d.size || 1} // accessor to get the point size
, getShape = function(d) { return d.shape || 'circle' } // accessor to get point shape
, forceX = [] // List of numbers to Force into the X scale (ie. 0, or a max / min, etc.)
, forceY = [] // List of numbers to Force into the Y scale
, forceSize = [] // List of numbers to Force into the Size scale
, interactive = true // If true, plots a voronoi overlay for advanced point intersection
, pointActive = function(d) { return !d.notActive } // any points that return false will be filtered out
, padData = false // If true, adds half a data points width to front and back, for lining up a line chart with a bar chart
, padDataOuter = .1 //outerPadding to imitate ordinal scale outer padding
, clipEdge = false // if true, masks points within x and y scale
, clipVoronoi = true // if true, masks each point with a circle... can turn off to slightly increase performance
, showVoronoi = false // display the voronoi areas
, clipRadius = function() { return 25 } // function to get the radius for voronoi point clips
, xDomain = null // Override x domain (skips the calculation from data)
, yDomain = null // Override y domain
, xRange = null // Override x range
, yRange = null // Override y range
, sizeDomain = null // Override point size domain
, sizeRange = null
, singlePoint = false
, dispatch = d3.dispatch('elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout', 'renderEnd')
, useVoronoi = true
, duration = 250
, interactiveUpdateDelay = 300
, showLabels = false
;
//============================================================
// Private Variables
//------------------------------------------------------------
var x0, y0, z0 // used to store previous scales
, timeoutID
, needsUpdate = false // Flag for when the points are visually updating, but the interactive layer is behind, to disable tooltips
, renderWatch = nv.utils.renderWatch(dispatch, duration)
, _sizeRange_def = [16, 256]
, _caches
;
function getCache(d) {
var cache, i;
cache = _caches = _caches || {};
i = d[0].series;
cache = cache[i] = cache[i] || {};
i = d[1];
cache = cache[i] = cache[i] || {};
return cache;
}
function getDiffs(d) {
var i, key,
point = d[0],
cache = getCache(d),
diffs = false;
for (i = 1; i < arguments.length; i ++) {
key = arguments[i];
if (cache[key] !== point[key] || !cache.hasOwnProperty(key)) {
cache[key] = point[key];
diffs = true;
}
}
return diffs;
}
function chart(selection) {
renderWatch.reset();
selection.each(function(data) {
container = d3.select(this);
var availableWidth = nv.utils.availableWidth(width, container, margin),
availableHeight = nv.utils.availableHeight(height, container, margin);
nv.utils.initSVG(container);
//add series index to each data point for reference
data.forEach(function(series, i) {
series.values.forEach(function(point) {
point.series = i;
});
});
// Setup Scales
var logScale = chart.yScale().name === d3.scale.log().name ? true : false;
// remap and flatten the data for use in calculating the scales' domains
var seriesData = (xDomain && yDomain && sizeDomain) ? [] : // if we know xDomain and yDomain and sizeDomain, no need to calculate.... if Size is constant remember to set sizeDomain to speed up performance
d3.merge(
data.map(function(d) {
return d.values.map(function(d,i) {
return { x: getX(d,i), y: getY(d,i), size: getSize(d,i) }
})
})
);
x .domain(xDomain || d3.extent(seriesData.map(function(d) { return d.x; }).concat(forceX)))
if (padData && data[0])
x.range(xRange || [(availableWidth * padDataOuter + availableWidth) / (2 *data[0].values.length), availableWidth - availableWidth * (1 + padDataOuter) / (2 * data[0].values.length) ]);
//x.range([availableWidth * .5 / data[0].values.length, availableWidth * (data[0].values.length - .5) / data[0].values.length ]);
else
x.range(xRange || [0, availableWidth]);
if (logScale) {
var min = d3.min(seriesData.map(function(d) { if (d.y !== 0) return d.y; }));
y.clamp(true)
.domain(yDomain || d3.extent(seriesData.map(function(d) {
if (d.y !== 0) return d.y;
else return min * 0.1;
}).concat(forceY)))
.range(yRange || [availableHeight, 0]);
} else {
y.domain(yDomain || d3.extent(seriesData.map(function (d) { return d.y;}).concat(forceY)))
.range(yRange || [availableHeight, 0]);
}
z .domain(sizeDomain || d3.extent(seriesData.map(function(d) { return d.size }).concat(forceSize)))
.range(sizeRange || _sizeRange_def);
// If scale's domain don't have a range, slightly adjust to make one... so a chart can show a single data point
singlePoint = x.domain()[0] === x.domain()[1] || y.domain()[0] === y.domain()[1];
if (x.domain()[0] === x.domain()[1])
x.domain()[0] ?
x.domain([x.domain()[0] - x.domain()[0] * 0.01, x.domain()[1] + x.domain()[1] * 0.01])
: x.domain([-1,1]);
if (y.domain()[0] === y.domain()[1])
y.domain()[0] ?
y.domain([y.domain()[0] - y.domain()[0] * 0.01, y.domain()[1] + y.domain()[1] * 0.01])
: y.domain([-1,1]);
if ( isNaN(x.domain()[0])) {
x.domain([-1,1]);
}
if ( isNaN(y.domain()[0])) {
y.domain([-1,1]);
}
x0 = x0 || x;
y0 = y0 || y;
z0 = z0 || z;
var scaleDiff = x(1) !== x0(1) || y(1) !== y0(1) || z(1) !== z0(1);
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-scatter').data([data]);
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-scatter nv-chart-' + id);
var defsEnter = wrapEnter.append('defs');
var gEnter = wrapEnter.append('g');
var g = wrap.select('g');
wrap.classed('nv-single-point', singlePoint);
gEnter.append('g').attr('class', 'nv-groups');
gEnter.append('g').attr('class', 'nv-point-paths');
wrapEnter.append('g').attr('class', 'nv-point-clips');
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
defsEnter.append('clipPath')
.attr('id', 'nv-edge-clip-' + id)
.append('rect');
wrap.select('#nv-edge-clip-' + id + ' rect')
.attr('width', availableWidth)
.attr('height', (availableHeight > 0) ? availableHeight : 0);
g.attr('clip-path', clipEdge ? 'url(#nv-edge-clip-' + id + ')' : '');
function updateInteractiveLayer() {
// Always clear needs-update flag regardless of whether or not
// we will actually do anything (avoids needless invocations).
needsUpdate = false;
if (!interactive) return false;
// inject series and point index for reference into voronoi
if (useVoronoi === true) {
var vertices = d3.merge(data.map(function(group, groupIndex) {
return group.values
.map(function(point, pointIndex) {
// *Adding noise to make duplicates very unlikely
// *Injecting series and point index for reference
/* *Adding a 'jitter' to the points, because there's an issue in d3.geom.voronoi.
*/
var pX = getX(point,pointIndex);
var pY = getY(point,pointIndex);
return [nv.utils.NaNtoZero(x(pX))+ Math.random() * 1e-4,
nv.utils.NaNtoZero(y(pY))+ Math.random() * 1e-4,
groupIndex,
pointIndex, point]; //temp hack to add noise until I think of a better way so there are no duplicates
})
.filter(function(pointArray, pointIndex) {
return pointActive(pointArray[4], pointIndex); // Issue #237.. move filter to after map, so pointIndex is correct!
})
})
);
if (vertices.length == 0) return false; // No active points, we're done
if (vertices.length < 3) {
// Issue #283 - Adding 2 dummy points to the voronoi b/c voronoi requires min 3 points to work
vertices.push([x.range()[0] - 20, y.range()[0] - 20, null, null]);
vertices.push([x.range()[1] + 20, y.range()[1] + 20, null, null]);
vertices.push([x.range()[0] - 20, y.range()[0] + 20, null, null]);
vertices.push([x.range()[1] + 20, y.range()[1] - 20, null, null]);
}
// keep voronoi sections from going more than 10 outside of graph
// to avoid overlap with other things like legend etc
var bounds = d3.geom.polygon([
[-10,-10],
[-10,height + 10],
[width + 10,height + 10],
[width + 10,-10]
]);
var voronoi = d3.geom.voronoi(vertices).map(function(d, i) {
return {
'data': bounds.clip(d),
'series': vertices[i][2],
'point': vertices[i][3]
}
});
// nuke all voronoi paths on reload and recreate them
wrap.select('.nv-point-paths').selectAll('path').remove();
var pointPaths = wrap.select('.nv-point-paths').selectAll('path').data(voronoi);
var vPointPaths = pointPaths
.enter().append("svg:path")
.attr("d", function(d) {
if (!d || !d.data || d.data.length === 0)
return 'M 0 0';
else
return "M" + d.data.join(",") + "Z";
})
.attr("id", function(d,i) {
return "nv-path-"+i; })
.attr("clip-path", function(d,i) { return "url(#nv-clip-"+id+"-"+i+")"; })
;
// good for debugging point hover issues
if (showVoronoi) {
vPointPaths.style("fill", d3.rgb(230, 230, 230))
.style('fill-opacity', 0.4)
.style('stroke-opacity', 1)
.style("stroke", d3.rgb(200,200,200));
}
if (clipVoronoi) {
// voronoi sections are already set to clip,
// just create the circles with the IDs they expect
wrap.select('.nv-point-clips').selectAll('*').remove(); // must do * since it has sub-dom
var pointClips = wrap.select('.nv-point-clips').selectAll('clipPath').data(vertices);
var vPointClips = pointClips
.enter().append("svg:clipPath")
.attr("id", function(d, i) { return "nv-clip-"+id+"-"+i;})
.append("svg:circle")
.attr('cx', function(d) { return d[0]; })
.attr('cy', function(d) { return d[1]; })
.attr('r', clipRadius);
}
var mouseEventCallback = function(d, mDispatch) {
if (needsUpdate) return 0;
var series = data[d.series];
if (series === undefined) return;
var point = series.values[d.point];
point['color'] = color(series, d.series);
// standardize attributes for tooltip.
point['x'] = getX(point);
point['y'] = getY(point);
// can't just get box of event node since it's actually a voronoi polygon
var box = container.node().getBoundingClientRect();
var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
var scrollLeft = window.pageXOffset || document.documentElement.scrollLeft;
var pos = {
left: x(getX(point, d.point)) + box.left + scrollLeft + margin.left + 10,
top: y(getY(point, d.point)) + box.top + scrollTop + margin.top + 10
};
mDispatch({
point: point,
series: series,
pos: pos,
relativePos: [x(getX(point, d.point)) + margin.left, y(getY(point, d.point)) + margin.top],
seriesIndex: d.series,
pointIndex: d.point
});
};
pointPaths
.on('click', function(d) {
mouseEventCallback(d, dispatch.elementClick);
})
.on('dblclick', function(d) {
mouseEventCallback(d, dispatch.elementDblClick);
})
.on('mouseover', function(d) {
mouseEventCallback(d, dispatch.elementMouseover);
})
.on('mouseout', function(d, i) {
mouseEventCallback(d, dispatch.elementMouseout);
});
} else {
// add event handlers to points instead voronoi paths
wrap.select('.nv-groups').selectAll('.nv-group')
.selectAll('.nv-point')
//.data(dataWithPoints)
//.style('pointer-events', 'auto') // recativate events, disabled by css
.on('click', function(d,i) {
//nv.log('test', d, i);
if (needsUpdate || !data[d.series]) return 0; //check if this is a dummy point
var series = data[d.series],
point = series.values[i];
dispatch.elementClick({
point: point,
series: series,
pos: [x(getX(point, i)) + margin.left, y(getY(point, i)) + margin.top], //TODO: make this pos base on the page
relativePos: [x(getX(point, i)) + margin.left, y(getY(point, i)) + margin.top],
seriesIndex: d.series,
pointIndex: i
});
})
.on('dblclick', function(d,i) {
if (needsUpdate || !data[d.series]) return 0; //check if this is a dummy point
var series = data[d.series],
point = series.values[i];
dispatch.elementDblClick({
point: point,
series: series,
pos: [x(getX(point, i)) + margin.left, y(getY(point, i)) + margin.top],//TODO: make this pos base on the page
relativePos: [x(getX(point, i)) + margin.left, y(getY(point, i)) + margin.top],
seriesIndex: d.series,
pointIndex: i
});
})
.on('mouseover', function(d,i) {
if (needsUpdate || !data[d.series]) return 0; //check if this is a dummy point
var series = data[d.series],
point = series.values[i];
dispatch.elementMouseover({
point: point,
series: series,
pos: [x(getX(point, i)) + margin.left, y(getY(point, i)) + margin.top],//TODO: make this pos base on the page
relativePos: [x(getX(point, i)) + margin.left, y(getY(point, i)) + margin.top],
seriesIndex: d.series,
pointIndex: i,
color: color(d, i)
});
})
.on('mouseout', function(d,i) {
if (needsUpdate || !data[d.series]) return 0; //check if this is a dummy point
var series = data[d.series],
point = series.values[i];
dispatch.elementMouseout({
point: point,
series: series,
pos: [x(getX(point, i)) + margin.left, y(getY(point, i)) + margin.top],//TODO: make this pos base on the page
relativePos: [x(getX(point, i)) + margin.left, y(getY(point, i)) + margin.top],
seriesIndex: d.series,
pointIndex: i,
color: color(d, i)
});
});
}
}
needsUpdate = true;
var groups = wrap.select('.nv-groups').selectAll('.nv-group')
.data(function(d) { return d }, function(d) { return d.key });
groups.enter().append('g')
.style('stroke-opacity', 1e-6)
.style('fill-opacity', 1e-6);
groups.exit()
.remove();
groups
.attr('class', function(d,i) {
return (d.classed || '') + ' nv-group nv-series-' + i;
})
.classed('nv-noninteractive', !interactive)
.classed('hover', function(d) { return d.hover });
groups.watchTransition(renderWatch, 'scatter: groups')
.style('fill', function(d,i) { return color(d, i) })
.style('stroke', function(d,i) { return color(d, i) })
.style('stroke-opacity', 1)
.style('fill-opacity', .5);
// create the points, maintaining their IDs from the original data set
var points = groups.selectAll('path.nv-point')
.data(function(d) {
return d.values.map(
function (point, pointIndex) {
return [point, pointIndex]
}).filter(
function(pointArray, pointIndex) {
return pointActive(pointArray[0], pointIndex)
})
});
points.enter().append('path')
.attr('class', function (d) {
return 'nv-point nv-point-' + d[1];
})
.style('fill', function (d) { return d.color })
.style('stroke', function (d) { return d.color })
.attr('transform', function(d) {
return 'translate(' + nv.utils.NaNtoZero(x0(getX(d[0],d[1]))) + ',' + nv.utils.NaNtoZero(y0(getY(d[0],d[1]))) + ')'
})
.attr('d',
nv.utils.symbol()
.type(function(d) { return getShape(d[0]); })
.size(function(d) { return z(getSize(d[0],d[1])) })
);
points.exit().remove();
groups.exit().selectAll('path.nv-point')
.watchTransition(renderWatch, 'scatter exit')
.attr('transform', function(d) {
return 'translate(' + nv.utils.NaNtoZero(x(getX(d[0],d[1]))) + ',' + nv.utils.NaNtoZero(y(getY(d[0],d[1]))) + ')'
})
.remove();
points.filter(function (d) { return scaleDiff || getDiffs(d, 'x', 'y'); })
.watchTransition(renderWatch, 'scatter points')
.attr('transform', function(d) {
//nv.log(d, getX(d[0],d[1]), x(getX(d[0],d[1])));
return 'translate(' + nv.utils.NaNtoZero(x(getX(d[0],d[1]))) + ',' + nv.utils.NaNtoZero(y(getY(d[0],d[1]))) + ')'
});
points.filter(function (d) { return scaleDiff || getDiffs(d, 'shape', 'size'); })
.watchTransition(renderWatch, 'scatter points')
.attr('d',
nv.utils.symbol()
.type(function(d) { return getShape(d[0]); })
.size(function(d) { return z(getSize(d[0],d[1])) })
);
// add label a label to scatter chart
if(showLabels)
{
var titles = groups.selectAll('.nv-label')
.data(function(d) {
return d.values.map(
function (point, pointIndex) {
return [point, pointIndex]
}).filter(
function(pointArray, pointIndex) {
return pointActive(pointArray[0], pointIndex)
})
});
titles.enter().append('text')
.style('fill', function (d,i) {
return d.color })
.style('stroke-opacity', 0)
.style('fill-opacity', 1)
.attr('transform', function(d) {
var dx = nv.utils.NaNtoZero(x0(getX(d[0],d[1]))) + Math.sqrt(z(getSize(d[0],d[1]))/Math.PI) + 2;
return 'translate(' + dx + ',' + nv.utils.NaNtoZero(y0(getY(d[0],d[1]))) + ')';
})
.text(function(d,i){
return d[0].label;});
titles.exit().remove();
groups.exit().selectAll('path.nv-label')
.watchTransition(renderWatch, 'scatter exit')
.attr('transform', function(d) {
var dx = nv.utils.NaNtoZero(x(getX(d[0],d[1])))+ Math.sqrt(z(getSize(d[0],d[1]))/Math.PI)+2;
return 'translate(' + dx + ',' + nv.utils.NaNtoZero(y(getY(d[0],d[1]))) + ')';
})
.remove();
titles.each(function(d) {
d3.select(this)
.classed('nv-label', true)
.classed('nv-label-' + d[1], false)
.classed('hover',false);
});
titles.watchTransition(renderWatch, 'scatter labels')
.attr('transform', function(d) {
var dx = nv.utils.NaNtoZero(x(getX(d[0],d[1])))+ Math.sqrt(z(getSize(d[0],d[1]))/Math.PI)+2;
return 'translate(' + dx + ',' + nv.utils.NaNtoZero(y(getY(d[0],d[1]))) + ')'
});
}
// Delay updating the invisible interactive layer for smoother animation
if( interactiveUpdateDelay )
{
clearTimeout(timeoutID); // stop repeat calls to updateInteractiveLayer
timeoutID = setTimeout(updateInteractiveLayer, interactiveUpdateDelay );
}
else
{
updateInteractiveLayer();
}
//store old scales for use in transitions on update
x0 = x.copy();
y0 = y.copy();
z0 = z.copy();
});
renderWatch.renderEnd('scatter immediate');
return chart;
}
//============================================================
// Expose Public Variables
//------------------------------------------------------------
chart.dispatch = dispatch;
chart.options = nv.utils.optionsFunc.bind(chart);
// utility function calls provided by this chart
chart._calls = new function() {
this.clearHighlights = function () {
nv.dom.write(function() {
container.selectAll(".nv-point.hover").classed("hover", false);
});
return null;
};
this.highlightPoint = function (seriesIndex, pointIndex, isHoverOver) {
nv.dom.write(function() {
container.select('.nv-groups')
.selectAll(".nv-series-" + seriesIndex)
.selectAll(".nv-point-" + pointIndex)
.classed("hover", isHoverOver);
});
};
};
// trigger calls from events too
dispatch.on('elementMouseover.point', function(d) {
if (interactive) chart._calls.highlightPoint(d.seriesIndex,d.pointIndex,true);
});
dispatch.on('elementMouseout.point', function(d) {
if (interactive) chart._calls.highlightPoint(d.seriesIndex,d.pointIndex,false);
});
chart._options = Object.create({}, {
// simple options, just get/set the necessary values
width: {get: function(){return width;}, set: function(_){width=_;}},
height: {get: function(){return height;}, set: function(_){height=_;}},
xScale: {get: function(){return x;}, set: function(_){x=_;}},
yScale: {get: function(){return y;}, set: function(_){y=_;}},
pointScale: {get: function(){return z;}, set: function(_){z=_;}},
xDomain: {get: function(){return xDomain;}, set: function(_){xDomain=_;}},
yDomain: {get: function(){return yDomain;}, set: function(_){yDomain=_;}},
pointDomain: {get: function(){return sizeDomain;}, set: function(_){sizeDomain=_;}},
xRange: {get: function(){return xRange;}, set: function(_){xRange=_;}},
yRange: {get: function(){return yRange;}, set: function(_){yRange=_;}},
pointRange: {get: function(){return sizeRange;}, set: function(_){sizeRange=_;}},
forceX: {get: function(){return forceX;}, set: function(_){forceX=_;}},
forceY: {get: function(){return forceY;}, set: function(_){forceY=_;}},
forcePoint: {get: function(){return forceSize;}, set: function(_){forceSize=_;}},
interactive: {get: function(){return interactive;}, set: function(_){interactive=_;}},
pointActive: {get: function(){return pointActive;}, set: function(_){pointActive=_;}},
padDataOuter: {get: function(){return padDataOuter;}, set: function(_){padDataOuter=_;}},
padData: {get: function(){return padData;}, set: function(_){padData=_;}},
clipEdge: {get: function(){return clipEdge;}, set: function(_){clipEdge=_;}},
clipVoronoi: {get: function(){return clipVoronoi;}, set: function(_){clipVoronoi=_;}},
clipRadius: {get: function(){return clipRadius;}, set: function(_){clipRadius=_;}},
showVoronoi: {get: function(){return showVoronoi;}, set: function(_){showVoronoi=_;}},
id: {get: function(){return id;}, set: function(_){id=_;}},
interactiveUpdateDelay: {get:function(){return interactiveUpdateDelay;}, set: function(_){interactiveUpdateDelay=_;}},
showLabels: {get: function(){return showLabels;}, set: function(_){ showLabels = _;}},
// simple functor options
x: {get: function(){return getX;}, set: function(_){getX = d3.functor(_);}},
y: {get: function(){return getY;}, set: function(_){getY = d3.functor(_);}},
pointSize: {get: function(){return getSize;}, set: function(_){getSize = d3.functor(_);}},
pointShape: {get: function(){return getShape;}, set: function(_){getShape = d3.functor(_);}},
// options that require extra logic in the setter
margin: {get: function(){return margin;}, set: function(_){
margin.top = _.top !== undefined ? _.top : margin.top;
margin.right = _.right !== undefined ? _.right : margin.right;
margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
margin.left = _.left !== undefined ? _.left : margin.left;
}},
duration: {get: function(){return duration;}, set: function(_){
duration = _;
renderWatch.reset(duration);
}},
color: {get: function(){return color;}, set: function(_){
color = nv.utils.getColor(_);
}},
useVoronoi: {get: function(){return useVoronoi;}, set: function(_){
useVoronoi = _;
if (useVoronoi === false) {
clipVoronoi = false;
}
}}
});
nv.utils.initOptions(chart);
return chart;
};
nv.models.scatterChart = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var scatter = nv.models.scatter()
, xAxis = nv.models.axis()
, yAxis = nv.models.axis()
, legend = nv.models.legend()
, distX = nv.models.distribution()
, distY = nv.models.distribution()
, tooltip = nv.models.tooltip()
;
var margin = {top: 30, right: 20, bottom: 50, left: 75}
, width = null
, height = null
, container = null
, color = nv.utils.defaultColor()
, x = scatter.xScale()
, y = scatter.yScale()
, showDistX = false
, showDistY = false
, showLegend = true
, showXAxis = true
, showYAxis = true
, rightAlignYAxis = false
, state = nv.utils.state()
, defaultState = null
, dispatch = d3.dispatch('stateChange', 'changeState', 'renderEnd')
, noData = null
, duration = 250
, showLabels = false
;
scatter.xScale(x).yScale(y);
xAxis.orient('bottom').tickPadding(10);
yAxis
.orient((rightAlignYAxis) ? 'right' : 'left')
.tickPadding(10)
;
distX.axis('x');
distY.axis('y');
tooltip
.headerFormatter(function(d, i) {
return xAxis.tickFormat()(d, i);
})
.valueFormatter(function(d, i) {
return yAxis.tickFormat()(d, i);
});
//============================================================
// Private Variables
//------------------------------------------------------------
var x0, y0
, renderWatch = nv.utils.renderWatch(dispatch, duration);
var stateGetter = function(data) {
return function(){
return {
active: data.map(function(d) { return !d.disabled })
};
}
};
var stateSetter = function(data) {
return function(state) {
if (state.active !== undefined)
data.forEach(function(series,i) {
series.disabled = !state.active[i];
});
}
};
function chart(selection) {
renderWatch.reset();
renderWatch.models(scatter);
if (showXAxis) renderWatch.models(xAxis);
if (showYAxis) renderWatch.models(yAxis);
if (showDistX) renderWatch.models(distX);
if (showDistY) renderWatch.models(distY);
selection.each(function(data) {
var that = this;
container = d3.select(this);
nv.utils.initSVG(container);
var availableWidth = nv.utils.availableWidth(width, container, margin),
availableHeight = nv.utils.availableHeight(height, container, margin);
chart.update = function() {
if (duration === 0)
container.call(chart);
else
container.transition().duration(duration).call(chart);
};
chart.container = this;
state
.setter(stateSetter(data), chart.update)
.getter(stateGetter(data))
.update();
// DEPRECATED set state.disableddisabled
state.disabled = data.map(function(d) { return !!d.disabled });
if (!defaultState) {
var key;
defaultState = {};
for (key in state) {
if (state[key] instanceof Array)
defaultState[key] = state[key].slice(0);
else
defaultState[key] = state[key];
}
}
// Display noData message if there's nothing to show.
if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) {
nv.utils.noData(chart, container);
renderWatch.renderEnd('scatter immediate');
return chart;
} else {
container.selectAll('.nv-noData').remove();
}
// Setup Scales
x = scatter.xScale();
y = scatter.yScale();
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-scatterChart').data([data]);
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-scatterChart nv-chart-' + scatter.id());
var gEnter = wrapEnter.append('g');
var g = wrap.select('g');
// background for pointer events
gEnter.append('rect').attr('class', 'nvd3 nv-background').style("pointer-events","none");
gEnter.append('g').attr('class', 'nv-x nv-axis');
gEnter.append('g').attr('class', 'nv-y nv-axis');
gEnter.append('g').attr('class', 'nv-scatterWrap');
gEnter.append('g').attr('class', 'nv-regressionLinesWrap');
gEnter.append('g').attr('class', 'nv-distWrap');
gEnter.append('g').attr('class', 'nv-legendWrap');
if (rightAlignYAxis) {
g.select(".nv-y.nv-axis")
.attr("transform", "translate(" + availableWidth + ",0)");
}
// Legend
if (!showLegend) {
g.select('.nv-legendWrap').selectAll('*').remove();
} else {
var legendWidth = availableWidth;
legend.width(legendWidth);
wrap.select('.nv-legendWrap')
.datum(data)
.call(legend);
if ( margin.top != legend.height()) {
margin.top = legend.height();
availableHeight = nv.utils.availableHeight(height, container, margin);
}
wrap.select('.nv-legendWrap')
.attr('transform', 'translate(0' + ',' + (-margin.top) +')');
}
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
// Main Chart Component(s)
scatter
.width(availableWidth)
.height(availableHeight)
.color(data.map(function(d,i) {
d.color = d.color || color(d, i);
return d.color;
}).filter(function(d,i) { return !data[i].disabled }))
.showLabels(showLabels);
wrap.select('.nv-scatterWrap')
.datum(data.filter(function(d) { return !d.disabled }))
.call(scatter);
wrap.select('.nv-regressionLinesWrap')
.attr('clip-path', 'url(#nv-edge-clip-' + scatter.id() + ')');
var regWrap = wrap.select('.nv-regressionLinesWrap').selectAll('.nv-regLines')
.data(function (d) {
return d;
});
regWrap.enter().append('g').attr('class', 'nv-regLines');
var regLine = regWrap.selectAll('.nv-regLine')
.data(function (d) {
return [d]
});
regLine.enter()
.append('line').attr('class', 'nv-regLine')
.style('stroke-opacity', 0);
// don't add lines unless we have slope and intercept to use
regLine.filter(function(d) {
return d.intercept && d.slope;
})
.watchTransition(renderWatch, 'scatterPlusLineChart: regline')
.attr('x1', x.range()[0])
.attr('x2', x.range()[1])
.attr('y1', function (d, i) {
return y(x.domain()[0] * d.slope + d.intercept)
})
.attr('y2', function (d, i) {
return y(x.domain()[1] * d.slope + d.intercept)
})
.style('stroke', function (d, i, j) {
return color(d, j)
})
.style('stroke-opacity', function (d, i) {
return (d.disabled || typeof d.slope === 'undefined' || typeof d.intercept === 'undefined') ? 0 : 1
});
// Setup Axes
if (showXAxis) {
xAxis
.scale(x)
._ticks( nv.utils.calcTicksX(availableWidth/100, data) )
.tickSize( -availableHeight , 0);
g.select('.nv-x.nv-axis')
.attr('transform', 'translate(0,' + y.range()[0] + ')')
.call(xAxis);
}
if (showYAxis) {
yAxis
.scale(y)
._ticks( nv.utils.calcTicksY(availableHeight/36, data) )
.tickSize( -availableWidth, 0);
g.select('.nv-y.nv-axis')
.call(yAxis);
}
// Setup Distribution
if (showDistX) {
distX
.getData(scatter.x())
.scale(x)
.width(availableWidth)
.color(data.map(function(d,i) {
return d.color || color(d, i);
}).filter(function(d,i) { return !data[i].disabled }));
gEnter.select('.nv-distWrap').append('g')
.attr('class', 'nv-distributionX');
g.select('.nv-distributionX')
.attr('transform', 'translate(0,' + y.range()[0] + ')')
.datum(data.filter(function(d) { return !d.disabled }))
.call(distX);
}
if (showDistY) {
distY
.getData(scatter.y())
.scale(y)
.width(availableHeight)
.color(data.map(function(d,i) {
return d.color || color(d, i);
}).filter(function(d,i) { return !data[i].disabled }));
gEnter.select('.nv-distWrap').append('g')
.attr('class', 'nv-distributionY');
g.select('.nv-distributionY')
.attr('transform', 'translate(' + (rightAlignYAxis ? availableWidth : -distY.size() ) + ',0)')
.datum(data.filter(function(d) { return !d.disabled }))
.call(distY);
}
//============================================================
// Event Handling/Dispatching (in chart's scope)
//------------------------------------------------------------
legend.dispatch.on('stateChange', function(newState) {
for (var key in newState)
state[key] = newState[key];
dispatch.stateChange(state);
chart.update();
});
// Update chart from a state object passed to event handler
dispatch.on('changeState', function(e) {
if (typeof e.disabled !== 'undefined') {
data.forEach(function(series,i) {
series.disabled = e.disabled[i];
});
state.disabled = e.disabled;
}
chart.update();
});
// mouseover needs availableHeight so we just keep scatter mouse events inside the chart block
scatter.dispatch.on('elementMouseout.tooltip', function(evt) {
tooltip.hidden(true);
container.select('.nv-chart-' + scatter.id() + ' .nv-series-' + evt.seriesIndex + ' .nv-distx-' + evt.pointIndex)
.attr('y1', 0);
container.select('.nv-chart-' + scatter.id() + ' .nv-series-' + evt.seriesIndex + ' .nv-disty-' + evt.pointIndex)
.attr('x2', distY.size());
});
scatter.dispatch.on('elementMouseover.tooltip', function(evt) {
container.select('.nv-series-' + evt.seriesIndex + ' .nv-distx-' + evt.pointIndex)
.attr('y1', evt.relativePos[1] - availableHeight);
container.select('.nv-series-' + evt.seriesIndex + ' .nv-disty-' + evt.pointIndex)
.attr('x2', evt.relativePos[0] + distX.size());
tooltip.data(evt).hidden(false);
});
//store old scales for use in transitions on update
x0 = x.copy();
y0 = y.copy();
});
renderWatch.renderEnd('scatter with line immediate');
return chart;
}
//============================================================
// Expose Public Variables
//------------------------------------------------------------
// expose chart's sub-components
chart.dispatch = dispatch;
chart.scatter = scatter;
chart.legend = legend;
chart.xAxis = xAxis;
chart.yAxis = yAxis;
chart.distX = distX;
chart.distY = distY;
chart.tooltip = tooltip;
chart.options = nv.utils.optionsFunc.bind(chart);
chart._options = Object.create({}, {
// simple options, just get/set the necessary values
width: {get: function(){return width;}, set: function(_){width=_;}},
height: {get: function(){return height;}, set: function(_){height=_;}},
container: {get: function(){return container;}, set: function(_){container=_;}},
showDistX: {get: function(){return showDistX;}, set: function(_){showDistX=_;}},
showDistY: {get: function(){return showDistY;}, set: function(_){showDistY=_;}},
showLegend: {get: function(){return showLegend;}, set: function(_){showLegend=_;}},
showXAxis: {get: function(){return showXAxis;}, set: function(_){showXAxis=_;}},
showYAxis: {get: function(){return showYAxis;}, set: function(_){showYAxis=_;}},
defaultState: {get: function(){return defaultState;}, set: function(_){defaultState=_;}},
noData: {get: function(){return noData;}, set: function(_){noData=_;}},
duration: {get: function(){return duration;}, set: function(_){duration=_;}},
showLabels: {get: function(){return showLabels;}, set: function(_){showLabels=_;}},
// options that require extra logic in the setter
margin: {get: function(){return margin;}, set: function(_){
margin.top = _.top !== undefined ? _.top : margin.top;
margin.right = _.right !== undefined ? _.right : margin.right;
margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
margin.left = _.left !== undefined ? _.left : margin.left;
}},
rightAlignYAxis: {get: function(){return rightAlignYAxis;}, set: function(_){
rightAlignYAxis = _;
yAxis.orient( (_) ? 'right' : 'left');
}},
color: {get: function(){return color;}, set: function(_){
color = nv.utils.getColor(_);
legend.color(color);
distX.color(color);
distY.color(color);
}}
});
nv.utils.inheritOptions(chart, scatter);
nv.utils.initOptions(chart);
return chart;
};
nv.models.sparkline = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var margin = {top: 2, right: 0, bottom: 2, left: 0}
, width = 400
, height = 32
, container = null
, animate = true
, x = d3.scale.linear()
, y = d3.scale.linear()
, getX = function(d) { return d.x }
, getY = function(d) { return d.y }
, color = nv.utils.getColor(['#000'])
, xDomain
, yDomain
, xRange
, yRange
, showMinMaxPoints = true
, showCurrentPoint = true
, dispatch = d3.dispatch('renderEnd')
;
//============================================================
// Private Variables
//------------------------------------------------------------
var renderWatch = nv.utils.renderWatch(dispatch);
function chart(selection) {
renderWatch.reset();
selection.each(function(data) {
var availableWidth = width - margin.left - margin.right,
availableHeight = height - margin.top - margin.bottom;
container = d3.select(this);
nv.utils.initSVG(container);
// Setup Scales
x .domain(xDomain || d3.extent(data, getX ))
.range(xRange || [0, availableWidth]);
y .domain(yDomain || d3.extent(data, getY ))
.range(yRange || [availableHeight, 0]);
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-sparkline').data([data]);
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-sparkline');
var gEnter = wrapEnter.append('g');
var g = wrap.select('g');
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')
var paths = wrap.selectAll('path')
.data(function(d) { return [d] });
paths.enter().append('path');
paths.exit().remove();
paths
.style('stroke', function(d,i) { return d.color || color(d, i) })
.attr('d', d3.svg.line()
.x(function(d,i) { return x(getX(d,i)) })
.y(function(d,i) { return y(getY(d,i)) })
);
// TODO: Add CURRENT data point (Need Min, Mac, Current / Most recent)
var points = wrap.selectAll('circle.nv-point')
.data(function(data) {
var yValues = data.map(function(d, i) { return getY(d,i); });
function pointIndex(index) {
if (index != -1) {
var result = data[index];
result.pointIndex = index;
return result;
} else {
return null;
}
}
var maxPoint = pointIndex(yValues.lastIndexOf(y.domain()[1])),
minPoint = pointIndex(yValues.indexOf(y.domain()[0])),
currentPoint = pointIndex(yValues.length - 1);
return [(showMinMaxPoints ? minPoint : null), (showMinMaxPoints ? maxPoint : null), (showCurrentPoint ? currentPoint : null)].filter(function (d) {return d != null;});
});
points.enter().append('circle');
points.exit().remove();
points
.attr('cx', function(d,i) { return x(getX(d,d.pointIndex)) })
.attr('cy', function(d,i) { return y(getY(d,d.pointIndex)) })
.attr('r', 2)
.attr('class', function(d,i) {
return getX(d, d.pointIndex) == x.domain()[1] ? 'nv-point nv-currentValue' :
getY(d, d.pointIndex) == y.domain()[0] ? 'nv-point nv-minValue' : 'nv-point nv-maxValue'
});
});
renderWatch.renderEnd('sparkline immediate');
return chart;
}
//============================================================
// Expose Public Variables
//------------------------------------------------------------
chart.options = nv.utils.optionsFunc.bind(chart);
chart._options = Object.create({}, {
// simple options, just get/set the necessary values
width: {get: function(){return width;}, set: function(_){width=_;}},
height: {get: function(){return height;}, set: function(_){height=_;}},
xDomain: {get: function(){return xDomain;}, set: function(_){xDomain=_;}},
yDomain: {get: function(){return yDomain;}, set: function(_){yDomain=_;}},
xRange: {get: function(){return xRange;}, set: function(_){xRange=_;}},
yRange: {get: function(){return yRange;}, set: function(_){yRange=_;}},
xScale: {get: function(){return x;}, set: function(_){x=_;}},
yScale: {get: function(){return y;}, set: function(_){y=_;}},
animate: {get: function(){return animate;}, set: function(_){animate=_;}},
showMinMaxPoints: {get: function(){return showMinMaxPoints;}, set: function(_){showMinMaxPoints=_;}},
showCurrentPoint: {get: function(){return showCurrentPoint;}, set: function(_){showCurrentPoint=_;}},
//functor options
x: {get: function(){return getX;}, set: function(_){getX=d3.functor(_);}},
y: {get: function(){return getY;}, set: function(_){getY=d3.functor(_);}},
// options that require extra logic in the setter
margin: {get: function(){return margin;}, set: function(_){
margin.top = _.top !== undefined ? _.top : margin.top;
margin.right = _.right !== undefined ? _.right : margin.right;
margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
margin.left = _.left !== undefined ? _.left : margin.left;
}},
color: {get: function(){return color;}, set: function(_){
color = nv.utils.getColor(_);
}}
});
chart.dispatch = dispatch;
nv.utils.initOptions(chart);
return chart;
};
nv.models.sparklinePlus = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var sparkline = nv.models.sparkline();
var margin = {top: 15, right: 100, bottom: 10, left: 50}
, width = null
, height = null
, x
, y
, index = []
, paused = false
, xTickFormat = d3.format(',r')
, yTickFormat = d3.format(',.2f')
, showLastValue = true
, alignValue = true
, rightAlignValue = false
, noData = null
, dispatch = d3.dispatch('renderEnd')
;
//============================================================
// Private Variables
//------------------------------------------------------------
var renderWatch = nv.utils.renderWatch(dispatch);
function chart(selection) {
renderWatch.reset();
renderWatch.models(sparkline);
selection.each(function(data) {
var container = d3.select(this);
nv.utils.initSVG(container);
var availableWidth = nv.utils.availableWidth(width, container, margin),
availableHeight = nv.utils.availableHeight(height, container, margin);
chart.update = function() { container.call(chart); };
chart.container = this;
// Display No Data message if there's nothing to show.
if (!data || !data.length) {
nv.utils.noData(chart, container)
return chart;
} else {
container.selectAll('.nv-noData').remove();
}
var currentValue = sparkline.y()(data[data.length-1], data.length-1);
// Setup Scales
x = sparkline.xScale();
y = sparkline.yScale();
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-sparklineplus').data([data]);
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-sparklineplus');
var gEnter = wrapEnter.append('g');
var g = wrap.select('g');
gEnter.append('g').attr('class', 'nv-sparklineWrap');
gEnter.append('g').attr('class', 'nv-valueWrap');
gEnter.append('g').attr('class', 'nv-hoverArea');
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
// Main Chart Component(s)
var sparklineWrap = g.select('.nv-sparklineWrap');
sparkline.width(availableWidth).height(availableHeight);
sparklineWrap.call(sparkline);
if (showLastValue) {
var valueWrap = g.select('.nv-valueWrap');
var value = valueWrap.selectAll('.nv-currentValue')
.data([currentValue]);
value.enter().append('text').attr('class', 'nv-currentValue')
.attr('dx', rightAlignValue ? -8 : 8)
.attr('dy', '.9em')
.style('text-anchor', rightAlignValue ? 'end' : 'start');
value
.attr('x', availableWidth + (rightAlignValue ? margin.right : 0))
.attr('y', alignValue ? function (d) {
return y(d)
} : 0)
.style('fill', sparkline.color()(data[data.length - 1], data.length - 1))
.text(yTickFormat(currentValue));
}
gEnter.select('.nv-hoverArea').append('rect')
.on('mousemove', sparklineHover)
.on('click', function() { paused = !paused })
.on('mouseout', function() { index = []; updateValueLine(); });
g.select('.nv-hoverArea rect')
.attr('transform', function(d) { return 'translate(' + -margin.left + ',' + -margin.top + ')' })
.attr('width', availableWidth + margin.left + margin.right)
.attr('height', availableHeight + margin.top);
//index is currently global (within the chart), may or may not keep it that way
function updateValueLine() {
if (paused) return;
var hoverValue = g.selectAll('.nv-hoverValue').data(index);
var hoverEnter = hoverValue.enter()
.append('g').attr('class', 'nv-hoverValue')
.style('stroke-opacity', 0)
.style('fill-opacity', 0);
hoverValue.exit()
.transition().duration(250)
.style('stroke-opacity', 0)
.style('fill-opacity', 0)
.remove();
hoverValue
.attr('transform', function(d) { return 'translate(' + x(sparkline.x()(data[d],d)) + ',0)' })
.transition().duration(250)
.style('stroke-opacity', 1)
.style('fill-opacity', 1);
if (!index.length) return;
hoverEnter.append('line')
.attr('x1', 0)
.attr('y1', -margin.top)
.attr('x2', 0)
.attr('y2', availableHeight);
hoverEnter.append('text').attr('class', 'nv-xValue')
.attr('x', -6)
.attr('y', -margin.top)
.attr('text-anchor', 'end')
.attr('dy', '.9em');
g.select('.nv-hoverValue .nv-xValue')
.text(xTickFormat(sparkline.x()(data[index[0]], index[0])));
hoverEnter.append('text').attr('class', 'nv-yValue')
.attr('x', 6)
.attr('y', -margin.top)
.attr('text-anchor', 'start')
.attr('dy', '.9em');
g.select('.nv-hoverValue .nv-yValue')
.text(yTickFormat(sparkline.y()(data[index[0]], index[0])));
}
function sparklineHover() {
if (paused) return;
var pos = d3.mouse(this)[0] - margin.left;
function getClosestIndex(data, x) {
var distance = Math.abs(sparkline.x()(data[0], 0) - x);
var closestIndex = 0;
for (var i = 0; i < data.length; i++){
if (Math.abs(sparkline.x()(data[i], i) - x) < distance) {
distance = Math.abs(sparkline.x()(data[i], i) - x);
closestIndex = i;
}
}
return closestIndex;
}
index = [getClosestIndex(data, Math.round(x.invert(pos)))];
updateValueLine();
}
});
renderWatch.renderEnd('sparklinePlus immediate');
return chart;
}
//============================================================
// Expose Public Variables
//------------------------------------------------------------
// expose chart's sub-components
chart.dispatch = dispatch;
chart.sparkline = sparkline;
chart.options = nv.utils.optionsFunc.bind(chart);
chart._options = Object.create({}, {
// simple options, just get/set the necessary values
width: {get: function(){return width;}, set: function(_){width=_;}},
height: {get: function(){return height;}, set: function(_){height=_;}},
xTickFormat: {get: function(){return xTickFormat;}, set: function(_){xTickFormat=_;}},
yTickFormat: {get: function(){return yTickFormat;}, set: function(_){yTickFormat=_;}},
showLastValue: {get: function(){return showLastValue;}, set: function(_){showLastValue=_;}},
alignValue: {get: function(){return alignValue;}, set: function(_){alignValue=_;}},
rightAlignValue: {get: function(){return rightAlignValue;}, set: function(_){rightAlignValue=_;}},
noData: {get: function(){return noData;}, set: function(_){noData=_;}},
// options that require extra logic in the setter
margin: {get: function(){return margin;}, set: function(_){
margin.top = _.top !== undefined ? _.top : margin.top;
margin.right = _.right !== undefined ? _.right : margin.right;
margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
margin.left = _.left !== undefined ? _.left : margin.left;
}}
});
nv.utils.inheritOptions(chart, sparkline);
nv.utils.initOptions(chart);
return chart;
};
nv.models.stackedArea = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var margin = {top: 0, right: 0, bottom: 0, left: 0}
, width = 960
, height = 500
, color = nv.utils.defaultColor() // a function that computes the color
, id = Math.floor(Math.random() * 100000) //Create semi-unique ID incase user doesn't selet one
, container = null
, getX = function(d) { return d.x } // accessor to get the x value from a data point
, getY = function(d) { return d.y } // accessor to get the y value from a data point
, defined = function(d,i) { return !isNaN(getY(d,i)) && getY(d,i) !== null } // allows a line to be not continuous when it is not defined
, style = 'stack'
, offset = 'zero'
, order = 'default'
, interpolate = 'linear' // controls the line interpolation
, clipEdge = false // if true, masks lines within x and y scale
, x //can be accessed via chart.xScale()
, y //can be accessed via chart.yScale()
, scatter = nv.models.scatter()
, duration = 250
, dispatch = d3.dispatch('areaClick', 'areaMouseover', 'areaMouseout','renderEnd', 'elementClick', 'elementMouseover', 'elementMouseout')
;
scatter
.pointSize(2.2) // default size
.pointDomain([2.2, 2.2]) // all the same size by default
;
/************************************
* offset:
* 'wiggle' (stream)
* 'zero' (stacked)
* 'expand' (normalize to 100%)
* 'silhouette' (simple centered)
*
* order:
* 'inside-out' (stream)
* 'default' (input order)
************************************/
var renderWatch = nv.utils.renderWatch(dispatch, duration);
function chart(selection) {
renderWatch.reset();
renderWatch.models(scatter);
selection.each(function(data) {
var availableWidth = width - margin.left - margin.right,
availableHeight = height - margin.top - margin.bottom;
container = d3.select(this);
nv.utils.initSVG(container);
// Setup Scales
x = scatter.xScale();
y = scatter.yScale();
var dataRaw = data;
// Injecting point index into each point because d3.layout.stack().out does not give index
data.forEach(function(aseries, i) {
aseries.seriesIndex = i;
aseries.values = aseries.values.map(function(d, j) {
d.index = j;
d.seriesIndex = i;
return d;
});
});
var dataFiltered = data.filter(function(series) {
return !series.disabled;
});
data = d3.layout.stack()
.order(order)
.offset(offset)
.values(function(d) { return d.values }) //TODO: make values customizeable in EVERY model in this fashion
.x(getX)
.y(getY)
.out(function(d, y0, y) {
d.display = {
y: y,
y0: y0
};
})
(dataFiltered);
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-stackedarea').data([data]);
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-stackedarea');
var defsEnter = wrapEnter.append('defs');
var gEnter = wrapEnter.append('g');
var g = wrap.select('g');
gEnter.append('g').attr('class', 'nv-areaWrap');
gEnter.append('g').attr('class', 'nv-scatterWrap');
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
// If the user has not specified forceY, make sure 0 is included in the domain
// Otherwise, use user-specified values for forceY
if (scatter.forceY().length == 0) {
scatter.forceY().push(0);
}
scatter
.width(availableWidth)
.height(availableHeight)
.x(getX)
.y(function(d) {
if (d.display !== undefined) { return d.display.y + d.display.y0; }
})
.color(data.map(function(d,i) {
d.color = d.color || color(d, d.seriesIndex);
return d.color;
}));
var scatterWrap = g.select('.nv-scatterWrap')
.datum(data);
scatterWrap.call(scatter);
defsEnter.append('clipPath')
.attr('id', 'nv-edge-clip-' + id)
.append('rect');
wrap.select('#nv-edge-clip-' + id + ' rect')
.attr('width', availableWidth)
.attr('height', availableHeight);
g.attr('clip-path', clipEdge ? 'url(#nv-edge-clip-' + id + ')' : '');
var area = d3.svg.area()
.defined(defined)
.x(function(d,i) { return x(getX(d,i)) })
.y0(function(d) {
return y(d.display.y0)
})
.y1(function(d) {
return y(d.display.y + d.display.y0)
})
.interpolate(interpolate);
var zeroArea = d3.svg.area()
.defined(defined)
.x(function(d,i) { return x(getX(d,i)) })
.y0(function(d) { return y(d.display.y0) })
.y1(function(d) { return y(d.display.y0) });
var path = g.select('.nv-areaWrap').selectAll('path.nv-area')
.data(function(d) { return d });
path.enter().append('path').attr('class', function(d,i) { return 'nv-area nv-area-' + i })
.attr('d', function(d,i){
return zeroArea(d.values, d.seriesIndex);
})
.on('mouseover', function(d,i) {
d3.select(this).classed('hover', true);
dispatch.areaMouseover({
point: d,
series: d.key,
pos: [d3.event.pageX, d3.event.pageY],
seriesIndex: d.seriesIndex
});
})
.on('mouseout', function(d,i) {
d3.select(this).classed('hover', false);
dispatch.areaMouseout({
point: d,
series: d.key,
pos: [d3.event.pageX, d3.event.pageY],
seriesIndex: d.seriesIndex
});
})
.on('click', function(d,i) {
d3.select(this).classed('hover', false);
dispatch.areaClick({
point: d,
series: d.key,
pos: [d3.event.pageX, d3.event.pageY],
seriesIndex: d.seriesIndex
});
});
path.exit().remove();
path.style('fill', function(d,i){
return d.color || color(d, d.seriesIndex)
})
.style('stroke', function(d,i){ return d.color || color(d, d.seriesIndex) });
path.watchTransition(renderWatch,'stackedArea path')
.attr('d', function(d,i) {
return area(d.values,i)
});
//============================================================
// Event Handling/Dispatching (in chart's scope)
//------------------------------------------------------------
scatter.dispatch.on('elementMouseover.area', function(e) {
g.select('.nv-chart-' + id + ' .nv-area-' + e.seriesIndex).classed('hover', true);
});
scatter.dispatch.on('elementMouseout.area', function(e) {
g.select('.nv-chart-' + id + ' .nv-area-' + e.seriesIndex).classed('hover', false);
});
//Special offset functions
chart.d3_stackedOffset_stackPercent = function(stackData) {
var n = stackData.length, //How many series
m = stackData[0].length, //how many points per series
i,
j,
o,
y0 = [];
for (j = 0; j < m; ++j) { //Looping through all points
for (i = 0, o = 0; i < dataRaw.length; i++) { //looping through all series
o += getY(dataRaw[i].values[j]); //total y value of all series at a certian point in time.
}
if (o) for (i = 0; i < n; i++) { //(total y value of all series at point in time i) != 0
stackData[i][j][1] /= o;
} else { //(total y value of all series at point in time i) == 0
for (i = 0; i < n; i++) {
stackData[i][j][1] = 0;
}
}
}
for (j = 0; j < m; ++j) y0[j] = 0;
return y0;
};
});
renderWatch.renderEnd('stackedArea immediate');
return chart;
}
//============================================================
// Global getters and setters
//------------------------------------------------------------
chart.dispatch = dispatch;
chart.scatter = scatter;
scatter.dispatch.on('elementClick', function(){ dispatch.elementClick.apply(this, arguments); });
scatter.dispatch.on('elementMouseover', function(){ dispatch.elementMouseover.apply(this, arguments); });
scatter.dispatch.on('elementMouseout', function(){ dispatch.elementMouseout.apply(this, arguments); });
chart.interpolate = function(_) {
if (!arguments.length) return interpolate;
interpolate = _;
return chart;
};
chart.duration = function(_) {
if (!arguments.length) return duration;
duration = _;
renderWatch.reset(duration);
scatter.duration(duration);
return chart;
};
chart.dispatch = dispatch;
chart.scatter = scatter;
chart.options = nv.utils.optionsFunc.bind(chart);
chart._options = Object.create({}, {
// simple options, just get/set the necessary values
width: {get: function(){return width;}, set: function(_){width=_;}},
height: {get: function(){return height;}, set: function(_){height=_;}},
defined: {get: function(){return defined;}, set: function(_){defined=_;}},
clipEdge: {get: function(){return clipEdge;}, set: function(_){clipEdge=_;}},
offset: {get: function(){return offset;}, set: function(_){offset=_;}},
order: {get: function(){return order;}, set: function(_){order=_;}},
interpolate: {get: function(){return interpolate;}, set: function(_){interpolate=_;}},
// simple functor options
x: {get: function(){return getX;}, set: function(_){getX = d3.functor(_);}},
y: {get: function(){return getY;}, set: function(_){getY = d3.functor(_);}},
// options that require extra logic in the setter
margin: {get: function(){return margin;}, set: function(_){
margin.top = _.top !== undefined ? _.top : margin.top;
margin.right = _.right !== undefined ? _.right : margin.right;
margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
margin.left = _.left !== undefined ? _.left : margin.left;
}},
color: {get: function(){return color;}, set: function(_){
color = nv.utils.getColor(_);
}},
style: {get: function(){return style;}, set: function(_){
style = _;
switch (style) {
case 'stack':
chart.offset('zero');
chart.order('default');
break;
case 'stream':
chart.offset('wiggle');
chart.order('inside-out');
break;
case 'stream-center':
chart.offset('silhouette');
chart.order('inside-out');
break;
case 'expand':
chart.offset('expand');
chart.order('default');
break;
case 'stack_percent':
chart.offset(chart.d3_stackedOffset_stackPercent);
chart.order('default');
break;
}
}},
duration: {get: function(){return duration;}, set: function(_){
duration = _;
renderWatch.reset(duration);
scatter.duration(duration);
}}
});
nv.utils.inheritOptions(chart, scatter);
nv.utils.initOptions(chart);
return chart;
};
nv.models.stackedAreaChart = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var stacked = nv.models.stackedArea()
, xAxis = nv.models.axis()
, yAxis = nv.models.axis()
, legend = nv.models.legend()
, controls = nv.models.legend()
, interactiveLayer = nv.interactiveGuideline()
, tooltip = nv.models.tooltip()
, focus = nv.models.focus(nv.models.stackedArea())
;
var margin = {top: 30, right: 25, bottom: 25, left: 60}
, width = null
, height = null
, color = nv.utils.defaultColor()
, showControls = true
, showLegend = true
, showXAxis = true
, showYAxis = true
, rightAlignYAxis = false
, focusEnable = false
, useInteractiveGuideline = false
, showTotalInTooltip = true
, totalLabel = 'TOTAL'
, x //can be accessed via chart.xScale()
, y //can be accessed via chart.yScale()
, state = nv.utils.state()
, defaultState = null
, noData = null
, dispatch = d3.dispatch('stateChange', 'changeState','renderEnd')
, controlWidth = 250
, controlOptions = ['Stacked','Expanded']
, controlLabels = {}
, duration = 250
;
state.style = stacked.style();
xAxis.orient('bottom').tickPadding(7);
yAxis.orient((rightAlignYAxis) ? 'right' : 'left');
tooltip
.headerFormatter(function(d, i) {
return xAxis.tickFormat()(d, i);
})
.valueFormatter(function(d, i) {
return yAxis.tickFormat()(d, i);
});
interactiveLayer.tooltip
.headerFormatter(function(d, i) {
return xAxis.tickFormat()(d, i);
})
.valueFormatter(function(d, i) {
return d == null ? "N/A" : yAxis.tickFormat()(d, i);
});
var oldYTickFormat = null,
oldValueFormatter = null;
controls.updateState(false);
//============================================================
// Private Variables
//------------------------------------------------------------
var renderWatch = nv.utils.renderWatch(dispatch);
var style = stacked.style();
var stateGetter = function(data) {
return function(){
return {
active: data.map(function(d) { return !d.disabled }),
style: stacked.style()
};
}
};
var stateSetter = function(data) {
return function(state) {
if (state.style !== undefined)
style = state.style;
if (state.active !== undefined)
data.forEach(function(series,i) {
series.disabled = !state.active[i];
});
}
};
var percentFormatter = d3.format('%');
function chart(selection) {
renderWatch.reset();
renderWatch.models(stacked);
if (showXAxis) renderWatch.models(xAxis);
if (showYAxis) renderWatch.models(yAxis);
selection.each(function(data) {
var container = d3.select(this),
that = this;
nv.utils.initSVG(container);
var availableWidth = nv.utils.availableWidth(width, container, margin),
availableHeight = nv.utils.availableHeight(height, container, margin) - (focusEnable ? focus.height() : 0);
chart.update = function() { container.transition().duration(duration).call(chart); };
chart.container = this;
state
.setter(stateSetter(data), chart.update)
.getter(stateGetter(data))
.update();
// DEPRECATED set state.disabled
state.disabled = data.map(function(d) { return !!d.disabled });
if (!defaultState) {
var key;
defaultState = {};
for (key in state) {
if (state[key] instanceof Array)
defaultState[key] = state[key].slice(0);
else
defaultState[key] = state[key];
}
}
// Display No Data message if there's nothing to show.
if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) {
nv.utils.noData(chart, container)
return chart;
} else {
container.selectAll('.nv-noData').remove();
}
// Setup Scales
x = stacked.xScale();
y = stacked.yScale();
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-stackedAreaChart').data([data]);
var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-stackedAreaChart').append('g');
var g = wrap.select('g');
gEnter.append('g').attr('class', 'nv-legendWrap');
gEnter.append('g').attr('class', 'nv-controlsWrap');
var focusEnter = gEnter.append('g').attr('class', 'nv-focus');
focusEnter.append('g').attr('class', 'nv-background').append('rect');
focusEnter.append('g').attr('class', 'nv-x nv-axis');
focusEnter.append('g').attr('class', 'nv-y nv-axis');
focusEnter.append('g').attr('class', 'nv-stackedWrap');
focusEnter.append('g').attr('class', 'nv-interactive');
// g.select("rect").attr("width",availableWidth).attr("height",availableHeight);
var contextEnter = gEnter.append('g').attr('class', 'nv-focusWrap');
// Legend
if (!showLegend) {
g.select('.nv-legendWrap').selectAll('*').remove();
} else {
var legendWidth = (showControls) ? availableWidth - controlWidth : availableWidth;
legend.width(legendWidth);
g.select('.nv-legendWrap').datum(data).call(legend);
if ( margin.top != legend.height()) {
margin.top = legend.height();
availableHeight = nv.utils.availableHeight(height, container, margin) - (focusEnable ? focus.height() : 0);
}
g.select('.nv-legendWrap')
.attr('transform', 'translate(' + (availableWidth-legendWidth) + ',' + (-margin.top) +')');
}
// Controls
if (!showControls) {
g.select('.nv-controlsWrap').selectAll('*').remove();
} else {
var controlsData = [
{
key: controlLabels.stacked || 'Stacked',
metaKey: 'Stacked',
disabled: stacked.style() != 'stack',
style: 'stack'
},
{
key: controlLabels.stream || 'Stream',
metaKey: 'Stream',
disabled: stacked.style() != 'stream',
style: 'stream'
},
{
key: controlLabels.expanded || 'Expanded',
metaKey: 'Expanded',
disabled: stacked.style() != 'expand',
style: 'expand'
},
{
key: controlLabels.stack_percent || 'Stack %',
metaKey: 'Stack_Percent',
disabled: stacked.style() != 'stack_percent',
style: 'stack_percent'
}
];
controlWidth = (controlOptions.length/3) * 260;
controlsData = controlsData.filter(function(d) {
return controlOptions.indexOf(d.metaKey) !== -1;
});
controls
.width( controlWidth )
.color(['#444', '#444', '#444']);
g.select('.nv-controlsWrap')
.datum(controlsData)
.call(controls);
if ( margin.top != Math.max(controls.height(), legend.height()) ) {
margin.top = Math.max(controls.height(), legend.height());
availableHeight = nv.utils.availableHeight(height, container, margin);
}
g.select('.nv-controlsWrap')
.attr('transform', 'translate(0,' + (-margin.top) +')');
}
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
if (rightAlignYAxis) {
g.select(".nv-y.nv-axis")
.attr("transform", "translate(" + availableWidth + ",0)");
}
//Set up interactive layer
if (useInteractiveGuideline) {
interactiveLayer
.width(availableWidth)
.height(availableHeight)
.margin({left: margin.left, top: margin.top})
.svgContainer(container)
.xScale(x);
wrap.select(".nv-interactive").call(interactiveLayer);
}
g.select('.nv-focus .nv-background rect')
.attr('width', availableWidth)
.attr('height', availableHeight);
stacked
.width(availableWidth)
.height(availableHeight)
.color(data.map(function(d,i) {
return d.color || color(d, i);
}).filter(function(d,i) { return !data[i].disabled; }));
var stackedWrap = g.select('.nv-focus .nv-stackedWrap')
.datum(data.filter(function(d) { return !d.disabled; }));
// Setup Axes
if (showXAxis) {
xAxis.scale(x)
._ticks( nv.utils.calcTicksX(availableWidth/100, data) )
.tickSize( -availableHeight, 0);
}
if (showYAxis) {
var ticks;
if (stacked.offset() === 'wiggle') {
ticks = 0;
}
else {
ticks = nv.utils.calcTicksY(availableHeight/36, data);
}
yAxis.scale(y)
._ticks(ticks)
.tickSize(-availableWidth, 0);
}
//============================================================
// Update Axes
//============================================================
function updateXAxis() {
if(showXAxis) {
g.select('.nv-focus .nv-x.nv-axis')
.attr('transform', 'translate(0,' + availableHeight + ')')
.transition()
.duration(duration)
.call(xAxis)
;
}
}
function updateYAxis() {
if(showYAxis) {
if (stacked.style() === 'expand' || stacked.style() === 'stack_percent') {
var currentFormat = yAxis.tickFormat();
if ( !oldYTickFormat || currentFormat !== percentFormatter )
oldYTickFormat = currentFormat;
//Forces the yAxis to use percentage in 'expand' mode.
yAxis.tickFormat(percentFormatter);
}
else {
if (oldYTickFormat) {
yAxis.tickFormat(oldYTickFormat);
oldYTickFormat = null;
}
}
g.select('.nv-focus .nv-y.nv-axis')
.transition().duration(0)
.call(yAxis);
}
}
//============================================================
// Update Focus
//============================================================
if(!focusEnable) {
stackedWrap.transition().call(stacked);
updateXAxis();
updateYAxis();
} else {
focus.width(availableWidth);
g.select('.nv-focusWrap')
.attr('transform', 'translate(0,' + ( availableHeight + margin.bottom + focus.margin().top) + ')')
.datum(data.filter(function(d) { return !d.disabled; }))
.call(focus);
var extent = focus.brush.empty() ? focus.xDomain() : focus.brush.extent();
if(extent !== null){
onBrush(extent);
}
}
//============================================================
// Event Handling/Dispatching (in chart's scope)
//------------------------------------------------------------
stacked.dispatch.on('areaClick.toggle', function(e) {
if (data.filter(function(d) { return !d.disabled }).length === 1)
data.forEach(function(d) {
d.disabled = false;
});
else
data.forEach(function(d,i) {
d.disabled = (i != e.seriesIndex);
});
state.disabled = data.map(function(d) { return !!d.disabled });
dispatch.stateChange(state);
chart.update();
});
legend.dispatch.on('stateChange', function(newState) {
for (var key in newState)
state[key] = newState[key];
dispatch.stateChange(state);
chart.update();
});
controls.dispatch.on('legendClick', function(d,i) {
if (!d.disabled) return;
controlsData = controlsData.map(function(s) {
s.disabled = true;
return s;
});
d.disabled = false;
stacked.style(d.style);
state.style = stacked.style();
dispatch.stateChange(state);
chart.update();
});
interactiveLayer.dispatch.on('elementMousemove', function(e) {
stacked.clearHighlights();
var singlePoint, pointIndex, pointXLocation, allData = [], valueSum = 0, allNullValues = true;
data
.filter(function(series, i) {
series.seriesIndex = i;
return !series.disabled;
})
.forEach(function(series,i) {
pointIndex = nv.interactiveBisect(series.values, e.pointXValue, chart.x());
var point = series.values[pointIndex];
var pointYValue = chart.y()(point, pointIndex);
if (pointYValue != null) {
stacked.highlightPoint(i, pointIndex, true);
}
if (typeof point === 'undefined') return;
if (typeof singlePoint === 'undefined') singlePoint = point;
if (typeof pointXLocation === 'undefined') pointXLocation = chart.xScale()(chart.x()(point,pointIndex));
//If we are in 'expand' mode, use the stacked percent value instead of raw value.
var tooltipValue = (stacked.style() == 'expand') ? point.display.y : chart.y()(point,pointIndex);
allData.push({
key: series.key,
value: tooltipValue,
color: color(series,series.seriesIndex),
point: point
});
if (showTotalInTooltip && stacked.style() != 'expand' && tooltipValue != null) {
valueSum += tooltipValue;
allNullValues = false;
};
});
allData.reverse();
//Highlight the tooltip entry based on which stack the mouse is closest to.
if (allData.length > 2) {
var yValue = chart.yScale().invert(e.mouseY);
var yDistMax = Infinity, indexToHighlight = null;
allData.forEach(function(series,i) {
//To handle situation where the stacked area chart is negative, we need to use absolute values
//when checking if the mouse Y value is within the stack area.
yValue = Math.abs(yValue);
var stackedY0 = Math.abs(series.point.display.y0);
var stackedY = Math.abs(series.point.display.y);
if ( yValue >= stackedY0 && yValue <= (stackedY + stackedY0))
{
indexToHighlight = i;
return;
}
});
if (indexToHighlight != null)
allData[indexToHighlight].highlight = true;
}
//If we are not in 'expand' mode, add a 'Total' row to the tooltip.
if (showTotalInTooltip && stacked.style() != 'expand' && allData.length >= 2 && !allNullValues) {
allData.push({
key: totalLabel,
value: valueSum,
total: true
});
}
var xValue = chart.x()(singlePoint,pointIndex);
var valueFormatter = interactiveLayer.tooltip.valueFormatter();
// Keeps track of the tooltip valueFormatter if the chart changes to expanded view
if (stacked.style() === 'expand' || stacked.style() === 'stack_percent') {
if ( !oldValueFormatter ) {
oldValueFormatter = valueFormatter;
}
//Forces the tooltip to use percentage in 'expand' mode.
valueFormatter = d3.format(".1%");
}
else {
if (oldValueFormatter) {
valueFormatter = oldValueFormatter;
oldValueFormatter = null;
}
}
interactiveLayer.tooltip
.chartContainer(that.parentNode)
.valueFormatter(valueFormatter)
.data(
{
value: xValue,
series: allData
}
)();
interactiveLayer.renderGuideLine(pointXLocation);
});
interactiveLayer.dispatch.on("elementMouseout",function(e) {
stacked.clearHighlights();
});
/* Update `main' graph on brush update. */
focus.dispatch.on("onBrush", function(extent) {
onBrush(extent);
});
// Update chart from a state object passed to event handler
dispatch.on('changeState', function(e) {
if (typeof e.disabled !== 'undefined' && data.length === e.disabled.length) {
data.forEach(function(series,i) {
series.disabled = e.disabled[i];
});
state.disabled = e.disabled;
}
if (typeof e.style !== 'undefined') {
stacked.style(e.style);
style = e.style;
}
chart.update();
});
//============================================================
// Functions
//------------------------------------------------------------
function onBrush(extent) {
// Update Main (Focus)
var stackedWrap = g.select('.nv-focus .nv-stackedWrap')
.datum(
data.filter(function(d) { return !d.disabled; })
.map(function(d,i) {
return {
key: d.key,
area: d.area,
classed: d.classed,
values: d.values.filter(function(d,i) {
return stacked.x()(d,i) >= extent[0] && stacked.x()(d,i) <= extent[1];
}),
disableTooltip: d.disableTooltip
};
})
);
stackedWrap.transition().duration(duration).call(stacked);
// Update Main (Focus) Axes
updateXAxis();
updateYAxis();
}
});
renderWatch.renderEnd('stacked Area chart immediate');
return chart;
}
//============================================================
// Event Handling/Dispatching (out of chart's scope)
//------------------------------------------------------------
stacked.dispatch.on('elementMouseover.tooltip', function(evt) {
evt.point['x'] = stacked.x()(evt.point);
evt.point['y'] = stacked.y()(evt.point);
tooltip.data(evt).hidden(false);
});
stacked.dispatch.on('elementMouseout.tooltip', function(evt) {
tooltip.hidden(true)
});
//============================================================
// Expose Public Variables
//------------------------------------------------------------
// expose chart's sub-components
chart.dispatch = dispatch;
chart.stacked = stacked;
chart.legend = legend;
chart.controls = controls;
chart.xAxis = xAxis;
chart.x2Axis = focus.xAxis;
chart.yAxis = yAxis;
chart.y2Axis = focus.yAxis;
chart.interactiveLayer = interactiveLayer;
chart.tooltip = tooltip;
chart.focus = focus;
chart.dispatch = dispatch;
chart.options = nv.utils.optionsFunc.bind(chart);
chart._options = Object.create({}, {
// simple options, just get/set the necessary values
width: {get: function(){return width;}, set: function(_){width=_;}},
height: {get: function(){return height;}, set: function(_){height=_;}},
showLegend: {get: function(){return showLegend;}, set: function(_){showLegend=_;}},
showXAxis: {get: function(){return showXAxis;}, set: function(_){showXAxis=_;}},
showYAxis: {get: function(){return showYAxis;}, set: function(_){showYAxis=_;}},
defaultState: {get: function(){return defaultState;}, set: function(_){defaultState=_;}},
noData: {get: function(){return noData;}, set: function(_){noData=_;}},
showControls: {get: function(){return showControls;}, set: function(_){showControls=_;}},
controlLabels: {get: function(){return controlLabels;}, set: function(_){controlLabels=_;}},
controlOptions: {get: function(){return controlOptions;}, set: function(_){controlOptions=_;}},
showTotalInTooltip: {get: function(){return showTotalInTooltip;}, set: function(_){showTotalInTooltip=_;}},
totalLabel: {get: function(){return totalLabel;}, set: function(_){totalLabel=_;}},
focusEnable: {get: function(){return focusEnable;}, set: function(_){focusEnable=_;}},
focusHeight: {get: function(){return focus.height();}, set: function(_){focus.height(_);}},
brushExtent: {get: function(){return focus.brushExtent();}, set: function(_){focus.brushExtent(_);}},
// options that require extra logic in the setter
margin: {get: function(){return margin;}, set: function(_){
margin.top = _.top !== undefined ? _.top : margin.top;
margin.right = _.right !== undefined ? _.right : margin.right;
margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
margin.left = _.left !== undefined ? _.left : margin.left;
}},
focusMargin: {get: function(){return focus.margin}, set: function(_){
focus.margin.top = _.top !== undefined ? _.top : focus.margin.top;
focus.margin.right = _.right !== undefined ? _.right : focus.margin.right;
focus.margin.bottom = _.bottom !== undefined ? _.bottom : focus.margin.bottom;
focus.margin.left = _.left !== undefined ? _.left : focus.margin.left;
}},
duration: {get: function(){return duration;}, set: function(_){
duration = _;
renderWatch.reset(duration);
stacked.duration(duration);
xAxis.duration(duration);
yAxis.duration(duration);
}},
color: {get: function(){return color;}, set: function(_){
color = nv.utils.getColor(_);
legend.color(color);
stacked.color(color);
focus.color(color);
}},
x: {get: function(){return stacked.x();}, set: function(_){
stacked.x(_);
focus.x(_);
}},
y: {get: function(){return stacked.y();}, set: function(_){
stacked.y(_);
focus.y(_);
}},
rightAlignYAxis: {get: function(){return rightAlignYAxis;}, set: function(_){
rightAlignYAxis = _;
yAxis.orient( rightAlignYAxis ? 'right' : 'left');
}},
useInteractiveGuideline: {get: function(){return useInteractiveGuideline;}, set: function(_){
useInteractiveGuideline = !!_;
chart.interactive(!_);
chart.useVoronoi(!_);
stacked.scatter.interactive(!_);
}}
});
nv.utils.inheritOptions(chart, stacked);
nv.utils.initOptions(chart);
return chart;
};
nv.models.stackedAreaWithFocusChart = function() {
return nv.models.stackedAreaChart()
.margin({ bottom: 30 })
.focusEnable( true );
};// based on http://bl.ocks.org/kerryrodden/477c1bfb081b783f80ad
nv.models.sunburst = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var margin = {top: 0, right: 0, bottom: 0, left: 0}
, width = 600
, height = 600
, mode = "count"
, modes = {count: function(d) { return 1; }, value: function(d) { return d.value || d.size }, size: function(d) { return d.value || d.size }}
, id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one
, container = null
, color = nv.utils.defaultColor()
, showLabels = false
, labelFormat = function(d){if(mode === 'count'){return d.name + ' #' + d.value}else{return d.name + ' ' + (d.value || d.size)}}
, labelThreshold = 0.02
, sort = function(d1, d2){return d1.name > d2.name;}
, key = function(d,i){return d.name;}
, groupColorByParent = true
, duration = 500
, dispatch = d3.dispatch('chartClick', 'elementClick', 'elementDblClick', 'elementMousemove', 'elementMouseover', 'elementMouseout', 'renderEnd');
//============================================================
// aux functions and setup
//------------------------------------------------------------
var x = d3.scale.linear().range([0, 2 * Math.PI]);
var y = d3.scale.sqrt();
var partition = d3.layout.partition().sort(sort);
var node, availableWidth, availableHeight, radius;
var prevPositions = {};
var arc = d3.svg.arc()
.startAngle(function(d) {return Math.max(0, Math.min(2 * Math.PI, x(d.x))) })
.endAngle(function(d) {return Math.max(0, Math.min(2 * Math.PI, x(d.x + d.dx))) })
.innerRadius(function(d) {return Math.max(0, y(d.y)) })
.outerRadius(function(d) {return Math.max(0, y(d.y + d.dy)) });
function rotationToAvoidUpsideDown(d) {
var centerAngle = computeCenterAngle(d);
if(centerAngle > 90){
return 180;
}
else {
return 0;
}
}
function computeCenterAngle(d) {
var startAngle = Math.max(0, Math.min(2 * Math.PI, x(d.x)));
var endAngle = Math.max(0, Math.min(2 * Math.PI, x(d.x + d.dx)));
var centerAngle = (((startAngle + endAngle) / 2) * (180 / Math.PI)) - 90;
return centerAngle;
}
function labelThresholdMatched(d) {
var startAngle = Math.max(0, Math.min(2 * Math.PI, x(d.x)));
var endAngle = Math.max(0, Math.min(2 * Math.PI, x(d.x + d.dx)));
var size = endAngle - startAngle;
return size > labelThreshold;
}
// When zooming: interpolate the scales.
function arcTweenZoom(e,i) {
var xd = d3.interpolate(x.domain(), [node.x, node.x + node.dx]),
yd = d3.interpolate(y.domain(), [node.y, 1]),
yr = d3.interpolate(y.range(), [node.y ? 20 : 0, radius]);
if (i === 0) {
return function() {return arc(e);}
}
else {
return function (t) {
x.domain(xd(t));
y.domain(yd(t)).range(yr(t));
return arc(e);
}
};
}
function arcTweenUpdate(d) {
var ipo = d3.interpolate({x: d.x0, dx: d.dx0, y: d.y0, dy: d.dy0}, d);
return function (t) {
var b = ipo(t);
d.x0 = b.x;
d.dx0 = b.dx;
d.y0 = b.y;
d.dy0 = b.dy;
return arc(b);
};
}
function updatePrevPosition(node) {
var k = key(node);
if(! prevPositions[k]) prevPositions[k] = {};
var pP = prevPositions[k];
pP.dx = node.dx;
pP.x = node.x;
pP.dy = node.dy;
pP.y = node.y;
}
function storeRetrievePrevPositions(nodes) {
nodes.forEach(function(n){
var k = key(n);
var pP = prevPositions[k];
//console.log(k,n,pP);
if( pP ){
n.dx0 = pP.dx;
n.x0 = pP.x;
n.dy0 = pP.dy;
n.y0 = pP.y;
}
else {
n.dx0 = n.dx;
n.x0 = n.x;
n.dy0 = n.dy;
n.y0 = n.y;
}
updatePrevPosition(n);
});
}
function zoomClick(d) {
var labels = container.selectAll('text')
var path = container.selectAll('path')
// fade out all text elements
labels.transition().attr("opacity",0);
// to allow reference to the new center node
node = d;
path.transition()
.duration(duration)
.attrTween("d", arcTweenZoom)
.each('end', function(e) {
// partially taken from here: http://bl.ocks.org/metmajer/5480307
// check if the animated element's data e lies within the visible angle span given in d
if(e.x >= d.x && e.x < (d.x + d.dx) ){
if(e.depth >= d.depth){
// get a selection of the associated text element
var parentNode = d3.select(this.parentNode);
var arcText = parentNode.select('text');
// fade in the text element and recalculate positions
arcText.transition().duration(duration)
.text( function(e){return labelFormat(e) })
.attr("opacity", function(d){
if(labelThresholdMatched(d)) {
return 1;
}
else {
return 0;
}
})
.attr("transform", function() {
var width = this.getBBox().width;
if(e.depth === 0)
return "translate(" + (width / 2 * - 1) + ",0)";
else if(e.depth === d.depth){
return "translate(" + (y(e.y) + 5) + ",0)";
}
else {
var centerAngle = computeCenterAngle(e);
var rotation = rotationToAvoidUpsideDown(e);
if (rotation === 0) {
return 'rotate('+ centerAngle +')translate(' + (y(e.y) + 5) + ',0)';
}
else {
return 'rotate('+ centerAngle +')translate(' + (y(e.y) + width + 5) + ',0)rotate(' + rotation + ')';
}
}
});
}
}
})
}
//============================================================
// chart function
//------------------------------------------------------------
var renderWatch = nv.utils.renderWatch(dispatch);
function chart(selection) {
renderWatch.reset();
selection.each(function(data) {
container = d3.select(this);
availableWidth = nv.utils.availableWidth(width, container, margin);
availableHeight = nv.utils.availableHeight(height, container, margin);
radius = Math.min(availableWidth, availableHeight) / 2;
y.range([0, radius]);
// Setup containers and skeleton of chart
var wrap = container.select('g.nvd3.nv-wrap.nv-sunburst');
if( !wrap[0][0] ) {
wrap = container.append('g')
.attr('class', 'nvd3 nv-wrap nv-sunburst nv-chart-' + id)
.attr('transform', 'translate(' + availableWidth / 2 + ',' + availableHeight / 2 + ')');
}
container.on('click', function (d, i) {
dispatch.chartClick({
data: d,
index: i,
pos: d3.event,
id: id
});
});
partition.value(modes[mode] || modes["count"]);
//reverse the drawing order so that the labels of inner
//arcs are drawn on top of the outer arcs.
var nodes = partition.nodes(data[0]).reverse()
storeRetrievePrevPositions(nodes);
var cG = wrap.selectAll('.arc-container').data(nodes, key)
//handle new datapoints
var cGE = cG.enter()
.append("g")
.attr("class",'arc-container')
cGE.append("path")
.attr("d", arc)
.style("fill", function (d) {
if (d.color) {
return d.color;
}
else if (groupColorByParent) {
return color((d.children ? d : d.parent).name);
}
else {
return color(d.name);
}
})
.style("stroke", "#FFF")
.on("click", zoomClick)
.on('mouseover', function(d,i){
d3.select(this).classed('hover', true).style('opacity', 0.8);
dispatch.elementMouseover({
data: d,
color: d3.select(this).style("fill")
});
})
.on('mouseout', function(d,i){
d3.select(this).classed('hover', false).style('opacity', 1);
dispatch.elementMouseout({
data: d
});
})
.on('mousemove', function(d,i){
dispatch.elementMousemove({
data: d
});
});
///Iterating via each and selecting based on the this
///makes it work ... a cG.selectAll('path') doesn't.
///Without iteration the data (in the element) didn't update.
cG.each(function(d){
d3.select(this).select('path')
.transition()
.duration(duration)
.attrTween('d', arcTweenUpdate);
});
if(showLabels){
//remove labels first and add them back
cG.selectAll('text').remove();
//this way labels are on top of newly added arcs
cG.append('text')
.text( function(e){ return labelFormat(e)})
.transition()
.duration(duration)
.attr("opacity", function(d){
if(labelThresholdMatched(d)) {
return 1;
}
else {
return 0;
}
})
.attr("transform", function(d) {
var width = this.getBBox().width;
if(d.depth === 0){
return "rotate(0)translate(" + (width / 2 * -1) + ",0)";
}
else {
var centerAngle = computeCenterAngle(d);
var rotation = rotationToAvoidUpsideDown(d);
if (rotation === 0) {
return 'rotate('+ centerAngle +')translate(' + (y(d.y) + 5) + ',0)';
}
else {
return 'rotate('+ centerAngle +')translate(' + (y(d.y) + width + 5) + ',0)rotate(' + rotation + ')';
}
}
});
}
//zoom out to the center when the data is updated.
zoomClick(nodes[nodes.length - 1])
//remove unmatched elements ...
cG.exit()
.transition()
.duration(duration)
.attr('opacity',0)
.each('end',function(d){
var k = key(d);
prevPositions[k] = undefined;
})
.remove();
});
renderWatch.renderEnd('sunburst immediate');
return chart;
}
//============================================================
// Expose Public Variables
//------------------------------------------------------------
chart.dispatch = dispatch;
chart.options = nv.utils.optionsFunc.bind(chart);
chart._options = Object.create({}, {
// simple options, just get/set the necessary values
width: {get: function(){return width;}, set: function(_){width=_;}},
height: {get: function(){return height;}, set: function(_){height=_;}},
mode: {get: function(){return mode;}, set: function(_){mode=_;}},
id: {get: function(){return id;}, set: function(_){id=_;}},
duration: {get: function(){return duration;}, set: function(_){duration=_;}},
groupColorByParent: {get: function(){return groupColorByParent;}, set: function(_){groupColorByParent=!!_;}},
showLabels: {get: function(){return showLabels;}, set: function(_){showLabels=!!_}},
labelFormat: {get: function(){return labelFormat;}, set: function(_){labelFormat=_}},
labelThreshold: {get: function(){return labelThreshold;}, set: function(_){labelThreshold=_}},
sort: {get: function(){return sort;}, set: function(_){sort=_}},
key: {get: function(){return key;}, set: function(_){key=_}},
// options that require extra logic in the setter
margin: {get: function(){return margin;}, set: function(_){
margin.top = _.top != undefined ? _.top : margin.top;
margin.right = _.right != undefined ? _.right : margin.right;
margin.bottom = _.bottom != undefined ? _.bottom : margin.bottom;
margin.left = _.left != undefined ? _.left : margin.left;
}},
color: {get: function(){return color;}, set: function(_){
color=nv.utils.getColor(_);
}}
});
nv.utils.initOptions(chart);
return chart;
};
nv.models.sunburstChart = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var sunburst = nv.models.sunburst();
var tooltip = nv.models.tooltip();
var margin = {top: 30, right: 20, bottom: 20, left: 20}
, width = null
, height = null
, color = nv.utils.defaultColor()
, id = Math.round(Math.random() * 100000)
, defaultState = null
, noData = null
, duration = 250
, dispatch = d3.dispatch('stateChange', 'changeState','renderEnd');
//============================================================
// Private Variables
//------------------------------------------------------------
var renderWatch = nv.utils.renderWatch(dispatch);
tooltip
.duration(0)
.headerEnabled(false)
.valueFormatter(function(d){return d;});
//============================================================
// Chart function
//------------------------------------------------------------
function chart(selection) {
renderWatch.reset();
renderWatch.models(sunburst);
selection.each(function(data) {
var container = d3.select(this);
nv.utils.initSVG(container);
var availableWidth = nv.utils.availableWidth(width, container, margin);
var availableHeight = nv.utils.availableHeight(height, container, margin);
chart.update = function() {
if (duration === 0) {
container.call(chart);
} else {
container.transition().duration(duration).call(chart);
}
};
chart.container = container;
// Display No Data message if there's nothing to show.
if (!data || !data.length) {
nv.utils.noData(chart, container);
return chart;
} else {
container.selectAll('.nv-noData').remove();
}
sunburst.width(availableWidth).height(availableHeight);
container.call(sunburst);
});
renderWatch.renderEnd('sunburstChart immediate');
return chart;
}
//============================================================
// Event Handling/Dispatching (out of chart's scope)
//------------------------------------------------------------
sunburst.dispatch.on('elementMouseover.tooltip', function(evt) {
evt.series = {
key: evt.data.name,
value: (evt.data.value || evt.data.size),
color: evt.color
};
tooltip.data(evt).hidden(false);
});
sunburst.dispatch.on('elementMouseout.tooltip', function(evt) {
tooltip.hidden(true);
});
sunburst.dispatch.on('elementMousemove.tooltip', function(evt) {
tooltip();
});
//============================================================
// Expose Public Variables
//------------------------------------------------------------
// expose chart's sub-components
chart.dispatch = dispatch;
chart.sunburst = sunburst;
chart.tooltip = tooltip;
chart.options = nv.utils.optionsFunc.bind(chart);
// use Object get/set functionality to map between vars and chart functions
chart._options = Object.create({}, {
// simple options, just get/set the necessary values
noData: {get: function(){return noData;}, set: function(_){noData=_;}},
defaultState: {get: function(){return defaultState;}, set: function(_){defaultState=_;}},
// options that require extra logic in the setter
color: {get: function(){return color;}, set: function(_){
color = _;
sunburst.color(color);
}},
duration: {get: function(){return duration;}, set: function(_){
duration = _;
renderWatch.reset(duration);
sunburst.duration(duration);
}},
margin: {get: function(){return margin;}, set: function(_){
margin.top = _.top !== undefined ? _.top : margin.top;
margin.right = _.right !== undefined ? _.right : margin.right;
margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
margin.left = _.left !== undefined ? _.left : margin.left;
}}
});
nv.utils.inheritOptions(chart, sunburst);
nv.utils.initOptions(chart);
return chart;
};
nv.version = "1.8.3-dev";
})(); | {
"content_hash": "e5b4230bc84c1fa4402039906421e4b9",
"timestamp": "",
"source": "github",
"line_count": 14622,
"max_line_length": 219,
"avg_line_length": 41.476337026398575,
"alnum_prop": 0.46845912473390966,
"repo_name": "wlngai/granula",
"id": "df85e71cb125f87f41cccdb2d36e1cff452258da",
"size": "606468",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "granula-visualizer/src/main/resources/granula/lib/nv.d3.js",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?php
// @todo write documentation for this config file
// @todo allow users to create their own layout scheme as a separate plugin
App::import('Vendors','Estilista.tools');
$palette = array(
'text' => new Color( 0, 0, 0),
'bg' => new Color(255,255,255)
);
// @todo create tests for it to really allow same layout for browser
// and print. In the sense that images will scale accordingly, and increase
// it resolution under print.
$unit = new Unit(
array(
'unit_name' => 'px',
'multiplier' => 1,
'round_it' => true
)
);
// @todo Create a basic layout instrument to create the basic for the layout.
$horizontal_grid = new Grid(
array(
'M_size' => 80,
'm_size' => round(80/8,0),
'g_size' => round(80/8,0),
'M_quantity' => 12,
'alignment' => 'left',
'left_gutter' => 0,
'right_gutter' => 0,
'unit' => &$unit
)
);
$vertical_grid = &$horizontal_grid;
// @todo make it allow strings instead of this odd size specification array
$line_height = $horizontal_grid->size(array('g' => 2), false);
$image_generator = new CompoundImage;
// @todo improve the concept of automated class generation, allow for replacement
// of class names and reduced size.
$used_automatic_classes = array(
'width' => array()
);
for ($i = 1; $i <= 12; $i++)
{
$used_automatic_classes['width'][] = array('M' => $i, 'g' => -1);
$used_automatic_classes['width'][] = array('M' => $i, 'g' => 0);
}
for ($i = 1; $i <= 4; $i++)
{
$used_automatic_classes['height'][] = array('M' => 0, 'g' => $i);
}
// @todo Improve the way that we choose the layout instruments we are going
// to use, and the way it handles shortnames.
// Passamos para o configure os objetos
Configure::write('Typographer.Teste.tools',
array(
'vg' => $vertical_grid,
'hg' => $horizontal_grid,
'u' => $unit,
'line_height' => $line_height,
'ig' => $image_generator,
'palette' => $palette
)
);
Configure::write('Typographer.Teste.used_automatic_classes', $used_automatic_classes);
?> | {
"content_hash": "143a080f29bd7829e9d3fbb66f4a91dc",
"timestamp": "",
"source": "github",
"line_count": 81,
"max_line_length": 86,
"avg_line_length": 25.074074074074073,
"alnum_prop": 0.6184145741014279,
"repo_name": "hugomelo/ralsp",
"id": "1b13ddb108b82ab410843930c74daa72d80d2d43",
"size": "2485",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/cake/app/plugins/typographer/config/teste_config.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "932"
},
{
"name": "Batchfile",
"bytes": "1013"
},
{
"name": "CSS",
"bytes": "136986"
},
{
"name": "Groff",
"bytes": "5241"
},
{
"name": "HTML",
"bytes": "2000"
},
{
"name": "JavaScript",
"bytes": "119408"
},
{
"name": "PHP",
"bytes": "8181623"
},
{
"name": "Shell",
"bytes": "1077"
}
],
"symlink_target": ""
} |
<!doctype html>
<html>
<head>
<title>{{ title }}</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
</head>
<body>
{% block body %}
{% endblock %}
</body>
</html>
| {
"content_hash": "3bfd1a42e4d5972ae2cc225290a126fe",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 110,
"avg_line_length": 29.666666666666668,
"alnum_prop": 0.6320224719101124,
"repo_name": "andrewskaggs/lunch-tools",
"id": "00acdbdd053520816c3a9355c1e277ac30d63ddd",
"size": "356",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server/views/layout.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3793"
},
{
"name": "HTML",
"bytes": "19922"
},
{
"name": "JavaScript",
"bytes": "40491"
}
],
"symlink_target": ""
} |
/**
* Created by leo on 1/20/15.
*/
var should = require('should');
var request = require('superagent');
describe("serverError Response test !", function() {
describe("test serverError request !", function() {
it("should response serverError view !", function(done) {
request.get(sails.getBaseurl()+"/api/v1/response/serverError")
.end(function(err,res){
console.log(res.text)
res.text.should.match(/E_VIEW_FAILED/);
done() ;
}) ;
});
});
});
| {
"content_hash": "d4192258d2e19ce1ad0ff2266f061468",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 68,
"avg_line_length": 24.428571428571427,
"alnum_prop": 0.5925925925925926,
"repo_name": "no7dw/warning-system",
"id": "6194468bcfad481dee9acdac5b14da38c645eb27",
"size": "513",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/responses/serverError.test.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "874"
},
{
"name": "HTML",
"bytes": "78394"
},
{
"name": "JavaScript",
"bytes": "175610"
},
{
"name": "Makefile",
"bytes": "482"
}
],
"symlink_target": ""
} |
<!--
/*
-->
<!doctype html>
<title>resolving broken url</title>
<link rel=help href="http://www.whatwg.org/html/#dom-sharedworker">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<div id="log"></div>
<script>
test(function() {
assert_throws("SyntaxError", function() {
var worker = new SharedWorker('http://foo bar');
});
});
</script>
<!--
*/
//-->
| {
"content_hash": "a8a80a59a731e2b9f232b2f774c1c85a",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 67,
"avg_line_length": 21.94736842105263,
"alnum_prop": 0.645083932853717,
"repo_name": "google-ar/WebARonARCore",
"id": "2ca3d93d3e8fa2a16a557370fe85bca3952e1713",
"size": "417",
"binary": false,
"copies": "251",
"ref": "refs/heads/webarcore_57.0.2987.5",
"path": "third_party/WebKit/LayoutTests/external/wpt/workers/constructors/SharedWorker/unresolvable-url.html",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package persistentvolume
import (
"reflect"
"testing"
"github.com/kubernetes/dashboard/src/app/backend/api"
"github.com/kubernetes/dashboard/src/app/backend/resource/dataselect"
v1 "k8s.io/api/core/v1"
storage "k8s.io/api/storage/v1"
metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes/fake"
)
func TestGetPersistentVolumeClaim(t *testing.T) {
cases := []struct {
persistentVolume *v1.PersistentVolume
expected string
}{
{
&v1.PersistentVolume{
ObjectMeta: metaV1.ObjectMeta{Name: "foo"},
Spec: v1.PersistentVolumeSpec{
ClaimRef: &v1.ObjectReference{
Namespace: "default",
Name: "my-claim"},
},
},
"default/my-claim",
},
{
&v1.PersistentVolume{
ObjectMeta: metaV1.ObjectMeta{Name: "foo"},
Spec: v1.PersistentVolumeSpec{},
},
"",
},
}
for _, c := range cases {
actual := getPersistentVolumeClaim(c.persistentVolume)
if !reflect.DeepEqual(actual, c.expected) {
t.Errorf("getPersistentVolumeClaim(%#v) == \n%#v\nexpected \n%#v\n",
c.persistentVolume, actual, c.expected)
}
}
}
func TestGetStorageClassPersistentVolumes(t *testing.T) {
cases := []struct {
storageClass *storage.StorageClass
name string
persistentVolumeList *v1.PersistentVolumeList
expected *PersistentVolumeList
}{
{
storageClass: &storage.StorageClass{ObjectMeta: metaV1.ObjectMeta{
Name: "test-storage", Labels: map[string]string{"app": "test"},
}},
name: "test-storage",
persistentVolumeList: &v1.PersistentVolumeList{Items: []v1.PersistentVolume{
{
ObjectMeta: metaV1.ObjectMeta{
Name: "pv-1", Labels: map[string]string{"app": "test"},
},
Spec: v1.PersistentVolumeSpec{
StorageClassName: "test-storage",
},
},
}},
expected: &PersistentVolumeList{
ListMeta: api.ListMeta{TotalItems: 1},
Items: []PersistentVolume{{
TypeMeta: api.TypeMeta{Kind: api.ResourceKindPersistentVolume},
StorageClass: "test-storage",
ObjectMeta: api.ObjectMeta{Name: "pv-1",
Labels: map[string]string{"app": "test"}},
}},
Errors: []error{},
},
},
}
for _, c := range cases {
fakeClient := fake.NewSimpleClientset(c.persistentVolumeList, c.storageClass)
actual, _ := GetStorageClassPersistentVolumes(fakeClient, c.name, dataselect.NoDataSelect)
if !reflect.DeepEqual(actual, c.expected) {
t.Errorf("GetStorageClassPersistentVolumes(client, %#v) == \ngot: %#v, \nexpected %#v",
c.name, actual, c.expected)
}
}
}
| {
"content_hash": "e42a7e94d02fa04bba535b57eef7aef9",
"timestamp": "",
"source": "github",
"line_count": 95,
"max_line_length": 92,
"avg_line_length": 27.05263157894737,
"alnum_prop": 0.6614785992217899,
"repo_name": "kenan435/dashboard",
"id": "9b178c6728cf5ed69e9b1c95046d1a8d24a2fec9",
"size": "3171",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/app/backend/resource/persistentvolume/common_test.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "75964"
},
{
"name": "Go",
"bytes": "1084390"
},
{
"name": "HTML",
"bytes": "495975"
},
{
"name": "JavaScript",
"bytes": "1545440"
},
{
"name": "Shell",
"bytes": "7622"
},
{
"name": "XSLT",
"bytes": "2532"
}
],
"symlink_target": ""
} |
title: Deployment Checklist
sidebar_label: Checklist
---
## Set the Node.JS environment to `production`
Set the `NODE_ENV` (or `FOAL_ENV`) environment variable to `production`.
```bash
NODE_ENV=production npm run start
```
## Use HTTPS
You must use HTTPS to prevent [man-in-the-middle attacks](https://en.wikipedia.org/wiki/Man-in-the-middle_attack). Otherwise, your credentials and authentication tokens will appear in clear on the network.
If you use cookies, make sure to let them only be sent to the server when the request is made using SSL. You can do such thing with the cookie `secure` directive.
*config/production.yml (example)*
```yaml
settings:
// If you use sessions
session:
cookie:
secure: true
// If you use JWT
jwt:
cookie:
secure: true
```
## Generate Different Secrets
Use different secrets for your production environment (JWT, etc). Specify them using environment variables or a `.env` file.
*.env (example)*
```
SETTINGS_JWT_SECRET=YZP0iv6gM+VBTxk61l8nKUno2QxsQHO9hm8XfeedZUw
```
You can generate 256-bit secrets encoded in base64 with the following command:
```bash
foal createsecret
```
## Database Credentials & Migrations
Use different credentials for your production database. Specify them using environment variables or a `.env` file.
If you use database migrations, run them on your production server with the following command:
```bash
npm run migrations
```
## Files to Upload
If you install dependencies and build the app on the remote host, then you should upload these files:
```sh
config/
ormconfig.js
package-lock.json
package.json
public/ # this may depend on how the platform manages static files
src/
tsconfig.app.json
```
Then you will need to run `npm install` and `npm run build`.
> If you get an error such as `Foal not found error`, it is probably because the dev dependencies (which include the `@foal/cli` package) have not been installed. To force the installation of these dependencies, you can use the following command: `npm install --production=false`.
If you install dependencies and build the app on your local host directly, then you should upload these files:
```sh
build/
config/
node_modules/
ormconfig.js
package-lock.json
package.json
public/ # this may depend on how the platform manages static files
```
| {
"content_hash": "593c09c42500a6263ddb79dced7a3dd5",
"timestamp": "",
"source": "github",
"line_count": 88,
"max_line_length": 280,
"avg_line_length": 26.352272727272727,
"alnum_prop": 0.7524795170332039,
"repo_name": "FoalTS/foal",
"id": "2e86cfa5fc86cc24285a49fe5979da305c4263f0",
"size": "2323",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "docs/i18n/id/docusaurus-plugin-content-docs/version-2.x/deployment-and-environments/checklist.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "13340"
},
{
"name": "JavaScript",
"bytes": "13176"
},
{
"name": "Shell",
"bytes": "4470"
},
{
"name": "TypeScript",
"bytes": "1843250"
}
],
"symlink_target": ""
} |
// Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.skyframe;
import static com.google.common.truth.Truth.assertThat;
import com.google.common.collect.ImmutableList;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Test for {@code ReverseDepsUtilImpl}.
*/
@RunWith(Parameterized.class)
public class ReverseDepsUtilImplTest {
private static final SkyFunctionName NODE_TYPE = SkyFunctionName.create("Type");
private final int numElements;
@Parameters
public static List<Object[]> paramenters() {
List<Object[]> params = new ArrayList<>();
for (int i = 0; i < 20; i++) {
params.add(new Object[] {i});
}
return params;
}
public ReverseDepsUtilImplTest(int numElements) {
this.numElements = numElements;
}
private static final ReverseDepsUtil<Example> REVERSE_DEPS_UTIL =
new ReverseDepsUtilImpl<Example>() {
@Override
void setReverseDepsObject(Example container, Object object) {
container.reverseDeps = object;
}
@Override
void setSingleReverseDep(Example container, boolean singleObject) {
container.single = singleObject;
}
@Override
void setDataToConsolidate(Example container, List<Object> dataToConsolidate) {
container.dataToConsolidate = dataToConsolidate;
}
@Override
Object getReverseDepsObject(Example container) {
return container.reverseDeps;
}
@Override
boolean isSingleReverseDep(Example container) {
return container.single;
}
@Override
List<Object> getDataToConsolidate(Example container) {
return container.dataToConsolidate;
}
};
private class Example {
Object reverseDeps = ImmutableList.of();
boolean single;
List<Object> dataToConsolidate;
@Override
public String toString() {
return "Example: " + reverseDeps + ", " + single + ", " + dataToConsolidate;
}
}
@Test
public void testAddAndRemove() {
for (int numRemovals = 0; numRemovals <= numElements; numRemovals++) {
Example example = new Example();
for (int j = 0; j < numElements; j++) {
REVERSE_DEPS_UTIL.addReverseDeps(
example, Collections.singleton(SkyKey.create(NODE_TYPE, j)));
}
// Not a big test but at least check that it does not blow up.
assertThat(REVERSE_DEPS_UTIL.toString(example)).isNotEmpty();
assertThat(REVERSE_DEPS_UTIL.getReverseDeps(example)).hasSize(numElements);
for (int i = 0; i < numRemovals; i++) {
REVERSE_DEPS_UTIL.removeReverseDep(example, SkyKey.create(NODE_TYPE, i));
}
assertThat(REVERSE_DEPS_UTIL.getReverseDeps(example)).hasSize(numElements - numRemovals);
assertThat(example.dataToConsolidate).isNull();
}
}
// Same as testAdditionAndRemoval but we add all the reverse deps in one call.
@Test
public void testAddAllAndRemove() {
for (int numRemovals = 0; numRemovals <= numElements; numRemovals++) {
Example example = new Example();
List<SkyKey> toAdd = new ArrayList<>();
for (int j = 0; j < numElements; j++) {
toAdd.add(SkyKey.create(NODE_TYPE, j));
}
REVERSE_DEPS_UTIL.addReverseDeps(example, toAdd);
assertThat(REVERSE_DEPS_UTIL.getReverseDeps(example)).hasSize(numElements);
for (int i = 0; i < numRemovals; i++) {
REVERSE_DEPS_UTIL.removeReverseDep(example, SkyKey.create(NODE_TYPE, i));
}
assertThat(REVERSE_DEPS_UTIL.getReverseDeps(example)).hasSize(numElements - numRemovals);
assertThat(example.dataToConsolidate).isNull();
}
}
@Test
public void testDuplicateCheckOnGetReverseDeps() {
Example example = new Example();
for (int i = 0; i < numElements; i++) {
REVERSE_DEPS_UTIL.addReverseDeps(example, Collections.singleton(SkyKey.create(NODE_TYPE, i)));
}
// Should only fail when we call getReverseDeps().
REVERSE_DEPS_UTIL.addReverseDeps(example, Collections.singleton(SkyKey.create(NODE_TYPE, 0)));
try {
REVERSE_DEPS_UTIL.getReverseDeps(example);
assertThat(numElements).isEqualTo(0);
} catch (Exception expected) {
}
}
@Test
public void doubleAddThenRemove() {
Example example = new Example();
SkyKey key = SkyKey.create(NODE_TYPE, 0);
REVERSE_DEPS_UTIL.addReverseDeps(example, Collections.singleton(key));
// Should only fail when we call getReverseDeps().
REVERSE_DEPS_UTIL.addReverseDeps(example, Collections.singleton(key));
REVERSE_DEPS_UTIL.removeReverseDep(example, key);
try {
REVERSE_DEPS_UTIL.getReverseDeps(example);
Assert.fail();
} catch (IllegalStateException expected) {
}
}
@Test
public void doubleAddThenRemoveCheckedOnSize() {
Example example = new Example();
SkyKey fixedKey = SkyKey.create(NODE_TYPE, 0);
SkyKey key = SkyKey.create(NODE_TYPE, 1);
REVERSE_DEPS_UTIL.addReverseDeps(example, ImmutableList.of(fixedKey, key));
// Should only fail when we reach the limit.
REVERSE_DEPS_UTIL.addReverseDeps(example, Collections.singleton(key));
REVERSE_DEPS_UTIL.removeReverseDep(example, key);
REVERSE_DEPS_UTIL.checkReverseDep(example, fixedKey);
try {
REVERSE_DEPS_UTIL.checkReverseDep(example, fixedKey);
Assert.fail();
} catch (IllegalStateException expected) {
}
}
@Test
public void addRemoveAdd() {
Example example = new Example();
SkyKey fixedKey = SkyKey.create(NODE_TYPE, 0);
SkyKey key = SkyKey.create(NODE_TYPE, 1);
REVERSE_DEPS_UTIL.addReverseDeps(example, ImmutableList.of(fixedKey, key));
REVERSE_DEPS_UTIL.removeReverseDep(example, key);
REVERSE_DEPS_UTIL.addReverseDeps(example, Collections.singleton(key));
assertThat(REVERSE_DEPS_UTIL.getReverseDeps(example)).containsExactly(fixedKey, key);
}
@Test
public void testMaybeCheck() {
Example example = new Example();
for (int i = 0; i < numElements; i++) {
REVERSE_DEPS_UTIL.addReverseDeps(example, Collections.singleton(SkyKey.create(NODE_TYPE, i)));
// This should always succeed, since the next element is still not present.
REVERSE_DEPS_UTIL.maybeCheckReverseDepNotPresent(example, SkyKey.create(NODE_TYPE, i + 1));
}
try {
REVERSE_DEPS_UTIL.maybeCheckReverseDepNotPresent(example, SkyKey.create(NODE_TYPE, 0));
// Should only fail if empty or above the checking threshold.
assertThat(numElements == 0 || numElements >= ReverseDepsUtilImpl.MAYBE_CHECK_THRESHOLD)
.isTrue();
} catch (Exception expected) {
}
}
}
| {
"content_hash": "cf2c9a286a0f282bab9ca6b957c1b90b",
"timestamp": "",
"source": "github",
"line_count": 209,
"max_line_length": 100,
"avg_line_length": 35.49760765550239,
"alnum_prop": 0.6885024935975199,
"repo_name": "anupcshan/bazel",
"id": "7c5e47686961e51dbcaea84727637c466f1343ef",
"size": "7419",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/test/java/com/google/devtools/build/skyframe/ReverseDepsUtilImplTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "78"
},
{
"name": "C",
"bytes": "48918"
},
{
"name": "C++",
"bytes": "302447"
},
{
"name": "HTML",
"bytes": "17129"
},
{
"name": "Java",
"bytes": "16699472"
},
{
"name": "Objective-C",
"bytes": "5420"
},
{
"name": "Protocol Buffer",
"bytes": "91066"
},
{
"name": "Python",
"bytes": "265316"
},
{
"name": "Shell",
"bytes": "462997"
}
],
"symlink_target": ""
} |
package org.teachingkidsprogramming.section03ifs;
import java.awt.Color;
import org.teachingextensions.approvals.lite.util.ThreadUtils;
import org.teachingextensions.logo.Tortoise;
import org.teachingextensions.logo.utils.ColorUtils.PenColors;
import org.teachingextensions.logo.utils.EventUtils.MessageBox;
public class ChooseYourOwnAdventure2
{
public static void main(String[] args)
{
startStory();
}
private static void startStory()
{
tellMoreStory("One morning the Tortoise woke up in a dream.");
animateStartStory();
String action = askAQuestion("Do you want to 'wake up' or 'explore' the dream?");
if ("wake up".equalsIgnoreCase(action))
{
wakeUp();
}
else if ("explore".equalsIgnoreCase(action))
{
approachOoze();
}
else
{
endStory();
}
}
private static void endStory()
{
MessageBox.showMessage("You don't know how to read directions. You can't play this game. The end.");
}
private static void approachOoze()
{
MessageBox.showMessage(
"You approach a glowing, green bucket of ooze. Worried that you will get in trouble, you pick up the bucket.");
String answer = MessageBox.askForTextInput("Do you want to pour the ooze into the 'backyard' or 'toilet'?");
if ("toilet".equalsIgnoreCase(answer))
{
pourIntoToilet();
}
else if ("backyard".equalsIgnoreCase(answer))
{
pourIntoBackyard();
}
else
{
endStory();
}
}
private static void pourIntoBackyard()
{
// pourIntoBackyard (recipe below) --#19.1
// ------------- Recipe for pourIntoBackyard --#19.2
MessageBox.showMessage(
"As you walk into the backyard a net scoops you up and a giant takes you to a boiling pot of water.");
MessageBox.askForTextInput("As the man starts to prepare you as soup, do you...'Scream' or 'Faint'?");
// If they answer "faint" --#20.1
// Tell the user "You made a delicious soup! Yum! The end." --#21
// Otherwise, if they answer "scream" --#20.2
// startStory --#22
// Otherwise, if they answer anything else --#20.3
// endStory --#23
//------------- End of pourIntoBackyard recipe --#19.3
}
private static void pourIntoToilet()
{
MessageBox.showMessage(
"As you pour the ooze into the toilet it backs up, gurgles, and explodes, covering you in radioactive waste.");
String answer = MessageBox.askForTextInput("Do you want to train to be a NINJA? 'Yes' or 'HECK YES'?");
if (answer.equalsIgnoreCase("yes"))
{
MessageBox
.showMessage("Awesome dude! You live out the rest of your life fighting crimes and eating pizza!");
}
else if ("heck yes".equalsIgnoreCase(answer))
{
MessageBox
.showMessage("Awesome dude! You live out the rest of your life fighting crimes and eating pizza!");
}
else
{
endStory();
}
}
private static void wakeUp()
{
MessageBox.showMessage("You wake up and have a boring day. The end.");
}
private static void animateStartStory()
{
Tortoise.show();
Color color = PenColors.Grays.Black;
for (int i = 0; i < 25; i++)
{
Tortoise.getBackgroundWindow().setColor(color);
color = PenColors.lighten(color);
ThreadUtils.sleep(100);
}
}
private static void tellMoreStory(String message)
{
MessageBox.showMessage(message);
}
private static String askAQuestion(String question)
{
String answer = MessageBox.askForTextInput(question);
return answer;
}
}
| {
"content_hash": "83c9a3b54610abf4e17cee2c4858fb7d",
"timestamp": "",
"source": "github",
"line_count": 115,
"max_line_length": 119,
"avg_line_length": 32.00869565217391,
"alnum_prop": 0.634881825590872,
"repo_name": "91096008/TeachingKidsProgramming",
"id": "f89699d17360a27568b1c0866ffe6ff27272b528",
"size": "3681",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/org/teachingkidsprogramming/section03ifs/ChooseYourOwnAdventure2.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "136899"
}
],
"symlink_target": ""
} |
package com.freshplanet.ane.AirAmazonMP3.functions;
import android.content.pm.PackageManager;
import com.adobe.fre.FREContext;
import com.adobe.fre.FREObject;
public class HasAmazonMP3AppFunction extends BaseFunction {
@Override
public FREObject call(FREContext context, FREObject[] args) {
super.call(context, args);
PackageManager packageManager = context.getActivity().getPackageManager();
Boolean hasAmazonMP3App = false;
try {
packageManager.getPackageInfo("com.amazon.mp3", PackageManager.GET_ACTIVITIES);
hasAmazonMP3App = true;
}
catch (PackageManager.NameNotFoundException e) {
hasAmazonMP3App = false;
}
try {
return FREObject.newObject(hasAmazonMP3App);
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
| {
"content_hash": "ceb464fc6a5d6022dcfc62224ce79846",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 82,
"avg_line_length": 23.058823529411764,
"alnum_prop": 0.7487244897959183,
"repo_name": "freshplanet/ANE-AmazonMP3",
"id": "9bd9e04b1443dcf389a90f68d964ca7c19902364",
"size": "1375",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "android/lib/src/main/java/com/freshplanet/ane/AirAmazonMP3/functions/HasAmazonMP3AppFunction.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ActionScript",
"bytes": "5342"
},
{
"name": "Java",
"bytes": "13484"
},
{
"name": "Shell",
"bytes": "643"
}
],
"symlink_target": ""
} |
{% macro edit_link(value, endpoint) %}
{% if value.can_edit() %}
<a href="{{ url_for(endpoint + '.edit_view', id=value.id) }}" target="_blank"><span class="fa fa-pencil glyphicon glyphicon-pencil"></span></a>
{% endif %}
{% endmacro %}
{% macro detail_link(value, endpoint) %}
{% if value.can_view_details() %}
<a href="{{ url_for(endpoint + '.details_view', id=value.id) }}" target="_blank"><span class="fa fa-eye glyphicon glyphicon-eye-open"></span></a>
{% endif %}
{% endmacro %}
<a style='cursor:help' data-toggle='popover'
title='{{ title }} <span class="object-ref-link">{{ edit_link(value, endpoint) }} {{ detail_link(value, endpoint) }}</span>'
data-content='<table class="object-ref-header-table table table-responsive table-striped table-condensed table-condensed">
<tr><th colspan="2">基本信息</th></tr>
{% for f in header %}
<tr><td>{{ f.label }}</td><td>{{ f.value or ' ' }}</td></tr>
{% endfor %}
</table>
{% if detail_labels|length > 0 %}
<table class="object-ref-line-table table table-striped table-bordered table-hover table-condensed">
<tr><th colspan="{{ detail_labels|length }}">行信息</th></tr>
<tr>
{% for label in detail_labels %}<th>{{ label }}</th>{% endfor %}
</tr>
{% for line in detail_lines %}
<tr>{% for field in line %}<td>{{ field or ' ' }}</td>{% endfor %}</tr>
{% endfor %}
</table>
{% endif %}'>[ {{ title }} ]</a>
| {
"content_hash": "6a6036290d0fd9923b5e67401ce81a49",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 153,
"avg_line_length": 47.61290322580645,
"alnum_prop": 0.5785907859078591,
"repo_name": "betterlife/flask-psi",
"id": "2be83a22aca21654bd753d1b6bf372ca14b4eb83",
"size": "1490",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "psi/templates/components/object_ref.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "8807"
},
{
"name": "HTML",
"bytes": "24618"
},
{
"name": "JavaScript",
"bytes": "12365"
},
{
"name": "Mako",
"bytes": "412"
},
{
"name": "Python",
"bytes": "202168"
},
{
"name": "Shell",
"bytes": "726"
}
],
"symlink_target": ""
} |
package de.jpaw.util;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.file.Paths;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class ConfigurationReaderFactory {
private static final Logger LOGGER = LoggerFactory.getLogger(ConfigurationReaderFactory.class);
public static final String DEFAULT_JPAW_PROPERTIES = "&./jpaw.properties";
private static final ConfigurationReaderInstance FALLBACK_READER = new ConfigurationReaderInstance();
/** A cache to keep all instances of the readers. */
private static final Map<String, ConfigurationReaderInstance> INSTANCES = new ConcurrentHashMap<>();
private ConfigurationReaderFactory() { }
private static ConfigurationReaderInstance getConfigReaderFromPath(final String path) {
try (final FileInputStream fis = new FileInputStream(path)) {
return new ConfigurationReaderInstance(fis, path, "file");
} catch (Exception e) {
LOGGER.error("Error obtaining properties from file {}: {} {}", path, e.getMessage(), ExceptionUtil.causeChain(e));
return FALLBACK_READER;
}
}
private static ConfigurationReaderInstance getConfigReaderFromResource(final String path) {
try (final InputStream is = ConfigurationReaderFactory.class.getResourceAsStream(path.substring(1))) {
if (is == null) {
// null is a valid response, if the resource does not exist
LOGGER.warn("Resource {} does not exist, using fallback configuration (environment / system property only)", path);
return FALLBACK_READER;
}
return new ConfigurationReaderInstance(is, path, "resource");
} catch (Exception e) {
LOGGER.warn("Error obtaining properties from resource {}, using fallback configuration (environment / system property only): {} {}",
path, e.getMessage(), ExceptionUtil.causeChain(e));
return FALLBACK_READER;
}
}
/** Returns a configuration reader which uses environment or system properties only. */
public static ConfigurationReaderInstance getEnvOrSystemPropConfigReader() {
return FALLBACK_READER;
}
/** Returns a configuration reader which uses a property file as specified by a system property. */
public static ConfigurationReaderInstance getConfigReaderForName(String propertyFileName, String defaultPath) {
final String realPropertiesPath = FALLBACK_READER.getProperty(propertyFileName, defaultPath);
final String currentWorkingDir = Paths.get("").toAbsolutePath().toString();
if (realPropertiesPath == null) {
// no default path specified, and no property set, use fallback reader
LOGGER.info("Using env/system property configuration for {} (path is unspecified and no default given)", propertyFileName);
return FALLBACK_READER;
}
LOGGER.info("Reading {} from path {} (working dir is {})", propertyFileName, realPropertiesPath, currentWorkingDir);
return getConfigReader(realPropertiesPath);
}
/** Returns a configuration reader which uses a resource or file as fallback. */
public static ConfigurationReaderInstance getConfigReader(final String propertiesFilePath) {
if (propertiesFilePath == null || propertiesFilePath.isEmpty()) {
// get instance without property file
return INSTANCES.computeIfAbsent("", path -> new ConfigurationReaderInstance());
}
return INSTANCES.computeIfAbsent(propertiesFilePath, path -> {
final char firstChar = path.charAt(0);
if (firstChar == '~') {
// expand ~ by user's home
return getConfigReaderFromPath(System.getProperty("user.home") + path.substring(1));
}
if (firstChar == '&') {
// read from resource
return getConfigReaderFromResource(path.substring(1));
}
// read from unmodified filename
return getConfigReaderFromPath(path);
});
}
public static ConfigurationReaderInstance getDefaultJpawConfigReader() {
final String jpawPropertiesPath = FALLBACK_READER.getProperty("jpaw.properties", DEFAULT_JPAW_PROPERTIES);
LOGGER.info("Reading jpaw.properties from path {}", jpawPropertiesPath);
return getConfigReader(jpawPropertiesPath);
}
}
| {
"content_hash": "ed0f3b477e3b9c8e3cafac02e5a258f8",
"timestamp": "",
"source": "github",
"line_count": 92,
"max_line_length": 144,
"avg_line_length": 49.32608695652174,
"alnum_prop": 0.6846628470691934,
"repo_name": "jpaw/jpaw",
"id": "63f43af39500b5a506ad7338130e1bad8c3b8e5f",
"size": "4538",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "jpaw-util/src/main/java/de/jpaw/util/ConfigurationReaderFactory.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "2901"
},
{
"name": "Java",
"bytes": "825643"
},
{
"name": "Makefile",
"bytes": "776"
},
{
"name": "Shell",
"bytes": "4364"
},
{
"name": "Xtend",
"bytes": "15484"
}
],
"symlink_target": ""
} |
<?php
namespace Drupal\Component\Plugin\Exception;
/**
* Generic Plugin exception class to be thrown when no more specific class
* is applicable.
*/
class PluginException extends \Exception implements ExceptionInterface { }
| {
"content_hash": "fe9a775aed6a3e4e148cde32662fe529",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 74,
"avg_line_length": 25.444444444444443,
"alnum_prop": 0.777292576419214,
"repo_name": "sweimer/ICFID8",
"id": "49a12cabc664d3bbe37d81f627e2646b84015cdc",
"size": "229",
"binary": false,
"copies": "476",
"ref": "refs/heads/master",
"path": "docroot/core/lib/Drupal/Component/Plugin/Exception/PluginException.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "974154"
},
{
"name": "Gherkin",
"bytes": "10701"
},
{
"name": "HTML",
"bytes": "813389"
},
{
"name": "JavaScript",
"bytes": "2371726"
},
{
"name": "PHP",
"bytes": "38283693"
},
{
"name": "PLpgSQL",
"bytes": "2020"
},
{
"name": "Shell",
"bytes": "62999"
}
],
"symlink_target": ""
} |
using System;
using System.Reflection;
using System.Diagnostics;
using System.Globalization;
using System.Collections.Generic;
using System.Reflection.Runtime.General;
using System.Reflection.Runtime.TypeInfos;
using System.Reflection.Runtime.ParameterInfos;
using System.Runtime.InteropServices;
using Internal.Reflection.Core.Execution;
namespace System.Reflection.Runtime.MethodInfos
{
//
// This represents the synthetic nullary instance constructor for Types created by Type.GetTypeFromCLSID().
//
internal sealed partial class RuntimeCLSIDNullaryConstructorInfo : RuntimeConstructorInfo
{
private RuntimeCLSIDNullaryConstructorInfo(RuntimeCLSIDTypeInfo declaringType)
{
_declaringType = declaringType;
}
public sealed override MethodAttributes Attributes => MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName;
public sealed override CallingConventions CallingConvention => CallingConventions.Standard | CallingConventions.HasThis;
public sealed override IEnumerable<CustomAttributeData> CustomAttributes => Empty<CustomAttributeData>.Enumerable;
public sealed override Type DeclaringType => _declaringType;
public sealed override bool HasSameMetadataDefinitionAs(MemberInfo other)
{
if (other == null)
throw new ArgumentNullException(nameof(other));
// This logic is written to match CoreCLR's behavior.
return other is RuntimeCLSIDNullaryConstructorInfo;
}
public sealed override bool Equals(object obj)
{
RuntimeCLSIDNullaryConstructorInfo other = obj as RuntimeCLSIDNullaryConstructorInfo;
if (other == null)
return false;
if (!(_declaringType.Equals(other._declaringType)))
return false;
return true;
}
public sealed override int GetHashCode() => _declaringType.GetHashCode();
public sealed override object Invoke(BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
{
if (parameters != null && parameters.Length != 0)
throw new TargetParameterCountException();
Guid clsid = _declaringType.GUID;
string server = _declaringType.Server;
IntPtr pItf = IntPtr.Zero;
try
{
pItf = McgMarshal.CoCreateInstanceEx(clsid, server);
// CoCreateInstanceEx will throw exception if it fails to
// create an instance.
Debug.Assert(pItf != IntPtr.Zero);
return Marshal.GetObjectForIUnknown(pItf);
}
finally
{
if (pItf != IntPtr.Zero)
Marshal.Release(pItf);
}
}
public sealed override MethodBase MetadataDefinitionMethod { get { throw new NotSupportedException(); } }
public sealed override int MetadataToken { get { throw new InvalidOperationException(); } }
public sealed override RuntimeMethodHandle MethodHandle { get { throw new PlatformNotSupportedException(); } }
public sealed override MethodImplAttributes MethodImplementationFlags => MethodImplAttributes.IL;
public sealed override string Name => ConstructorInfo.ConstructorName;
protected sealed override RuntimeParameterInfo[] RuntimeParameters => Array.Empty<RuntimeParameterInfo>();
public sealed override string ToString()
{
// A constructor's "return type" is always System.Void and we don't want to allocate a ParameterInfo object to record that revelation.
// In deference to that, ComputeToString() lets us pass null as a synonym for "void."
return RuntimeMethodHelpers.ComputeToString(this, Array.Empty<RuntimeTypeInfo>(), RuntimeParameters, returnParameter: null);
}
protected sealed override MethodInvoker UncachedMethodInvoker
{
get
{
// If we got here, someone called MethodBase.Invoke() (not to be confused with ConstructorInfo.Invoke()). When invoked a constructor, that overload
// (which should never been exposed on MethodBase) reexecutes a constructor on an already constructed object. This is meaningless so leaving it PNSE
// unless there's a real-world app that does this.
throw new PlatformNotSupportedException();
}
}
private readonly RuntimeCLSIDTypeInfo _declaringType;
}
}
| {
"content_hash": "1b52585ce0be21652a995051feef6b0a",
"timestamp": "",
"source": "github",
"line_count": 108,
"max_line_length": 179,
"avg_line_length": 43.2037037037037,
"alnum_prop": 0.6735962280325761,
"repo_name": "krytarowski/corert",
"id": "5fa00d9c2c90de9520d0d69375726c659b828180",
"size": "4870",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/System.Private.Reflection.Core/src/System/Reflection/Runtime/MethodInfos/RuntimeClsIdNullaryConstructorInfo.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "740594"
},
{
"name": "Batchfile",
"bytes": "61072"
},
{
"name": "C",
"bytes": "661396"
},
{
"name": "C#",
"bytes": "19664551"
},
{
"name": "C++",
"bytes": "4320041"
},
{
"name": "CMake",
"bytes": "55995"
},
{
"name": "Groovy",
"bytes": "4569"
},
{
"name": "Objective-C",
"bytes": "14147"
},
{
"name": "PAWN",
"bytes": "849"
},
{
"name": "PowerShell",
"bytes": "2992"
},
{
"name": "Shell",
"bytes": "106427"
}
],
"symlink_target": ""
} |
import path = require('path');
import tl = require('vsts-task-lib/task');
import sign = require('ios-signing-common/ios-signing-common');
import utils = require('./xcodeutils');
import { ToolRunner } from 'vsts-task-lib/toolrunner';
async function run() {
try {
tl.setResourcePath(path.join(__dirname, 'task.json'));
//clean up the temporary keychain, so it is not used to search for code signing identity in future builds
var keychainToDelete = utils.getTaskState('XCODE_KEYCHAIN_TO_DELETE')
if (keychainToDelete) {
try {
await sign.deleteKeychain(keychainToDelete);
} catch (err) {
tl.debug('Failed to delete temporary keychain. Error = ' + err);
tl.warning(tl.loc('TempKeychainDeleteFailed', keychainToDelete));
}
}
//delete provisioning profile if specified
var profileToDelete = utils.getTaskState('XCODE_PROFILE_TO_DELETE');
if (profileToDelete) {
try {
await sign.deleteProvisioningProfile(profileToDelete);
} catch (err) {
tl.debug('Failed to delete provisioning profile. Error = ' + err);
tl.warning(tl.loc('ProvProfileDeleteFailed', profileToDelete));
}
}
} catch (err) {
tl.setResult(tl.TaskResult.Failed, err);
}
}
run(); | {
"content_hash": "7843ece24dee3d0828d6c6bd5186fe70",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 113,
"avg_line_length": 35.87179487179487,
"alnum_prop": 0.6061472480343102,
"repo_name": "alexmullans/vsts-tasks",
"id": "b3f183044f2acd401e6e89e7aa9778dcf2f84f51",
"size": "1399",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "Tasks/Xcode/postxcode.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "757"
},
{
"name": "CSS",
"bytes": "3780"
},
{
"name": "HTML",
"bytes": "47002"
},
{
"name": "Java",
"bytes": "1575"
},
{
"name": "JavaScript",
"bytes": "82602"
},
{
"name": "PowerShell",
"bytes": "1243257"
},
{
"name": "SQLPL",
"bytes": "7822"
},
{
"name": "Shell",
"bytes": "23492"
},
{
"name": "TypeScript",
"bytes": "3274794"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<!--
Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
-->
<html>
<head>
<title>Jasmine Spec Runner</title>
<link href="thirdparty/bootstrap2/css/bootstrap.min.css" rel="stylesheet">
<link href="thirdparty/bootstrap2/css/bootstrap-responsive.min.css" rel="stylesheet">
<link href="BootstrapReporterView.css" rel="stylesheet">
<script src="thirdparty/jasmine-core/jasmine.js"></script>
<!-- Pre-load third party scripts that cannot be async loaded. -->
<!-- Keep in sync with Gruntfile.js jasmine vendor dependencies -->
<script src="../src/thirdparty/jquery-2.1.0.min.js"></script>
<script src="../src/thirdparty/mustache/mustache.js"></script>
<script src="../src/thirdparty/path-utils/path-utils.js"></script>
<script src="../src/thirdparty/less-1.7.0.min.js"></script>
<script src="thirdparty/bootstrap2/js/bootstrap.min.js"></script>
<!-- All other scripts are loaded through require. -->
<script src="../src/thirdparty/requirejs/require.js" data-main="SpecRunner"></script>
</head>
<body>
<div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">Brackets Tests</a>
<div class="nav-collapse">
<ul class="nav">
<li><a id="all" href="?suite=all">All</a></li>
<li><a id="unit" href="?suite=unit">Unit</a></li>
<li><a id="integration" href="?suite=integration">Integration</a></li>
<li><a id="livepreview" href="?suite=livepreview">Live Preview</a></li>
<li><a id="performance" href="?suite=performance">Performance</a></li>
<li><a id="extension" href="?suite=extension">Extensions</a></li>
<li><a id="reload" href="#">Reload</a></li>
<li><a id="show-dev-tools" href="#">Show Developer Tools</a></li>
</ul>
</div>
</div>
</div>
</div>
</body>
</html>
| {
"content_hash": "c7618cde67dfb27ab2d4efe20815817d",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 90,
"avg_line_length": 44.05194805194805,
"alnum_prop": 0.6571344339622641,
"repo_name": "cosmosgenius/brackets",
"id": "6f8e516c7877e6eb0c98496d959a3a8601c9ce47",
"size": "3392",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "test/SpecRunner.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1623591"
},
{
"name": "Clojure",
"bytes": "28"
},
{
"name": "JavaScript",
"bytes": "10020946"
},
{
"name": "PHP",
"bytes": "28796"
},
{
"name": "Ruby",
"bytes": "9030"
},
{
"name": "Shell",
"bytes": "8449"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Bootstrap Template</title>
<link href="../css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<form class="form-horizontal" role="form">
<div class="form-group">
<label for="firstname" class="col-sm-2 control-label">名字</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="firstname" placeholder="请输入名字">
</div>
</div>
<div class="form-group">
<label for="lastname" class="col-sm-2 control-label">姓</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="lastname" placeholder="请输入姓">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<div class="checkbox">
<label>
<input type="checkbox"> 请记住我
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">登录</button>
</div>
</div>
</form>
<script src="../js/jquery.min.js"></script>
<script src="../js/bootstrap.min.js"></script>
</body>
</html> | {
"content_hash": "6206f5b656fc82eb1b26f80f6005b026",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 117,
"avg_line_length": 33.770833333333336,
"alnum_prop": 0.5249845774213449,
"repo_name": "ijlhjj/webclient",
"id": "cc0066e34ed9ce9dda0bbcd835e269e11ec5327d",
"size": "1657",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "Bootstrap/Bootstrap3/表单/水平表单.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "373403"
},
{
"name": "HTML",
"bytes": "1445666"
},
{
"name": "JavaScript",
"bytes": "912923"
}
],
"symlink_target": ""
} |
from functools import partial
import time
import os
import tensorflow.compat.v2 as tf
tf.enable_v2_behavior()
import bit_common
import bit_hyperrule
import bit_tf2.models as models
import input_pipeline_tf2_or_jax as input_pipeline
def reshape_for_keras(features, batch_size, crop_size):
features["image"] = tf.reshape(features["image"], (batch_size, crop_size, crop_size, 3))
features["label"] = tf.reshape(features["label"], (batch_size, -1))
return (features["image"], features["label"])
class BiTLRSched(tf.keras.callbacks.Callback):
def __init__(self, base_lr, num_samples):
self.step = 0
self.base_lr = base_lr
self.num_samples = num_samples
def on_train_batch_begin(self, batch, logs=None):
lr = bit_hyperrule.get_lr(self.step, self.num_samples, self.base_lr)
tf.keras.backend.set_value(self.model.optimizer.lr, lr)
self.step += 1
def main(args):
tf.io.gfile.makedirs(args.logdir)
logger = bit_common.setup_logger(args)
logger.info(f'Available devices: {tf.config.list_physical_devices()}')
tf.io.gfile.makedirs(args.bit_pretrained_dir)
bit_model_file = os.path.join(args.bit_pretrained_dir, f'{args.model}.h5')
if not tf.io.gfile.exists(bit_model_file):
model_url = models.KNOWN_MODELS[args.model]
logger.info(f'Downloading the model from {model_url}...')
tf.io.gfile.copy(model_url, bit_model_file)
# Set up input pipeline
dataset_info = input_pipeline.get_dataset_info(
args.dataset, 'train', args.examples_per_class)
# Distribute training
strategy = tf.distribute.MirroredStrategy()
num_devices = strategy.num_replicas_in_sync
print('Number of devices: {}'.format(num_devices))
resize_size, crop_size = bit_hyperrule.get_resolution_from_dataset(args.dataset)
data_train = input_pipeline.get_data(
dataset=args.dataset, mode='train',
repeats=None, batch_size=args.batch,
resize_size=resize_size, crop_size=crop_size,
examples_per_class=args.examples_per_class,
examples_per_class_seed=args.examples_per_class_seed,
mixup_alpha=bit_hyperrule.get_mixup(dataset_info['num_examples']),
num_devices=num_devices,
tfds_manual_dir=args.tfds_manual_dir)
data_test = input_pipeline.get_data(
dataset=args.dataset, mode='test',
repeats=1, batch_size=args.batch,
resize_size=resize_size, crop_size=crop_size,
examples_per_class=1, examples_per_class_seed=0,
mixup_alpha=None,
num_devices=num_devices,
tfds_manual_dir=args.tfds_manual_dir)
data_train = data_train.map(lambda x: reshape_for_keras(
x, batch_size=args.batch, crop_size=crop_size))
data_test = data_test.map(lambda x: reshape_for_keras(
x, batch_size=args.batch, crop_size=crop_size))
with strategy.scope():
filters_factor = int(args.model[-1])*4
model = models.ResnetV2(
num_units=models.NUM_UNITS[args.model],
num_outputs=21843,
filters_factor=filters_factor,
name="resnet",
trainable=True,
dtype=tf.float32)
model.build((None, None, None, 3))
logger.info(f'Loading weights...')
model.load_weights(bit_model_file)
logger.info(f'Weights loaded into model!')
model._head = tf.keras.layers.Dense(
units=dataset_info['num_classes'],
use_bias=True,
kernel_initializer="zeros",
trainable=True,
name="head/dense")
lr_supports = bit_hyperrule.get_schedule(dataset_info['num_examples'])
schedule_length = lr_supports[-1]
# NOTE: Let's not do that unless verified necessary and we do the same
# across all three codebases.
# schedule_length = schedule_length * 512 / args.batch
optimizer = tf.keras.optimizers.SGD(momentum=0.9)
loss_fn = tf.keras.losses.CategoricalCrossentropy(from_logits=True)
model.compile(optimizer=optimizer, loss=loss_fn, metrics=['accuracy'])
logger.info(f'Fine-tuning the model...')
steps_per_epoch = args.eval_every or schedule_length
history = model.fit(
data_train,
steps_per_epoch=steps_per_epoch,
epochs=schedule_length // steps_per_epoch,
validation_data=data_test, # here we are only using
# this data to evaluate our performance
callbacks=[BiTLRSched(args.base_lr, dataset_info['num_examples'])],
)
for epoch, accu in enumerate(history.history['val_accuracy']):
logger.info(
f'Step: {epoch * args.eval_every}, '
f'Test accuracy: {accu:0.3f}')
if __name__ == "__main__":
parser = bit_common.argparser(models.KNOWN_MODELS.keys())
parser.add_argument("--tfds_manual_dir", default=None,
help="Path to maually downloaded dataset.")
parser.add_argument("--batch_eval", default=32, type=int,
help="Eval batch size.")
main(parser.parse_args())
| {
"content_hash": "15d26e15e05c54b9ad8948c9bb5f1c3c",
"timestamp": "",
"source": "github",
"line_count": 136,
"max_line_length": 90,
"avg_line_length": 35.330882352941174,
"alnum_prop": 0.6795005202913632,
"repo_name": "google-research/big_transfer",
"id": "5292887839d96f884e66a35882199fa15baff319",
"size": "5417",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bit_tf2/train.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "70283"
}
],
"symlink_target": ""
} |

Logs will show up immediately after you run the code. You can also access historical logs by clicking on the Logs button at the top right corner on the Code page for a service.
| {
"content_hash": "965b13430ac41fed24184bd9ce05fb60",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 176,
"avg_line_length": 37,
"alnum_prop": 0.7612612612612613,
"repo_name": "njosefbeck/clay-docs",
"id": "3102a8494f4cf1504d9e9bcd2a9ea5a4a2e04120",
"size": "261",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "walkthrough/logging-and-debugging-service-code.md",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
package org.apache.bookkeeper.metadata.etcd;
import com.coreos.jetcd.data.ByteSequence;
import com.coreos.jetcd.options.WatchOption;
import com.coreos.jetcd.watch.WatchResponse;
import com.coreos.jetcd.watch.WatchResponseWithError;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.BiConsumer;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.bookkeeper.common.concurrent.FutureUtils;
/**
* Watcher class holds watcher information.
*/
@Slf4j
public class EtcdWatcher implements AutoCloseable {
private final ScheduledExecutorService executor;
@Getter
private final WatchOption watchOption;
@Getter
private final ByteSequence key;
// watch listener
private final CopyOnWriteArraySet<BiConsumer<WatchResponse, Throwable>> consumers;
@Getter
@Setter
private long watchID;
// the revision to watch on.
@Getter
@Setter
private long revision;
private boolean closed = false;
// the client owns this watcher
private final EtcdWatchClient owner;
EtcdWatcher(ByteSequence key,
WatchOption watchOption,
ScheduledExecutorService executor,
EtcdWatchClient owner) {
this.key = key;
this.watchOption = watchOption;
this.executor = executor;
this.owner = owner;
this.consumers = new CopyOnWriteArraySet<>();
}
public void addConsumer(BiConsumer<WatchResponse, Throwable> consumer) {
this.consumers.add(consumer);
}
synchronized boolean isClosed() {
return closed;
}
void notifyWatchResponse(WatchResponseWithError watchResponse) {
synchronized (this) {
if (closed) {
return;
}
}
this.executor.submit(() -> consumers.forEach(c -> {
if (watchResponse.getException() != null) {
c.accept(null, watchResponse.getException());
} else {
c.accept(
new WatchResponse(watchResponse.getWatchResponse()),
null);
}
}));
}
public CompletableFuture<Void> closeAsync() {
return owner.unwatch(this);
}
@Override
public void close() {
synchronized (this) {
if (closed) {
return;
}
closed = true;
}
try {
FutureUtils.result(closeAsync());
} catch (Exception e) {
log.warn("Encountered error on removing watcher '{}' from watch client : {}",
watchID, e.getMessage());
}
consumers.clear();
}
}
| {
"content_hash": "4375368772744d02cb885a52a763f2f6",
"timestamp": "",
"source": "github",
"line_count": 99,
"max_line_length": 89,
"avg_line_length": 28.252525252525253,
"alnum_prop": 0.628888094386843,
"repo_name": "sijie/bookkeeper",
"id": "ad3b6a38907a81e2c41be17f67921c3e4e884938",
"size": "3602",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "metadata-drivers/etcd/src/main/java/org/apache/bookkeeper/metadata/etcd/EtcdWatcher.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "4163"
},
{
"name": "C++",
"bytes": "17844"
},
{
"name": "CSS",
"bytes": "6348"
},
{
"name": "Dockerfile",
"bytes": "12599"
},
{
"name": "Groovy",
"bytes": "111690"
},
{
"name": "HTML",
"bytes": "16892"
},
{
"name": "Java",
"bytes": "13173512"
},
{
"name": "JavaScript",
"bytes": "914"
},
{
"name": "Makefile",
"bytes": "7304"
},
{
"name": "Python",
"bytes": "241177"
},
{
"name": "Roff",
"bytes": "39396"
},
{
"name": "Ruby",
"bytes": "6445"
},
{
"name": "Shell",
"bytes": "172995"
},
{
"name": "Thrift",
"bytes": "1473"
}
],
"symlink_target": ""
} |
jQuery( document ).ready( function() {
// Choose a customer in Order administration panel
jQuery( document ).on( 'change', '#user_customer_id', function() {
jQuery( '#wps_orders_selected_customer' ).val( jQuery( '#user_customer_id' ).chosen().val() );
refresh_customer_informations_admin();
});
// Create a new customer in administration
jQuery( document ).on( 'click', '#wps_signup_button', function() {
jQuery('#wps_signup_form').ajaxForm({
dataType: 'json',
beforeSubmit : function() {
jQuery( '#wps_signup_button' ).addClass( 'wps-bton-loading' );
},
success: function( response ) {
if( response[0] ) {
jQuery( '#TB_closeWindowButton').click();
jQuery( '#wps_signup_button' ).removeClass( 'wps-bton-loading' );
jQuery( '#wps_orders_selected_customer').val( response[2] );
// Refresh User list
jQuery( '#wps_customer_list_container').animate( {'opacity' : 0.15}, 350 );
var data = {
action: "wps_order_refresh_customer_list",
customer_id : response[2],
};
jQuery.post(ajaxurl, data, function( return_data ){
if ( return_data['status'] ) {
jQuery( '#wps_customer_list_container').html( return_data['response'] );
jQuery( '#wps_customer_list_container').animate( {'opacity' : 1}, 350, function() {
jQuery('#user_customer_id').chosen();
});
}
else {
alert( 'An error was occured...' );
jQuery( '#wps_customer_list_container').animate( {'opacity' : 1}, 350 );
}
}, 'json');
// Refresh address & account datas
refresh_customer_informations_admin();
}
else {
jQuery( '#wps_signup_error_container' ).html( response[1] );
jQuery( '#wps_signup_button' ).removeClass( 'wps-bton-loading' );
}
},
}).submit();
});
update_selected_address_ids();
/** Update Selected addresses ids **/
function update_selected_address_ids() {
if( jQuery( '.wps_select_address').length == 0 ) {
jQuery( '#wps_order_selected_address_billing').val( '' );
jQuery( '#wps_order_selected_address_shipping').val( '' );
}
jQuery( '.wps_select_address').each( function() {
if( jQuery( this ).is( ':checked') ) {
// Update data
var type = jQuery( this ).attr( 'name' ).replace( '_address_id', '' );
jQuery( '#wps_order_selected_address_' + type ).val( jQuery( this ) .val() );
}
});
}
/**
* Refresh Customer inforations in order back-office panel
*/
function refresh_customer_informations_admin() {
jQuery( '#wps_customer_account_informations' ).animate( {'opacity' : 0.15}, 350 );
jQuery( '#wps_customer_addresses' ).animate( {'opacity' : 0.15}, 350 );
var data = {
action: "wps_order_refresh_customer_informations",
customer_id : jQuery( '#wps_orders_selected_customer' ).val(),
order_id : jQuery( '#post_ID').val()
};
jQuery.post(ajaxurl, data, function( response ){
if ( response['status'] ) {
jQuery( '#wps_customer_account_informations' ).html( response['account'] );
jQuery('#wps_customer_account_informations').animate( {'opacity' : 1}, 350 );
jQuery( '#wps_customer_addresses' ).html( response['addresses'] );
jQuery( '#wps_customer_addresses' ).animate( {'opacity' : 1}, 350, function() {
update_selected_address_ids();
});
}
else {
alert( 'An error was occured...' );
jQuery( '#wps_selected_customer_informations' ).animate( {'opacity' : 1}, 350 );
}
}, 'json');
}
}); | {
"content_hash": "2dc11cef7358e9bbc15a10fa9b9282da",
"timestamp": "",
"source": "github",
"line_count": 98,
"max_line_length": 97,
"avg_line_length": 38.714285714285715,
"alnum_prop": 0.5561412756984713,
"repo_name": "fedeB-IT-dept/fedeB_website",
"id": "262f00718315e32a35b377a1c2de22e2b8dbca88",
"size": "3794",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "wp-content/plugins/wpshop/includes/modules/wps_customer/assets/backend/js/wps_customer_backend.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2966482"
},
{
"name": "HTML",
"bytes": "155001"
},
{
"name": "JavaScript",
"bytes": "3073802"
},
{
"name": "Modelica",
"bytes": "7982"
},
{
"name": "PHP",
"bytes": "29887346"
}
],
"symlink_target": ""
} |
"""
pyexcel.plugin.parsers.django
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Export data into database datables
:copyright: (c) 2015-2017 by Onni Software Ltd.
:license: New BSD License
"""
import pyexcel_io.database.common as django
from pyexcel_io import get_data, iget_data
from pyexcel.parser import DbParser
class DjangoExporter(DbParser):
"""Export data from django model"""
def parse_db(self, argument,
export_columns_list=None, on_demand=True,
**keywords):
models = argument
exporter = django.DjangoModelExporter()
if export_columns_list is None:
export_columns_list = [None] * len(models)
for model, export_columns in zip(models, export_columns_list):
adapter = django.DjangoModelExportAdapter(model, export_columns)
exporter.append(adapter)
if on_demand:
sheets, _ = iget_data(
exporter, file_type=self._file_type, **keywords)
else:
sheets = get_data(exporter, file_type=self._file_type, **keywords)
return sheets
| {
"content_hash": "953dc617215e625c8b0d67f4924b2785",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 78,
"avg_line_length": 33.878787878787875,
"alnum_prop": 0.6082289803220036,
"repo_name": "caspartse/QQ-Groups-Spider",
"id": "a2bf1b155a32c1d3375b9134de4f54a683270cfa",
"size": "1118",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vendor/pyexcel/plugins/parsers/django.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "157970"
},
{
"name": "Python",
"bytes": "10416"
},
{
"name": "Smarty",
"bytes": "9490"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<script>
window.onload = function() { document.getElementById("two").animate([ { baselineShift: "sub" }, { baselineShift: "super" } ], { duration: 4000, delay: 2000 }); };
window.onload = function() { document.getElementById("three").animate([ { baselineShift: "sub" }, { baselineShift: "super" } ], { duration: 4000, delay: 2000 }); };
window.onload = function() { document.getElementById("three").animate([ { stroke: "red" }, { stroke: "blue" } ], { duration: 4000, delay: 2000 }); };
</script>
</head>
<body>
<svg height="120" width="200">
<text font-family="Verdana" font-size="12" x="60" y="60">
<tspan baseline-shift="baseline">
one
</tspan>
<!-- See crbug.com/620618 - the animation of three but not two is visible. -->
<tspan baseline-shift="baseline" id="two">
two
</tspan>
<tspan baseline-shift="baseline" id="three">
three
</tspan>
<tspan baseline-shift="baseline">
four
</tspan>
</text>
</svg>
</body>
</html> | {
"content_hash": "dc2e5271ac4aa9a8143588c411b4978b",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 165,
"avg_line_length": 35.44827586206897,
"alnum_prop": 0.6089494163424124,
"repo_name": "translate-smil/translate-smil",
"id": "dafa516463abf6ea9214eba3ded29291026f6167",
"size": "1028",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gallery/wa/236-baseline-shift.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "122944"
},
{
"name": "Python",
"bytes": "18304"
},
{
"name": "Shell",
"bytes": "222"
}
],
"symlink_target": ""
} |
using rtps.messages.elements;
using System.Collections.Generic;
namespace rtps.messages.submessage.interpreter
{
/// <summary>
/// This message is sent from an RTPS Reader to an RTPS Writer. It contains
/// explicit information on where to send a reply to the Submessages that follow
/// it within the same message.
///
/// see 9.4.5.9 InfoReply Submessage, 8.3.7.8 InfoReply
/// From OMG RTPS Standard v2.1 p44: Provides information about where to reply to the
/// entities that appear in subsequent Submessages
///
/// From OMG RTPS Standard v2.1 p57: This message is sent from an RTPS Reader to an
/// RTPS Writer. It contains explicit information on where to send a reply to the
/// Submessages that follow it within the same message.
/// </summary>
public class InfoReply : SubMessage
{
private IList<Locator> unicastLocatorList;
private IList<Locator> multicastLocatorList;
public InfoReply()
: this(new List<Locator>(), new List<Locator>())
{
}
public InfoReply(IList<Locator> unicastLocators, IList<Locator> multicastLocators)
: base(SubMessageKind.INFO_REPLY)
{
this.unicastLocatorList = unicastLocators;
this.multicastLocatorList = multicastLocators;
if (multicastLocatorList != null && multicastLocatorList.Count > 0)
{
Header.Flags.SetMulticastFlag();
}
}
/// <summary>
/// Returns the MulticastFlag. If true, message contains MulticastLocatorList
/// true, if message contains multicast locator
/// </summary>
public bool HasMulticastFlag
{
get
{
return Header.Flags.HasMulticastFlag;
}
}
/// <summary>
/// Indicates an alternative set of unicast addresses that the Writer should
/// use to reach the Readers when replying to the Submessages that follow.
/// </summary>
public IList<Locator> UnicastLocatorList
{
get
{
return unicastLocatorList;
}
}
/// <summary>
/// Indicates an alternative set of multicast addresses that the Writer
/// should use to reach the Readers when replying to the Submessages that
/// follow. Only present when the MulticastFlag is set.
/// </summary>
public IList<Locator> MulticastLocatorList
{
get
{
return multicastLocatorList;
}
}
public override string ToString()
{
return base.ToString() + ", " + unicastLocatorList + ", " + multicastLocatorList;
}
}
}
| {
"content_hash": "754629d7d7d5726f6e32e72cfec7bb5e",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 93,
"avg_line_length": 33.9277108433735,
"alnum_prop": 0.59375,
"repo_name": "agustinsantos/DOOP.ec",
"id": "c7f1bdc77d17e17f01d21326ff1830b6e2deb1ac",
"size": "2817",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "DDS-RTPS/RTPS/oldMessages/submessage/interpreter/InfoReply.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "14433"
},
{
"name": "C#",
"bytes": "2442512"
},
{
"name": "CSS",
"bytes": "6560"
},
{
"name": "HTML",
"bytes": "224267"
},
{
"name": "Shell",
"bytes": "1019"
}
],
"symlink_target": ""
} |
package com.intellij.util.xml;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotates 'primary key' methods. Elements whose primary key methods return the same
* will be merged together in collection getters of elements merged with {@link ModelMerger}
*
* @author peter
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface PrimaryKey {
}
| {
"content_hash": "b5e59eb6bf256fc37468717f0c071be8",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 92,
"avg_line_length": 27.88888888888889,
"alnum_prop": 0.7868525896414342,
"repo_name": "google/intellij-community",
"id": "71c4508544e216c064b854afbfa71e304eec6736",
"size": "1102",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "xml/dom-openapi/src/com/intellij/util/xml/PrimaryKey.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Threading;
using ZyGames.Framework.Cache.Generic;
using ZyGames.Framework.Common.Log;
using ZyGames.Framework.Common.Serialization;
using ZyGames.Framework.Game.Cache;
using ZyGames.Framework.Collection;
using ZyGames.Framework.Game.Model;
using ZyGames.Tianjiexing.Component.Chat;
using ZyGames.Tianjiexing.Model;
using System.Diagnostics;
using ZyGames.Tianjiexing.Model.Config;
using ZyGames.Framework.Common;
namespace ZyGames.Tianjiexing.BLL.Combat
{
/// <summary>
/// 游戏活动中心
/// </summary>
public class GameActiveCenter
{
private static Timer _timer;
private static int sleepTime = 15;//秒
private static List<GameActive> _gameActiveList;
private string _userId;
static GameActiveCenter()
{
_timer = new Timer(InitActive, null, 6000, sleepTime * 1000);
// _gameActiveList = new ShareCacheStruct<GameActive>().FindAll(m => m.State && m.ActiveStyle != 4);
_gameActiveList = new ShareCacheStruct<GameActive>().FindAll(m => m.State);
_gameActiveList.QuickSort((x, y) =>
{
if (x == null && y == null) return 0;
if (x != null && y == null) return 1;
if (x == null) return -1;
return x.ActiveId.CompareTo(y.ActiveId);
});
}
public static void Stop()
{
_timer.Dispose();
}
/// <summary>
/// 刷新活动
/// </summary>
public static void InitActive(object sender)
{
try
{
ThreadPool.QueueUserWorkItem(RefreshActive);
}
catch (Exception ex)
{
new BaseLog().SaveLog("刷新活动线程出现问题", ex);
}
}
public GameActiveCenter(string userId)
{
_userId = userId;
}
/// <summary>
/// 是否有活动
/// </summary>
/// <returns></returns>
public bool HasActive()
{
GameActive[] activeList = GetActiveList();
foreach (var gameActive in activeList)
{
var status = gameActive.RefreshStatus();
if (status == CombatStatus.Wait || status == CombatStatus.Combat)
{
return true;
}
}
return false;
}
/// <summary>
/// 获取活动列表
/// </summary>
/// <returns></returns>
public GameActive[] GetActiveList()
{
List<GameActive> activeList = new List<GameActive>();
foreach (var gameActive in _gameActiveList)
{
UserFunction function = new GameDataCacheSet<UserFunction>().FindKey(_userId, gameActive.ActiveType);
if (function == null) continue;
if (function.FunEnum != FunctionEnum.Gonghui)
{
LoadData(gameActive);
activeList.Add(gameActive);
}
else if (function.FunEnum == FunctionEnum.Gonghui)
{
GameUser userInfo = new GameDataCacheSet<GameUser>().FindKey(_userId);
if (userInfo != null)
{
UserGuild guild = new ShareCacheStruct<UserGuild>().FindKey(userInfo.MercenariesID);
if (guild != null)
{
GuildLvInfo lvInfo = new ConfigCacheSet<GuildLvInfo>().FindKey(guild.GuildLv);
if (lvInfo != null)
{
var activityArray = lvInfo.ActivityDesc;
foreach (ActivityShow activityShow in activityArray)
{
if (activityShow.ActivityID == (int)gameActive.ActiveStyle)
{
activeList.Add(gameActive);
}
}
}
}
}
}
}
return activeList.ToArray();
}
public GameActive[] GetActiveList(FunctionEnum activeType)
{
List<GameActive> activeList = new List<GameActive>();
foreach (var gameActive in _gameActiveList)
{
if (gameActive.ActiveType != FunctionEnum.Gonghui && (gameActive.ActiveType != activeType ||
new GameDataCacheSet<UserFunction>().FindKey(_userId, gameActive.ActiveType) == null)) continue;
activeList.Add(gameActive);
if (activeType == FunctionEnum.Gonghui)
{
if (gameActive.ActiveType == FunctionEnum.Gonghui)
{
GameUser userInfo = new GameDataCacheSet<GameUser>().FindKey(_userId);
if (userInfo != null)
{
UserGuild guild = new ShareCacheStruct<UserGuild>().FindKey(userInfo.MercenariesID);
if (guild != null)
{
GuildLvInfo lvInfo = new ConfigCacheSet<GuildLvInfo>().FindKey(guild.GuildLv);
if (lvInfo != null)
{
var activityArray = lvInfo.ActivityDesc;
foreach (ActivityShow activityShow in activityArray)
{
if (activityShow.ActivityID == (int)gameActive.ActiveStyle)
{
activeList.Add(gameActive);
}
}
}
}
}
}
}
};
return activeList.ToArray();
}
/// <summary>
/// 刷新活动
/// </summary>
private static void RefreshActive(object sender)
{
try
{
Trace.WriteLine("刷新活动被执行");
foreach (var gameActive in _gameActiveList)
{
string[] list = gameActive.EnablePeriod.Split(new char[] { ',' });
//有多个时间段
foreach (string item in list)
{
gameActive.BeginTime = item.ToDateTime(DateTime.MinValue);
gameActive.EndTime = gameActive.BeginTime.AddMinutes(gameActive.Minutes);
if (gameActive.BossPrize == null && gameActive.ActiveType == FunctionEnum.Booszhang)
gameActive.BossPrize = JsonUtils.Deserialize<BossActivePrize>(gameActive.ActivePize);
DateTime currTime = DateTime.Now;
if (gameActive.CombatStatus != CombatStatus.Killed &&
gameActive.WaitMinutes > 0 && currTime >= gameActive.BeginTime
&& currTime <= gameActive.BeginTime.AddMinutes(gameActive.WaitMinutes))
{
LoadData(gameActive);
gameActive.CombatStatus = CombatStatus.Wait;
}
else if (gameActive.CombatStatus != CombatStatus.Killed &&
currTime >= gameActive.BeginTime && currTime <= gameActive.EndTime)
{
LoadData(gameActive);
gameActive.CombatStatus = CombatStatus.Combat;
}
else if (currTime < gameActive.BeginTime)
{
gameActive.CombatStatus = CombatStatus.NoStart;
}
else if (currTime > gameActive.EndTime)
{
gameActive.CombatStatus = CombatStatus.Over;
}
CombatStatus combatStatus = gameActive.RefreshStatus();
if (combatStatus == CombatStatus.Wait)
{
//有等待时间
int minute = gameActive.WaitMinutes;
if (combatStatus != CombatStatus.Killed &&
currTime >= gameActive.BeginTime.AddMinutes(minute) && currTime <= gameActive.EndTime)
{
ServerEnvSet.Set(ServerEnvKey.KillBossUserID, 0);
gameActive.CombatStatus = CombatStatus.Combat;
}
break;
}
else if (combatStatus == CombatStatus.Combat)
{
break;
}
else if (combatStatus == CombatStatus.Over)
{
DisposeData(gameActive);
}
}
}
}
catch (Exception ex)
{
new BaseLog().SaveLog(ex);
}
}
private static void LoadData(GameActive gameActive)
{
if ((gameActive.CombatStatus == CombatStatus.Wait || gameActive.CombatStatus == CombatStatus.Combat) && !gameActive.LoadSuccess)
{
if (!string.IsNullOrEmpty(gameActive.Broadcast))
{
var broadcastService = new TjxBroadcastService(null);
var msg = broadcastService.Create(NoticeType.Game, gameActive.Broadcast);
if (gameActive.ActiveId == 11)
{
int invertal = (int)new TimeSpan(0, 0, gameActive.WaitMinutes, 0).TotalSeconds / 5;
string startTime = DateTime.Now.ToString("HH:mm:ss");
string endTime = DateTime.Now.AddMinutes(gameActive.WaitMinutes).ToString("HH:mm:ss");
broadcastService.SendTimer(msg, startTime, endTime, true, invertal);//秒
}
else
{
broadcastService.Send(msg);
}
}
gameActive.LoadSuccess = true;
if (gameActive.ActiveType == FunctionEnum.Booszhang)
{
BossCombat.InitBoss(gameActive);
}
else if (gameActive.ActiveType == FunctionEnum.Lintuzhang)
{
CountryCombat.Init(gameActive);
}
else if (gameActive.ActiveType == FunctionEnum.Multiplot)
{
PlotTeamCombat.Init(gameActive);
}
else if (gameActive.ActiveType == FunctionEnum.MorePlotCoin)
{
PlotTeamCombat.Init(gameActive);
}
else if (gameActive.ActiveType == FunctionEnum.MorePlotEnergy)
{
PlotTeamCombat.Init(gameActive);
}
}
}
private static void DisposeData(GameActive gameActive)
{
if (gameActive.LoadSuccess)
{
gameActive.LoadSuccess = false;
if (gameActive.ActiveType == FunctionEnum.Booszhang)
{
BossCombat.Dispose(gameActive);
}
else if (gameActive.ActiveType == FunctionEnum.Lintuzhang)
{
CountryCombat.Dispose(gameActive);
}
else if (gameActive.ActiveType == FunctionEnum.Multiplot)
{
PlotTeamCombat.Dispose(gameActive);
}
else if (gameActive.ActiveType == FunctionEnum.MorePlotCoin)
{
PlotTeamCombat.Dispose(gameActive);
}
else if (gameActive.ActiveType == FunctionEnum.MorePlotEnergy)
{
PlotTeamCombat.Dispose(gameActive);
}
}
}
}
} | {
"content_hash": "53d086cd6db4569cb24a7da033d7c44e",
"timestamp": "",
"source": "github",
"line_count": 316,
"max_line_length": 140,
"avg_line_length": 40.927215189873415,
"alnum_prop": 0.4437485502203665,
"repo_name": "wenhulove333/ScutServer",
"id": "f1da36478436d5bdf068ff4048f0c4523330bc34",
"size": "14308",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Sample/Koudai/Server/src/ZyGames.Tianjiexing.BLL.Combat/GameActiveCenter.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "150472"
},
{
"name": "ActionScript",
"bytes": "339184"
},
{
"name": "Batchfile",
"bytes": "60466"
},
{
"name": "C",
"bytes": "3976261"
},
{
"name": "C#",
"bytes": "9481083"
},
{
"name": "C++",
"bytes": "11640198"
},
{
"name": "CMake",
"bytes": "489"
},
{
"name": "CSS",
"bytes": "13478"
},
{
"name": "Groff",
"bytes": "16179"
},
{
"name": "HTML",
"bytes": "283997"
},
{
"name": "Inno Setup",
"bytes": "28931"
},
{
"name": "Java",
"bytes": "214263"
},
{
"name": "JavaScript",
"bytes": "2809"
},
{
"name": "Lua",
"bytes": "4667522"
},
{
"name": "Makefile",
"bytes": "166623"
},
{
"name": "Objective-C",
"bytes": "401654"
},
{
"name": "Objective-C++",
"bytes": "355347"
},
{
"name": "Python",
"bytes": "1633926"
},
{
"name": "Shell",
"bytes": "101770"
},
{
"name": "Visual Basic",
"bytes": "18764"
}
],
"symlink_target": ""
} |
<!--
Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
--><!--
`paper-tabs` is a `core-selector` styled to look like tabs. Tabs make it easy to
explore and switch between different views or functional aspects of an app, or
to browse categorized data sets.
Use `selected` property to get or set the selected tab.
Example:
<paper-tabs selected="0">
<paper-tab>TAB 1</paper-tab>
<paper-tab>TAB 2</paper-tab>
<paper-tab>TAB 3</paper-tab>
</paper-tabs>
See <a href="#paper-tab">paper-tab</a> for more information about
`paper-tab`.
A common usage for `paper-tabs` is to use it along with `core-pages` to switch
between different views.
<paper-tabs selected="{{selected}}">
<paper-tab>Tab 1</paper-tab>
<paper-tab>Tab 2</paper-tab>
<paper-tab>Tab 3</paper-tab>
</paper-tabs>
<core-pages selected="{{selected}}">
<div>Page 1</div>
<div>Page 2</div>
<div>Page 3</div>
</core-pages>
`paper-tabs` adapt to mobile/narrow layout when there is a `core-narrow` class set
on itself or any of its ancestors.
To use links in tabs, add `link` attribute to `paper-tabs` and put an `<a>`
element in `paper-tab`.
Example:
<paper-tabs selected="0" link>
<paper-tab>
<a href="#link1" horizontal center-center layout>TAB ONE</a>
</paper-tab>
<paper-tab>
<a href="#link2" horizontal center-center layout>TAB TWO</a>
</paper-tab>
<paper-tab>
<a href="#link3" horizontal center-center layout>TAB THREE</a>
</paper-tab>
</paper-tabs>
Styling tabs:
To change the sliding bar color:
paper-tabs.pink::shadow #selectionBar {
background-color: #ff4081;
}
To change the ink ripple color:
paper-tabs.pink paper-tab::shadow #ink {
color: #ff4081;
}
@group Paper Elements
@element paper-tabs
@extends core-selector
@homepage github.io
--><html><head><link rel="import" href="../core-selector/core-selector.html">
<link rel="import" href="../paper-icon-button/paper-icon-button.html">
<link rel="import" href="../core-resizable/core-resizable.html">
<link rel="import" href="paper-tab.html">
</head><body><polymer-element name="paper-tabs" extends="core-selector" attributes="noink nobar noslide scrollable hideScrollButton" role="tablist" horizontal="" center="" layout="" assetpath="">
<template>
<link rel="stylesheet" href="paper-tabs.css">
<div class="scroll-button" hidden?="{{!scrollable || hideScrollButton}}">
<paper-icon-button icon="chevron-left" class="{{ {hidden: leftHidden} | tokenList }}" on-down="{{holdLeft}}" on-up="{{releaseHold}}"></paper-icon-button>
</div>
<div id="tabsContainer" class="{{ {scrollable: scrollable} | tokenList }}" flex="" on-scroll="{{scroll}}" on-trackstart="{{trackStart}}">
<div id="tabsContent" horizontal="" layout?="{{!scrollable}}">
<shadow></shadow>
<div id="selectionBar" hidden?="{{nobar}}" on-transitionend="{{barTransitionEnd}}"></div>
</div>
</div>
<div class="scroll-button" hidden?="{{!scrollable || hideScrollButton}}">
<paper-icon-button icon="chevron-right" class="{{ {hidden: rightHidden} | tokenList }}" on-down="{{holdRight}}" on-up="{{releaseHold}}"></paper-icon-button>
</div>
</template>
</polymer-element>
<script src="paper-tabs-extracted.js"></script></body></html> | {
"content_hash": "928955058ad4f4a32aa1b8ab07deda47",
"timestamp": "",
"source": "github",
"line_count": 109,
"max_line_length": 195,
"avg_line_length": 34.96330275229358,
"alnum_prop": 0.6717397008659145,
"repo_name": "dednal/chromium.src",
"id": "81a71a828277924824a56f805b5c9a3afc506870",
"size": "3811",
"binary": false,
"copies": "9",
"ref": "refs/heads/nw12",
"path": "third_party/polymer/components-chromium/paper-tabs/paper-tabs.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "AppleScript",
"bytes": "6973"
},
{
"name": "Arduino",
"bytes": "464"
},
{
"name": "Assembly",
"bytes": "34522"
},
{
"name": "Batchfile",
"bytes": "8451"
},
{
"name": "C",
"bytes": "9240962"
},
{
"name": "C++",
"bytes": "222772775"
},
{
"name": "CSS",
"bytes": "875874"
},
{
"name": "Dart",
"bytes": "74976"
},
{
"name": "Go",
"bytes": "18155"
},
{
"name": "HTML",
"bytes": "27190037"
},
{
"name": "Java",
"bytes": "7645280"
},
{
"name": "JavaScript",
"bytes": "18828195"
},
{
"name": "Makefile",
"bytes": "96270"
},
{
"name": "Objective-C",
"bytes": "1397246"
},
{
"name": "Objective-C++",
"bytes": "7575073"
},
{
"name": "PHP",
"bytes": "97817"
},
{
"name": "PLpgSQL",
"bytes": "248854"
},
{
"name": "Perl",
"bytes": "63937"
},
{
"name": "Protocol Buffer",
"bytes": "418340"
},
{
"name": "Python",
"bytes": "8032766"
},
{
"name": "Shell",
"bytes": "464218"
},
{
"name": "Standard ML",
"bytes": "4965"
},
{
"name": "XSLT",
"bytes": "418"
},
{
"name": "nesC",
"bytes": "18335"
}
],
"symlink_target": ""
} |
package org.sagebionetworks.repo.model.auth;
import java.util.Objects;
import java.util.function.Supplier;
import org.sagebionetworks.repo.model.UnauthorizedException;
/**
* Holds the result of an authorization check.
* If 'authorized' is false then 'message' gives the user-presentable message for denial
*
* @author brucehoff
*
*/
public class AuthorizationStatus {
private static final AuthorizationStatus AUTHORIZED_SINGLETON = new AuthorizationStatus(null);
// if not null, indicates access denied
private final RuntimeException denialException;
//do not expose constuctor. use static methods instead
private AuthorizationStatus(RuntimeException e) {
this.denialException = e;
}
/**
* Create a AuthorizationStatus that indicates the action action is authorized.
* @return AuthorizationStatus that indicates the action action is authorized.
*/
public static AuthorizationStatus authorized(){
return AUTHORIZED_SINGLETON;
}
/**
* Create a AuthorizationStatus that indicates the action action is denied.
* Provide an {@link RuntimeException} that will be thrown when {@link #checkAuthorizationOrElseThrow()} is called
* @param denialException
* @return a new AuthorizationStatus;
*/
public static AuthorizationStatus accessDenied(RuntimeException denialException){
return new AuthorizationStatus(denialException);
}
/**
* Create a AuthorizationStatus that indicates the action action is denied.
* Will use {@link org.sagebionetworks.repo.model.UnauthorizedException} as the underlying denialException that is
* thrown when {@link #checkAuthorizationOrElseThrow()} is called
* @param message message for the {@link org.sagebionetworks.repo.model.UnauthorizedException}
* @return a new AuthorizationStatus;
*/
public static AuthorizationStatus accessDenied(String message){
return accessDenied(new UnauthorizedException(message));
}
public void checkAuthorizationOrElseThrow(){
if(!isAuthorized()){
throw denialException;
}
}
/**
* @param isAuthorizedOrElseSupplier A supplier for a unauthorized message in case this one is not authorized, the message will be used with {@link AuthorizationStatus#accessDenied(String)}
* @return This {@link AuthorizationStatus} if authorized, else an {@link AuthorizationStatus} created with the message from the given supplier
*/
public AuthorizationStatus isAuthorizedOrElseGet(Supplier<String> orElseSupplier) {
return isAuthorized() ? this : AuthorizationStatus.accessDenied(orElseSupplier.get());
}
public boolean isAuthorized() {
return denialException == null;
}
public String getMessage() {
return denialException == null ? null : denialException.getMessage();
}
//The equals() here is not the conventional "check all fields members are equal" because it holds
// a RuntimeException which does not by default @Override equals()
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AuthorizationStatus that = (AuthorizationStatus) o;
return this.isAuthorized() == that.isAuthorized() &&
this.exceptionType() == that.exceptionType() &&
Objects.equals(this.getMessage(), that.getMessage());
}
@Override
public int hashCode() {
return Objects.hash(isAuthorized(), getMessage(), exceptionType());
}
private Class exceptionType (){
if (denialException == null){
return null;
}
return denialException.getClass();
}
@Override
public String toString() {
return "AuthorizationStatus{" +
"denialException=" + denialException +
'}';
}
}
| {
"content_hash": "f7abe33dfcf2f484b335387e23790309",
"timestamp": "",
"source": "github",
"line_count": 109,
"max_line_length": 190,
"avg_line_length": 33.04587155963303,
"alnum_prop": 0.7545807884508606,
"repo_name": "Sage-Bionetworks/Synapse-Repository-Services",
"id": "e28d755a054589a8cbe35910befcc616fc47e716",
"size": "3602",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "lib/models/src/main/java/org/sagebionetworks/repo/model/auth/AuthorizationStatus.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "47960"
},
{
"name": "Java",
"bytes": "21087205"
},
{
"name": "Python",
"bytes": "2379"
},
{
"name": "Rich Text Format",
"bytes": "31728"
},
{
"name": "Roff",
"bytes": "54"
},
{
"name": "Shell",
"bytes": "32205"
},
{
"name": "Velocity Template Language",
"bytes": "3416"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<title>ArtDope - Control Panel</title>
<link rel="icon" href="./images/icon.png" type="image/png" />
<!-- web font-->
<link href='http://fonts.googleapis.com/css?family=Audiowide' rel='stylesheet'
type='text/css'/>
<link href='http://fonts.googleapis.com/css?family=Orbitron' rel='stylesheet'
type='text/css'/>
<link rel="stylesheet" type="text/css" href="../css/base.css"/>
<link rel="stylesheet" type="text/css" href="../css/document.css"/>
<link rel="stylesheet" type="text/css" href="./css/controlpanel.css"/>
<link rel="stylesheet" type="text/css" href="./css/index.css"/>
<script type="text/javascript" src="../js/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="./js/controlpanel.js"></script>
<script type="text/javascript" src="./js/index.js"></script>
<div class="container">
<h1>Control Panel</h1>
<h2>Overview</h2>
<p>controlpanel.js is a library to handle GUIs to set parameters.</p>
<h2>Structure</h2>
<p>Each control is sepalated into a class. The basic structure of the classes
are the same.</p>
<h3>@function appendTo(DOM_Element)</h3>
<p>This is a function to append a container to given HTML DOM Element.</p>
<h3>@function getValue()</h3>
<p>This is a function to get the current value set by user using the
contorl.</p>
<h3>@function setValue(value, isExecuted)</h3>
<p>This is a function to set value by program. We can decide the callback
functions are executed after the value setting.</p>
<h3>@function addCallback(callback)</h3>
<p>This is a function to add a callback to be executed when the value of the
control is changed.</p>
<h3>@function removeCallback(callback)</h3>
<p>This is a function to remove callback which set by addCallback().</p>
<h2>Components</h2>
<h3>Switch</h3>
<table>
<tr><td>type</td><td>boolean</td></tr>
</table>
<p></p>
<div id="switch-container" class="component-container">
</div>
<h3>Radio Button</h3>
<table>
<tr><td>type</td><td>int</td></tr>
</table>
<p></p>
<div id="radio-container" class="component-container">
</div>
<h3>Selector</h3>
<table>
<tr><td>type</td><td>string</td></tr>
</table>
<p></p>
<div id="selector-container" class="component-container">
</div>
<h3>Horizontal Slider</h3>
<table>
<tr><td>type</td><td>float</td></tr>
</table>
<p></p>
<div id="sliderx-container" class="component-container">
</div>
<h3>Vertical Slider</h3>
<table>
<tr><td>type</td><td>float</td></tr>
</table>
<p></p>
<div id="slidery-container" class="component-container">
</div>
<h3>2D Slider</h3>
<table>
<tr><td>type</td><td>object</td></tr>
<tr><td>x</td><td>float</td><tr>
<tr><td>y</td><td>float</td><tr>
</table>
<p></p>
<div id="sliderxy-container" class="component-container">
</div>
</div>
<script type="text/javascript"
src="../js/google_analytics_tracking_code.js"></script>
</html>
| {
"content_hash": "21b9d420cc2d8b2acd1c700defca6410",
"timestamp": "",
"source": "github",
"line_count": 86,
"max_line_length": 79,
"avg_line_length": 34.18604651162791,
"alnum_prop": 0.6561224489795918,
"repo_name": "ku6ryo/artdope",
"id": "ad3fddba74d01a4401294653afda119b4996314c",
"size": "2940",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "controlpanel/index.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
#include "ecma-alloc.h"
#include "ecma-builtins.h"
#include "ecma-conversion.h"
#include "ecma-exceptions.h"
#include "ecma-gc.h"
#include "ecma-globals.h"
#include "ecma-helpers.h"
#include "ecma-objects.h"
#include "ecma-string-object.h"
#include "ecma-try-catch-macro.h"
#include "jrt.h"
#ifndef CONFIG_DISABLE_STRING_BUILTIN
#define ECMA_BUILTINS_INTERNAL
#include "ecma-builtins-internal.h"
#define BUILTIN_INC_HEADER_NAME "ecma-builtin-string.inc.h"
#define BUILTIN_UNDERSCORED_ID string
#include "ecma-builtin-internal-routines-template.inc.h"
/** \addtogroup ecma ECMA
* @{
*
* \addtogroup ecmabuiltins
* @{
*
* \addtogroup string ECMA String object built-in
* @{
*/
/**
* The String object's 'fromCharCode' routine
*
* See also:
* ECMA-262 v5, 15.5.3.2
*
* @return ecma value
* Returned value must be freed with ecma_free_value.
*/
static ecma_value_t
ecma_builtin_string_object_from_char_code (ecma_value_t this_arg, /**< 'this' argument */
const ecma_value_t args[], /**< arguments list */
ecma_length_t args_number) /**< number of arguments */
{
JERRY_UNUSED (this_arg);
if (args_number == 0)
{
return ecma_make_magic_string_value (LIT_MAGIC_STRING__EMPTY);
}
ecma_value_t ret_value = ECMA_VALUE_EMPTY;
ecma_string_t *ret_string_p = NULL;
lit_utf8_size_t utf8_buf_size = args_number * LIT_CESU8_MAX_BYTES_IN_CODE_UNIT;
JMEM_DEFINE_LOCAL_ARRAY (utf8_buf_p,
utf8_buf_size,
lit_utf8_byte_t);
lit_utf8_size_t utf8_buf_used = 0;
for (ecma_length_t arg_index = 0;
arg_index < args_number && ecma_is_value_empty (ret_value);
arg_index++)
{
ECMA_OP_TO_NUMBER_TRY_CATCH (arg_num, args[arg_index], ret_value);
uint32_t uint32_char_code = ecma_number_to_uint32 (arg_num);
ecma_char_t code_unit = (uint16_t) uint32_char_code;
JERRY_ASSERT (utf8_buf_used <= utf8_buf_size - LIT_UTF8_MAX_BYTES_IN_CODE_UNIT);
utf8_buf_used += lit_code_unit_to_utf8 (code_unit, utf8_buf_p + utf8_buf_used);
JERRY_ASSERT (utf8_buf_used <= utf8_buf_size);
ECMA_OP_TO_NUMBER_FINALIZE (arg_num);
}
if (ecma_is_value_empty (ret_value))
{
ret_string_p = ecma_new_ecma_string_from_utf8 (utf8_buf_p, utf8_buf_used);
}
JMEM_FINALIZE_LOCAL_ARRAY (utf8_buf_p);
if (ecma_is_value_empty (ret_value))
{
ret_value = ecma_make_string_value (ret_string_p);
}
return ret_value;
} /* ecma_builtin_string_object_from_char_code */
/**
* Handle calling [[Call]] of built-in String object
*
* @return ecma value
*/
ecma_value_t
ecma_builtin_string_dispatch_call (const ecma_value_t *arguments_list_p, /**< arguments list */
ecma_length_t arguments_list_len) /**< number of arguments */
{
JERRY_ASSERT (arguments_list_len == 0 || arguments_list_p != NULL);
ecma_value_t ret_value = ECMA_VALUE_EMPTY;
if (arguments_list_len == 0)
{
ret_value = ecma_make_magic_string_value (LIT_MAGIC_STRING__EMPTY);
}
else
{
ret_value = ecma_op_to_string (arguments_list_p[0]);
}
return ret_value;
} /* ecma_builtin_string_dispatch_call */
/**
* Handle calling [[Construct]] of built-in String object
*
* @return ecma value
*/
ecma_value_t
ecma_builtin_string_dispatch_construct (const ecma_value_t *arguments_list_p, /**< arguments list */
ecma_length_t arguments_list_len) /**< number of arguments */
{
JERRY_ASSERT (arguments_list_len == 0 || arguments_list_p != NULL);
return ecma_op_create_string_object (arguments_list_p, arguments_list_len);
} /* ecma_builtin_string_dispatch_construct */
/**
* @}
* @}
* @}
*/
#endif /* !CONFIG_DISABLE_STRING_BUILTIN */
| {
"content_hash": "4bcf7d99caa0e774337c231abbf14552",
"timestamp": "",
"source": "github",
"line_count": 141,
"max_line_length": 101,
"avg_line_length": 27.0354609929078,
"alnum_prop": 0.6306400839454355,
"repo_name": "bsdelf/jerryscript",
"id": "af99107020a32a1983b756b59a2726fcb1ee934b",
"size": "4444",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "jerry-core/ecma/builtin-objects/ecma-builtin-string.c",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "6566"
},
{
"name": "Batchfile",
"bytes": "1692"
},
{
"name": "C",
"bytes": "3206895"
},
{
"name": "C++",
"bytes": "275660"
},
{
"name": "CMake",
"bytes": "50629"
},
{
"name": "HTML",
"bytes": "35334"
},
{
"name": "JavaScript",
"bytes": "1649329"
},
{
"name": "Makefile",
"bytes": "17977"
},
{
"name": "Python",
"bytes": "154866"
},
{
"name": "Shell",
"bytes": "65021"
},
{
"name": "Tcl",
"bytes": "45226"
}
],
"symlink_target": ""
} |
package com.zutubi.services.mail.rest.server.spring;
import static org.glassfish.hk2.utilities.BuilderHelper.createConstantDescriptor;
import javax.inject.Inject;
import javax.servlet.ServletContext;
import javax.ws.rs.ext.Provider;
import org.glassfish.hk2.api.DynamicConfiguration;
import org.glassfish.hk2.api.DynamicConfigurationService;
import org.glassfish.hk2.api.ServiceLocator;
import org.glassfish.jersey.server.spi.Container;
import org.glassfish.jersey.server.spi.ContainerLifecycleListener;
import org.glassfish.jersey.servlet.ServletContainer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.access.BeanFactoryReference;
import org.springframework.context.ConfigurableApplicationContext;
import com.zutubi.services.mail.core.lifecycle.ApplicationContextLocator;
/**
* JAX-RS Provider class for bootstrapping Jersey 2 Spring integration.
*
*/
@Provider
public class SpringLifecycleListener implements ContainerLifecycleListener {
/**
* The name of the servlet context init parameter that defines the name of the
* spring context to be retrieved.
*/
public static final String PARENT_CONTEXT_NAME = "parentContextKey";
private static final Logger LOGGER = LoggerFactory.getLogger(SpringLifecycleListener.class);
private ServiceLocator locator;
private BeanFactoryReference parentContextRef;
@Inject
public SpringLifecycleListener(ServiceLocator loc) {
LOGGER.debug("SpringLifecycleListener: " + loc);
locator = loc;
}
@Override
public void onStartup(Container container) {
LOGGER.debug("onStartup: " + container);
if (container instanceof ServletContainer) {
ServletContext servletContext = ((ServletContainer) container).getServletContext();
String factoryName = servletContext.getInitParameter("parentContextKey");
this.parentContextRef = ApplicationContextLocator.getInstance().useBeanFactory(factoryName);
ConfigurableApplicationContext ctx = (ConfigurableApplicationContext) this.parentContextRef.getFactory();
DynamicConfigurationService dcs = locator.getService(DynamicConfigurationService.class);
DynamicConfiguration dynamicConfiguration = dcs.createDynamicConfiguration();
dynamicConfiguration.addActiveDescriptor(createConstantDescriptor(new AutowiredInjectResolver(ctx)));
dynamicConfiguration.commit();
LOGGER.info("jersey-spring initialized");
} else {
LOGGER.info("jersey-spring not initialized");
}
}
@Override
public void onReload(Container container) {
LOGGER.debug("onReload: " + container);
}
@Override
public void onShutdown(Container container) {
LOGGER.debug("onShutdown: " + container);
if (this.parentContextRef != null) {
this.parentContextRef.release();
}
}
} | {
"content_hash": "e5d7b64b84c545b22fe2d857d19a0fe8",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 117,
"avg_line_length": 35.72289156626506,
"alnum_prop": 0.742664418212479,
"repo_name": "dostermeier/mbuddy",
"id": "e00440527bcbf8848814008456ff67a89c09fff1",
"size": "2965",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "mail-rest-server/src/main/java/com/zutubi/services/mail/rest/server/spring/SpringLifecycleListener.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "100589"
}
],
"symlink_target": ""
} |
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { UserService } from '../_services/user.service';
import { User } from '../_models';
import 'rxjs/add/observable/of';
/**
* Protect Admin routes
*
* @export
* @class AdminGuard
* @implements {CanActivate}
*/
@Injectable()
export class AdminGuard implements CanActivate {
constructor(private router: Router, private userService: UserService) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (localStorage.getItem('token')) {
return this.userService.me()
.map((user: User) => {
return user.isAdmin;
})
.catch(() => {
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
return Observable.of(false);
});
}
else {
// not logged in so redirect to login page with the return url
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
return false;
}
}
} | {
"content_hash": "60d9265b913e0dc03a837b262855860b",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 99,
"avg_line_length": 31.026315789473685,
"alnum_prop": 0.6225614927905004,
"repo_name": "sylcastaing/Olaf-web",
"id": "2db9865dd6ccc521982ec586f90e68a3db6d4101",
"size": "1179",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/_guards/admin.guard.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3685"
},
{
"name": "HTML",
"bytes": "10883"
},
{
"name": "JavaScript",
"bytes": "1996"
},
{
"name": "TypeScript",
"bytes": "46110"
}
],
"symlink_target": ""
} |
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.math.BigDecimal;
/**
* Created by bbraun on 5/10/2014.
*/
public class TotalPanel extends JPanel {
private BigDecimal tax = new BigDecimal(".06");
private Computer computer;
private String computers;
private String months;
private JLabel numberPcsLabel;
private JTextField numberOfPcs;
private JPanel pcPanel;
private JLabel payOffMonthsLabel;
private JTextField payOffMonths;
private JPanel monthsPanel;
private JButton calculate;
private JPanel calculatePanel;
private JPanel accCostPanel;
private JPanel customerCostPanel;
private JLabel accLabel;
private JLabel customerLabel;
private BigDecimal accCost;
private BigDecimal customerCost;
private int pcs;
private int mnths;
public TotalPanel(final Computer computer) {
this.computer = computer;
computers = "10";
months = "6";
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
pcPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
monthsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
calculatePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
accCostPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
customerCostPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
numberPcsLabel = new JLabel("Number of Computers: ");
numberOfPcs = new JTextField(computers, 10);
numberOfPcs.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
char vChar = e.getKeyChar();
if (!(Character.isDigit(vChar) ||
(vChar == KeyEvent.VK_BACK_SPACE) ||
(vChar == KeyEvent.VK_DELETE))) {
e.consume();
}
}
});
payOffMonthsLabel = new JLabel("Months till Payoff: ");
payOffMonths = new JTextField(months, 10);
payOffMonths.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
char vChar = e.getKeyChar();
if (!(Character.isDigit(vChar) ||
(vChar == KeyEvent.VK_BACK_SPACE) ||
(vChar == KeyEvent.VK_DELETE))) {
e.consume();
}
}
});
calculate = new JButton("Calculate Cost");
calculate.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
accCost = computer.getCost(Integer.parseInt(numberOfPcs.getText()), tax);
accLabel.setText("$" + accCost.toString());
customerCost = calculateMonthly(accCost, Integer.parseInt(payOffMonths.getText()));
customerLabel.setText("$" + customerCost.toString());
}
});
accLabel = new JLabel();
accCostPanel.add(new JLabel("ACC Cost: "));
accCostPanel.add(accLabel);
customerLabel = new JLabel();
customerCostPanel.add(new JLabel("Customer Monthly Cost: "));
customerCostPanel.add(customerLabel);
pcPanel.add(numberPcsLabel);
pcPanel.add(numberOfPcs);
monthsPanel.add(payOffMonthsLabel);
monthsPanel.add(payOffMonths);
calculatePanel.add(calculate);
add(pcPanel);
add(monthsPanel);
add(accCostPanel);
add(customerCostPanel);
add(calculatePanel);
}
private BigDecimal calculateMonthly(BigDecimal cost, int months) {
BigDecimal total;
total = cost.divide(new BigDecimal(months), 2, BigDecimal.ROUND_HALF_EVEN);
return total;
}
}
| {
"content_hash": "be7023f0bdf30aa12018322ad163042b",
"timestamp": "",
"source": "github",
"line_count": 111,
"max_line_length": 99,
"avg_line_length": 35.828828828828826,
"alnum_prop": 0.5981895901433241,
"repo_name": "bmb330/ACCHaaSCalculator",
"id": "87b7fb13cc3e74d259bdd206889bada0377bd209",
"size": "3977",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/TotalPanel.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "37646"
}
],
"symlink_target": ""
} |
package com.example.test;
public class Counter {
public static int inc()
{
return count++;
}
public static int count = 0;
}
| {
"content_hash": "aaf9dd0da2bb71f134b71007554febca",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 32,
"avg_line_length": 11,
"alnum_prop": 0.577922077922078,
"repo_name": "davidkarlsen/mycila",
"id": "d9b8244c64c679c640334a389b6eb5bb50ec0c22",
"size": "787",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "mycila-testing-plugins/mycila-testing-jetty/src/it/tests/server-webapp-scope/src/main/java/com/example/test/Counter.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "1317"
},
{
"name": "Java",
"bytes": "622632"
}
],
"symlink_target": ""
} |
/**
* Web page integration module for the mermaid framework. It uses the mermaidAPI for mermaid functionality and to render
* the diagrams to svg code.
*/
import he from 'he'
import mermaidAPI from './mermaidAPI'
import { logger } from './logger'
/**
* ## init
* Function that goes through the document to find the chart definitions in there and render them.
*
* The function tags the processed attributes with the attribute data-processed and ignores found elements with the
* attribute already set. This way the init function can be triggered several times.
*
* Optionally, `init` can accept in the second argument one of the following:
* - a DOM Node
* - an array of DOM nodes (as would come from a jQuery selector)
* - a W3C selector, a la `.mermaid`
*
* ```mermaid
* graph LR;
* a(Find elements)-->b{Processed}
* b-->|Yes|c(Leave element)
* b-->|No |d(Transform)
* ```
* Renders the mermaid diagrams
* @param nodes a css selector or an array of nodes
*/
const init = function () {
const conf = mermaidAPI.getConfig()
logger.debug('Starting rendering diagrams')
let nodes
if (arguments.length >= 2) {
/*! sequence config was passed as #1 */
if (typeof arguments[0] !== 'undefined') {
mermaid.sequenceConfig = arguments[0]
}
nodes = arguments[1]
} else {
nodes = arguments[0]
}
// if last argument is a function this is the callback function
let callback
if (typeof arguments[arguments.length - 1] === 'function') {
callback = arguments[arguments.length - 1]
logger.debug('Callback function found')
} else {
if (typeof conf.mermaid !== 'undefined') {
if (typeof conf.mermaid.callback === 'function') {
callback = conf.mermaid.callback
logger.debug('Callback function found')
} else {
logger.debug('No Callback function found')
}
}
}
nodes = nodes === undefined ? document.querySelectorAll('.mermaid')
: typeof nodes === 'string' ? document.querySelectorAll(nodes)
: nodes instanceof window.Node ? [nodes]
: nodes // Last case - sequence config was passed pick next
logger.debug('Start On Load before: ' + mermaid.startOnLoad)
if (typeof mermaid.startOnLoad !== 'undefined') {
logger.debug('Start On Load inner: ' + mermaid.startOnLoad)
mermaidAPI.initialize({ startOnLoad: mermaid.startOnLoad })
}
if (typeof mermaid.ganttConfig !== 'undefined') {
mermaidAPI.initialize({ gantt: mermaid.ganttConfig })
}
let txt
for (let i = 0; i < nodes.length; i++) {
const element = nodes[i]
/*! Check if previously processed */
if (!element.getAttribute('data-processed')) {
element.setAttribute('data-processed', true)
} else {
continue
}
const id = `mermaid-${Date.now()}`
// Fetch the graph definition including tags
txt = element.innerHTML
// transforms the html to pure text
txt = he.decode(txt).trim().replace(/<br>/ig, '<br/>')
mermaidAPI.render(id, txt, (svgCode, bindFunctions) => {
element.innerHTML = svgCode
if (typeof callback !== 'undefined') {
callback(id)
}
bindFunctions(element)
}, element)
}
}
const initialize = function (config) {
logger.debug('Initializing mermaid')
if (typeof config.mermaid !== 'undefined') {
if (typeof config.mermaid.startOnLoad !== 'undefined') {
mermaid.startOnLoad = config.mermaid.startOnLoad
}
if (typeof config.mermaid.htmlLabels !== 'undefined') {
mermaid.htmlLabels = config.mermaid.htmlLabels
}
}
mermaidAPI.initialize(config)
}
/**
* ##contentLoaded
* Callback function that is called when page is loaded. This functions fetches configuration for mermaid rendering and
* calls init for rendering the mermaid diagrams on the page.
*/
const contentLoaded = function () {
let config
if (mermaid.startOnLoad) {
// No config found, do check API config
config = mermaidAPI.getConfig()
if (config.startOnLoad) {
mermaid.init()
}
} else {
if (typeof mermaid.startOnLoad === 'undefined') {
logger.debug('In start, no config')
config = mermaidAPI.getConfig()
if (config.startOnLoad) {
mermaid.init()
}
}
}
}
if (typeof document !== 'undefined') {
/*!
* Wait for document loaded before starting the execution
*/
window.addEventListener('load', function () {
contentLoaded()
}, false)
}
const mermaid = {
startOnLoad: true,
htmlLabels: true,
mermaidAPI,
parse: mermaidAPI.parse,
render: mermaidAPI.render,
init,
initialize,
contentLoaded
}
export default mermaid
| {
"content_hash": "1a187103e9b4e873839c274afeaef324",
"timestamp": "",
"source": "github",
"line_count": 167,
"max_line_length": 120,
"avg_line_length": 27.730538922155688,
"alnum_prop": 0.6586050529043403,
"repo_name": "mojo2012/spot-framework",
"id": "a8f05ffea1df32ef3a8f80bf9112b3fe30a199b8",
"size": "4631",
"binary": false,
"copies": "6",
"ref": "refs/heads/develop",
"path": "docs/node_modules/mermaid/src/mermaid.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "10146"
},
{
"name": "HTML",
"bytes": "10317"
},
{
"name": "Java",
"bytes": "997187"
}
],
"symlink_target": ""
} |
//===--- Executor.h - ABI structures for executors --------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Swift ABI describing executors.
//
//===----------------------------------------------------------------------===//
#ifndef SWIFT_ABI_EXECUTOR_H
#define SWIFT_ABI_EXECUTOR_H
#include <inttypes.h>
#include "swift/ABI/Actor.h"
#include "swift/ABI/HeapObject.h"
#include "swift/Runtime/Casting.h"
namespace swift {
class AsyncContext;
class AsyncTask;
class DefaultActor;
class Job;
class SerialExecutorWitnessTable;
/// An unmanaged reference to an executor.
///
/// This type corresponds to the type Optional<Builtin.Executor> in
/// Swift. The representation of nil in Optional<Builtin.Executor>
/// aligns with what this type calls the generic executor, so the
/// notional subtype of this type which is never generic corresponds
/// to the type Builtin.Executor.
///
/// An executor reference is divided into two pieces:
///
/// - The identity, which is just a (potentially ObjC) object
/// reference; when this is null, the reference is generic.
/// Equality of executor references is based solely on equality
/// of identity.
///
/// - The implementation, which is an optional reference to a
/// witness table for the SerialExecutor protocol. When this
/// is null, but the identity is non-null, the reference is to
/// a default actor. The low bits of the implementation pointer
/// are reserved for the use of marking interesting properties
/// about the executor's implementation. The runtime masks these
/// bits off before accessing the witness table, so setting them
/// in the future should back-deploy as long as the witness table
/// reference is still present.
class ExecutorRef {
HeapObject *Identity; // Not necessarily Swift reference-countable
uintptr_t Implementation;
// We future-proof the ABI here by masking the low bits off the
// implementation pointer before using it as a witness table.
enum: uintptr_t {
WitnessTableMask = ~uintptr_t(alignof(void*) - 1)
};
constexpr ExecutorRef(HeapObject *identity, uintptr_t implementation)
: Identity(identity), Implementation(implementation) {}
public:
/// A generic execution environment. When running in a generic
/// environment, it's presumed to be okay to switch synchronously
/// to an actor. As an executor request, this represents a request
/// to drop whatever the current actor is.
constexpr static ExecutorRef generic() {
return ExecutorRef(nullptr, 0);
}
/// Given a pointer to a default actor, return an executor reference
/// for it.
static ExecutorRef forDefaultActor(DefaultActor *actor) {
assert(actor);
return ExecutorRef(actor, 0);
}
/// Given a pointer to a serial executor and its SerialExecutor
/// conformance, return an executor reference for it.
static ExecutorRef forOrdinary(HeapObject *identity,
const SerialExecutorWitnessTable *witnessTable) {
assert(identity);
assert(witnessTable);
return ExecutorRef(identity, reinterpret_cast<uintptr_t>(witnessTable));
}
HeapObject *getIdentity() const {
return Identity;
}
/// Is this the generic executor reference?
bool isGeneric() const {
return Identity == 0;
}
/// Is this a default-actor executor reference?
bool isDefaultActor() const {
return !isGeneric() && Implementation == 0;
}
DefaultActor *getDefaultActor() const {
assert(isDefaultActor());
return reinterpret_cast<DefaultActor*>(Identity);
}
const SerialExecutorWitnessTable *getSerialExecutorWitnessTable() const {
assert(!isGeneric() && !isDefaultActor());
auto table = Implementation & WitnessTableMask;
return reinterpret_cast<const SerialExecutorWitnessTable*>(table);
}
/// Do we have to do any work to start running as the requested
/// executor?
bool mustSwitchToRun(ExecutorRef newExecutor) const {
return Identity != newExecutor.Identity;
}
/// Is this executor the main executor?
bool isMainExecutor() const;
/// Get the raw value of the Implementation field, for tracing.
uintptr_t getRawImplementation() { return Implementation; }
bool operator==(ExecutorRef other) const {
return Identity == other.Identity;
}
bool operator!=(ExecutorRef other) const {
return !(*this == other);
}
};
using JobInvokeFunction =
SWIFT_CC(swiftasync)
void (Job *);
using TaskContinuationFunction =
SWIFT_CC(swiftasync)
void (SWIFT_ASYNC_CONTEXT AsyncContext *);
using ThrowingTaskFutureWaitContinuationFunction =
SWIFT_CC(swiftasync)
void (SWIFT_ASYNC_CONTEXT AsyncContext *, SWIFT_CONTEXT void *);
template <class AsyncSignature>
class AsyncFunctionPointer;
template <class AsyncSignature>
struct AsyncFunctionTypeImpl;
template <class AsyncSignature>
struct AsyncContinuationTypeImpl;
/// The abstract signature for an asynchronous function.
template <class Sig, bool HasErrorResult>
struct AsyncSignature;
template <class DirectResultTy, class... ArgTys, bool HasErrorResult>
struct AsyncSignature<DirectResultTy(ArgTys...), HasErrorResult> {
bool hasDirectResult = !std::is_same<DirectResultTy, void>::value;
using DirectResultType = DirectResultTy;
bool hasErrorResult = HasErrorResult;
using FunctionPointer = AsyncFunctionPointer<AsyncSignature>;
using FunctionType = typename AsyncFunctionTypeImpl<AsyncSignature>::type;
using ContinuationType = typename AsyncContinuationTypeImpl<AsyncSignature>::type;
};
/// A signature for a thin async function that takes no arguments
/// and returns no results.
using ThinNullaryAsyncSignature =
AsyncSignature<void(), false>;
/// A signature for a thick async function that takes no formal
/// arguments and returns no results.
using ThickNullaryAsyncSignature =
AsyncSignature<void(HeapObject*), false>;
template <class Signature>
struct AsyncFunctionTypeImpl;
template <class DirectResultTy, class... ArgTys, bool HasErrorResult>
struct AsyncFunctionTypeImpl<
AsyncSignature<DirectResultTy(ArgTys...), HasErrorResult>> {
using type = SWIFT_CC(swiftasync) void(SWIFT_ASYNC_CONTEXT AsyncContext *,
ArgTys...);
};
template <class Signature>
struct AsyncContinuationTypeImpl;
template <class DirectResultTy, class... ArgTys>
struct AsyncContinuationTypeImpl<
AsyncSignature<DirectResultTy(ArgTys...), /*throws=*/true>> {
using type = SWIFT_CC(swiftasync) void(SWIFT_ASYNC_CONTEXT AsyncContext *,
DirectResultTy,
SWIFT_CONTEXT void *);
};
template <class DirectResultTy, class... ArgTys>
struct AsyncContinuationTypeImpl<
AsyncSignature<DirectResultTy(ArgTys...), /*throws=*/false>> {
using type = SWIFT_CC(swiftasync) void(SWIFT_ASYNC_CONTEXT AsyncContext *,
DirectResultTy);
};
template <class... ArgTys>
struct AsyncContinuationTypeImpl<
AsyncSignature<void(ArgTys...), /*throws=*/true>> {
using type = SWIFT_CC(swiftasync) void(SWIFT_ASYNC_CONTEXT AsyncContext *,
SWIFT_CONTEXT SwiftError *);
};
template <class... ArgTys>
struct AsyncContinuationTypeImpl<
AsyncSignature<void(ArgTys...), /*throws=*/false>> {
using type = SWIFT_CC(swiftasync) void(SWIFT_ASYNC_CONTEXT AsyncContext *);
};
template <class Fn>
using AsyncFunctionType = typename AsyncFunctionTypeImpl<Fn>::type;
template <class Fn>
using AsyncContinuationType = typename AsyncContinuationTypeImpl<Fn>::type;
/// A "function pointer" for an async function.
///
/// Eventually, this will always be signed with the data key
/// using a type-specific discriminator.
template <class AsyncSignature>
class AsyncFunctionPointer {
public:
/// The function to run.
TargetCompactFunctionPointer<InProcess, AsyncFunctionType<AsyncSignature>,
/*nullable*/ false,
int32_t> Function;
/// The expected size of the context.
uint32_t ExpectedContextSize;
};
}
#endif
| {
"content_hash": "4f1dec5da457e80db057f94e7a02d647",
"timestamp": "",
"source": "github",
"line_count": 254,
"max_line_length": 84,
"avg_line_length": 33.31496062992126,
"alnum_prop": 0.7055069723469629,
"repo_name": "benlangmuir/swift",
"id": "e6e54c26016f61fc9e049c37c0a33fe2e0372070",
"size": "8462",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "include/swift/ABI/Executor.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "47063"
},
{
"name": "C",
"bytes": "5465361"
},
{
"name": "C++",
"bytes": "48553779"
},
{
"name": "CMake",
"bytes": "726224"
},
{
"name": "D",
"bytes": "1107"
},
{
"name": "DTrace",
"bytes": "2593"
},
{
"name": "Emacs Lisp",
"bytes": "57637"
},
{
"name": "LLVM",
"bytes": "74481"
},
{
"name": "Makefile",
"bytes": "2361"
},
{
"name": "Objective-C",
"bytes": "476267"
},
{
"name": "Objective-C++",
"bytes": "162387"
},
{
"name": "Python",
"bytes": "1818826"
},
{
"name": "Roff",
"bytes": "3683"
},
{
"name": "Ruby",
"bytes": "2132"
},
{
"name": "Shell",
"bytes": "215898"
},
{
"name": "Swift",
"bytes": "40342212"
},
{
"name": "Vim Script",
"bytes": "20025"
},
{
"name": "sed",
"bytes": "1056"
}
],
"symlink_target": ""
} |
<?php
namespace Symfony\Component\Translation;
/*
* This file is part of the Symfony framework.
*
* (c) Fabien Potencier <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
/**
* TranslatorInterface.
*
* @author Fabien Potencier <[email protected]>
*/
interface TranslatorInterface
{
/**
* Translates the given message.
*
* @param string $id The message id
* @param array $parameters An array of parameters for the message
* @param string $domain The domain for the message
* @param string $locale The locale
*
* @return string The translated string
*/
function trans($id, array $parameters = array(), $domain = null, $locale = null);
/**
* Translates the given choice message by choosing a translation according to a number.
*
* @param string $id The message id
* @param integer $number The number to use to find the indice of the message
* @param array $parameters An array of parameters for the message
* @param string $domain The domain for the message
* @param string $locale The locale
*
* @return string The translated string
*/
function transChoice($id, $number, array $parameters = array(), $domain = null, $locale = null);
/**
* Sets the current locale.
*
* @param string $locale The locale
*/
function setLocale($locale);
/**
* Returns the current locale.
*
* @return string The locale
*/
function getLocale();
}
| {
"content_hash": "59668b81d82ab4c6d6d1f315ffae4011",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 100,
"avg_line_length": 28.322033898305083,
"alnum_prop": 0.6343506882106523,
"repo_name": "popofr13/symfony2-esi-sandbox",
"id": "2a349a96278b90b7b5be64fa72f3d01976e05516",
"size": "1671",
"binary": false,
"copies": "10",
"ref": "refs/heads/master",
"path": "src/vendor/symfony/src/Symfony/Component/Translation/TranslatorInterface.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "26662"
}
],
"symlink_target": ""
} |
import gc
import sys
import time
import unittest
from django.dispatch import Signal, receiver
if sys.platform.startswith('java'):
def garbage_collect():
# Some JVM GCs will execute finalizers in a different thread, meaning
# we need to wait for that to complete before we go on looking for the
# effects of that.
gc.collect()
time.sleep(0.1)
elif hasattr(sys, "pypy_version_info"):
def garbage_collect():
# Collecting weakreferences can take two collections on PyPy.
gc.collect()
gc.collect()
else:
def garbage_collect():
gc.collect()
def receiver_1_arg(val, **kwargs):
return val
class Callable(object):
def __call__(self, val, **kwargs):
return val
def a(self, val, **kwargs):
return val
a_signal = Signal(providing_args=["val"])
b_signal = Signal(providing_args=["val"])
c_signal = Signal(providing_args=["val"])
class DispatcherTests(unittest.TestCase):
"""Test suite for dispatcher (barely started)"""
def _testIsClean(self, signal):
"""Assert that everything has been cleaned up automatically"""
self.assertEqual(signal.receivers, [])
# force cleanup just in case
signal.receivers = []
def testExact(self):
a_signal.connect(receiver_1_arg, sender=self)
expected = [(receiver_1_arg,"test")]
result = a_signal.send(sender=self, val="test")
self.assertEqual(result, expected)
a_signal.disconnect(receiver_1_arg, sender=self)
self._testIsClean(a_signal)
def testIgnoredSender(self):
a_signal.connect(receiver_1_arg)
expected = [(receiver_1_arg,"test")]
result = a_signal.send(sender=self, val="test")
self.assertEqual(result, expected)
a_signal.disconnect(receiver_1_arg)
self._testIsClean(a_signal)
def testGarbageCollected(self):
a = Callable()
a_signal.connect(a.a, sender=self)
expected = []
del a
garbage_collect()
result = a_signal.send(sender=self, val="test")
self.assertEqual(result, expected)
self._testIsClean(a_signal)
def testMultipleRegistration(self):
a = Callable()
a_signal.connect(a)
a_signal.connect(a)
a_signal.connect(a)
a_signal.connect(a)
a_signal.connect(a)
a_signal.connect(a)
result = a_signal.send(sender=self, val="test")
self.assertEqual(len(result), 1)
self.assertEqual(len(a_signal.receivers), 1)
del a
del result
garbage_collect()
self._testIsClean(a_signal)
def testUidRegistration(self):
def uid_based_receiver_1(**kwargs):
pass
def uid_based_receiver_2(**kwargs):
pass
a_signal.connect(uid_based_receiver_1, dispatch_uid = "uid")
a_signal.connect(uid_based_receiver_2, dispatch_uid = "uid")
self.assertEqual(len(a_signal.receivers), 1)
a_signal.disconnect(dispatch_uid = "uid")
self._testIsClean(a_signal)
def testRobust(self):
"""Test the sendRobust function"""
def fails(val, **kwargs):
raise ValueError('this')
a_signal.connect(fails)
result = a_signal.send_robust(sender=self, val="test")
err = result[0][1]
self.assertIsInstance(err, ValueError)
self.assertEqual(err.args, ('this',))
a_signal.disconnect(fails)
self._testIsClean(a_signal)
def testDisconnection(self):
receiver_1 = Callable()
receiver_2 = Callable()
receiver_3 = Callable()
a_signal.connect(receiver_1)
a_signal.connect(receiver_2)
a_signal.connect(receiver_3)
a_signal.disconnect(receiver_1)
del receiver_2
garbage_collect()
a_signal.disconnect(receiver_3)
self._testIsClean(a_signal)
def test_has_listeners(self):
self.assertFalse(a_signal.has_listeners())
self.assertFalse(a_signal.has_listeners(sender=object()))
receiver_1 = Callable()
a_signal.connect(receiver_1)
self.assertTrue(a_signal.has_listeners())
self.assertTrue(a_signal.has_listeners(sender=object()))
a_signal.disconnect(receiver_1)
self.assertFalse(a_signal.has_listeners())
self.assertFalse(a_signal.has_listeners(sender=object()))
class ReceiverTestCase(unittest.TestCase):
"""
Test suite for receiver.
"""
def testReceiverSingleSignal(self):
@receiver(a_signal)
def f(val, **kwargs):
self.state = val
self.state = False
a_signal.send(sender=self, val=True)
self.assertTrue(self.state)
def testReceiverSignalList(self):
@receiver([a_signal, b_signal, c_signal])
def f(val, **kwargs):
self.state.append(val)
self.state = []
a_signal.send(sender=self, val='a')
c_signal.send(sender=self, val='c')
b_signal.send(sender=self, val='b')
self.assertIn('a', self.state)
self.assertIn('b', self.state)
self.assertIn('c', self.state)
| {
"content_hash": "78c1d264f3c13edafd5d77100f774748",
"timestamp": "",
"source": "github",
"line_count": 164,
"max_line_length": 78,
"avg_line_length": 31.48170731707317,
"alnum_prop": 0.6135967460778617,
"repo_name": "makinacorpus/django",
"id": "5f7dca87cc5f44530123fb94bd25c2b1eb94f139",
"size": "5163",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/dispatch/tests/test_dispatcher.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "JavaScript",
"bytes": "98175"
},
{
"name": "Python",
"bytes": "8391980"
},
{
"name": "Shell",
"bytes": "12135"
}
],
"symlink_target": ""
} |
package com.thoughtworks.xstream.io.json;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.net.URL;
import javax.xml.stream.XMLStreamException;
import org.codehaus.jettison.mapped.Configuration;
import org.codehaus.jettison.mapped.MappedNamespaceConvention;
import org.codehaus.jettison.mapped.MappedXMLInputFactory;
import org.codehaus.jettison.mapped.MappedXMLOutputFactory;
import com.thoughtworks.xstream.io.AbstractDriver;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.StreamException;
import com.thoughtworks.xstream.io.xml.QNameMap;
import com.thoughtworks.xstream.io.xml.StaxReader;
import com.thoughtworks.xstream.io.xml.StaxWriter;
/**
* Simple XStream driver wrapping Jettison's Mapped reader and writer. Serializes object from and to JSON.
*
* @author Dejan Bosanac
*/
public class JettisonMappedXmlDriver extends AbstractDriver {
protected final MappedXMLOutputFactory mof;
protected final MappedXMLInputFactory mif;
protected final MappedNamespaceConvention convention;
protected final boolean useSerializeAsArray;
/**
* Construct a JettisonMappedXmlDriver.
*/
public JettisonMappedXmlDriver() {
this(new Configuration());
}
/**
* Construct a JettisonMappedXmlDriver with configuration.
*
* @param config the Jettison configuration
*/
public JettisonMappedXmlDriver(final Configuration config) {
this(config, true);
}
/**
* Construct a JettisonMappedXmlDriver with configuration.
* <p>
* This constructor has been added by special request of Jettison users to support JSON generated by older Jettison
* versions. if the driver is setup to ignore the XStream hints for JSON arrays, there is neither support from
* XStream's side nor are there any tests to ensure this mode.
* </p>
*
* @param config the Jettison configuration
* @param useSerializeAsArray flag to use XStream's hints for collections and arrays
* @since 1.4
*/
public JettisonMappedXmlDriver(final Configuration config, final boolean useSerializeAsArray) {
mof = new MappedXMLOutputFactory(config);
mif = new MappedXMLInputFactory(config);
convention = new MappedNamespaceConvention(config);
this.useSerializeAsArray = useSerializeAsArray;
}
@Override
public HierarchicalStreamReader createReader(final Reader reader) {
try {
return new StaxReader(new QNameMap(), mif.createXMLStreamReader(reader), getNameCoder());
} catch (final XMLStreamException e) {
throw new StreamException(e);
}
}
@Override
public HierarchicalStreamReader createReader(final InputStream input) {
try {
return new StaxReader(new QNameMap(), mif.createXMLStreamReader(input), getNameCoder());
} catch (final XMLStreamException e) {
throw new StreamException(e);
}
}
@Override
public HierarchicalStreamReader createReader(final URL in) {
InputStream instream = null;
try {
instream = in.openStream();
return new StaxReader(new QNameMap(), mif.createXMLStreamReader(in.toExternalForm(), instream),
getNameCoder());
} catch (final XMLStreamException e) {
throw new StreamException(e);
} catch (final IOException e) {
throw new StreamException(e);
} finally {
if (instream != null) {
try {
instream.close();
} catch (final IOException e) {
// ignore
}
}
}
}
@Override
public HierarchicalStreamReader createReader(final File in) {
InputStream instream = null;
try {
instream = new FileInputStream(in);
return new StaxReader(new QNameMap(), mif.createXMLStreamReader(in.toURI().toASCIIString(), instream),
getNameCoder());
} catch (final XMLStreamException e) {
throw new StreamException(e);
} catch (final IOException e) {
throw new StreamException(e);
} finally {
if (instream != null) {
try {
instream.close();
} catch (final IOException e) {
// ignore
}
}
}
}
@Override
public HierarchicalStreamWriter createWriter(final Writer writer) {
try {
if (useSerializeAsArray) {
return new JettisonStaxWriter(new QNameMap(), mof.createXMLStreamWriter(writer), getNameCoder(),
convention);
} else {
return new StaxWriter(new QNameMap(), mof.createXMLStreamWriter(writer), getNameCoder());
}
} catch (final XMLStreamException e) {
throw new StreamException(e);
}
}
@Override
public HierarchicalStreamWriter createWriter(final OutputStream output) {
try {
if (useSerializeAsArray) {
return new JettisonStaxWriter(new QNameMap(), mof.createXMLStreamWriter(output), getNameCoder(),
convention);
} else {
return new StaxWriter(new QNameMap(), mof.createXMLStreamWriter(output), getNameCoder());
}
} catch (final XMLStreamException e) {
throw new StreamException(e);
}
}
}
| {
"content_hash": "2b6299787f8a04c524a63674534dfd11",
"timestamp": "",
"source": "github",
"line_count": 166,
"max_line_length": 119,
"avg_line_length": 34.5722891566265,
"alnum_prop": 0.6459313469245513,
"repo_name": "codehaus/xstream",
"id": "0fa525fca584fe4f60cf703330d9ba30b1690faf",
"size": "6075",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "xstream/src/java/com/thoughtworks/xstream/io/json/JettisonMappedXmlDriver.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "6974"
},
{
"name": "HTML",
"bytes": "415008"
},
{
"name": "Java",
"bytes": "2456197"
},
{
"name": "XSLT",
"bytes": "1101"
}
],
"symlink_target": ""
} |
var errorHandler = require('../middleware/errorHandler');
module.exports = function(app) {
// manual 500 error
app.get('/500', function(req, res) {
throw new Error('This is a 500 Error');
});
// wildcard route for 404 errors
app.get('/*', function(req, res) {
console.log(req.path)
throw new errorHandler.NotFound;
});
} | {
"content_hash": "26f12dfd6fa40b4adbd03b03368ceb15",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 57,
"avg_line_length": 25.4,
"alnum_prop": 0.5853018372703412,
"repo_name": "philoushka/QuickPoll",
"id": "73523a3d439ef6b42a53eb50480390c80b50c3b7",
"size": "381",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "routes/global.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "228"
},
{
"name": "JavaScript",
"bytes": "68894"
}
],
"symlink_target": ""
} |
<?php
$config['plugin_load'] = '/test_app/plugins/test_plugin/config/load.php';
| {
"content_hash": "e798dec7084d16bda711c6445a6ada4c",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 73,
"avg_line_length": 27,
"alnum_prop": 0.691358024691358,
"repo_name": "MadMikeyB/MikeyPaste",
"id": "9222f0ae3a2961adf3bc858de68454fa737625fa",
"size": "806",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "cake/tests/test_app/plugins/test_plugin/config/load.php",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "JavaScript",
"bytes": "143"
},
{
"name": "PHP",
"bytes": "9036084"
},
{
"name": "Shell",
"bytes": "1830"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Windows.UI.Xaml.Navigation;
namespace TODOFileHandlingSample.Mvvm
{
public abstract class ViewModelBase : BindableBase, Services.NavigationService.INavigatable
{
public virtual Task OnNavigatedToAsync(string parameter, NavigationMode mode, Dictionary<string, object> state)
{
return Task.FromResult<object>(null);
}
public virtual Task OnNavigatedFromAsync(Dictionary<string, object> state, bool suspending)
{
return Task.FromResult<object>(null);
}
}
} | {
"content_hash": "03e6a1fb30039491164656ac3fe2dcdc",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 119,
"avg_line_length": 29.761904761904763,
"alnum_prop": 0.7072,
"repo_name": "johnsonlu/WinDevCamp",
"id": "d28621d0ce9df27cdabb96b315b5ac92e95032e9",
"size": "627",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "Presentation/z102. File Management/Demos/TODOFileHandlingSample/TODOFileHandlingSample/Mvvm/ViewModelBase.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "110"
},
{
"name": "C",
"bytes": "431"
},
{
"name": "C#",
"bytes": "1767149"
},
{
"name": "C++",
"bytes": "17747"
},
{
"name": "HTML",
"bytes": "106302"
},
{
"name": "Objective-C",
"bytes": "1217"
}
],
"symlink_target": ""
} |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.changes.committed;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.FileEditorManagerListener;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.vcs.CachingCommittedChangesProvider;
import com.intellij.openapi.vcs.VcsBundle;
import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vcs.versionBrowser.CommittedChangeList;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.EditorNotificationPanel;
import com.intellij.util.messages.MessageBus;
import com.intellij.util.messages.MessageBusConnection;
import com.intellij.util.text.DateFormatUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
/**
* @author yole
* todo: use EditorNotifications
*/
public class OutdatedVersionNotifier {
private static final Logger LOG = Logger.getInstance(OutdatedVersionNotifier.class);
private final FileEditorManager myFileEditorManager;
private final CommittedChangesCache myCache;
private final Project myProject;
private static final Key<OutdatedRevisionPanel> PANEL_KEY = new Key<>("OutdatedRevisionPanel");
private volatile boolean myIncomingChangesRequested;
public OutdatedVersionNotifier(FileEditorManager fileEditorManager,
CommittedChangesCache cache,
MessageBus messageBus, Project project) {
myFileEditorManager = fileEditorManager;
myCache = cache;
myProject = project;
MessageBusConnection busConnection = messageBus.connect();
busConnection.subscribe(CommittedChangesCache.COMMITTED_TOPIC, new CommittedChangesAdapter() {
@Override
public void incomingChangesUpdated(@Nullable final List<CommittedChangeList> receivedChanges) {
if (myCache.getCachedIncomingChanges() == null) {
requestLoadIncomingChanges();
}
else {
updateAllEditorsLater();
}
}
@Override
public void changesCleared() {
updateAllEditorsLater();
}
});
busConnection.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, new FileEditorManagerListener() {
@Override
public void fileOpened(@NotNull FileEditorManager source, @NotNull VirtualFile file) {
if (myCache.getCachedIncomingChanges() == null) {
requestLoadIncomingChanges();
}
else {
final Pair<CommittedChangeList, Change> pair = myCache.getIncomingChangeList(file);
if (pair != null) {
final FileEditor[] fileEditors = source.getEditors(file);
for(FileEditor editor: fileEditors) {
initPanel(pair.first, pair.second, editor);
}
}
}
}
});
}
private void requestLoadIncomingChanges() {
debug("Requesting load of incoming changes");
if (!myIncomingChangesRequested) {
myIncomingChangesRequested = true;
myCache.loadIncomingChangesAsync(committedChangeLists -> {
myIncomingChangesRequested = false;
updateAllEditorsLater();
}, true);
}
}
private static void debug(@NonNls String message) {
LOG.debug(message);
}
private void updateAllEditorsLater() {
debug("Queueing update of editors");
ApplicationManager.getApplication().invokeLater(() -> updateAllEditors(), myProject.getDisposed());
}
private void updateAllEditors() {
if (myCache.getCachedIncomingChanges() == null) {
requestLoadIncomingChanges();
return;
}
debug("Updating editors");
final VirtualFile[] files = myFileEditorManager.getOpenFiles();
for(VirtualFile file: files) {
final Pair<CommittedChangeList,Change> pair = myCache.getIncomingChangeList(file);
final FileEditor[] fileEditors = myFileEditorManager.getEditors(file);
for(FileEditor editor: fileEditors) {
final OutdatedRevisionPanel oldPanel = editor.getUserData(PANEL_KEY);
if (pair != null) {
if (oldPanel != null) {
oldPanel.setChangeList(pair.first, pair.second);
}
else {
initPanel(pair.first, pair.second, editor);
}
}
else if (oldPanel != null) {
myFileEditorManager.removeTopComponent(editor, oldPanel);
editor.putUserData(PANEL_KEY, null);
}
}
}
}
private void initPanel(final CommittedChangeList list, final Change c, final FileEditor editor) {
if (!isIncomingChangesSupported(list)) {
return;
}
final OutdatedRevisionPanel component = new OutdatedRevisionPanel(list, c);
editor.putUserData(PANEL_KEY, component);
myFileEditorManager.addTopComponent(editor, component);
}
private static class OutdatedRevisionPanel extends EditorNotificationPanel {
private CommittedChangeList myChangeList;
OutdatedRevisionPanel(CommittedChangeList changeList, final Change c) {
super();
createActionLabel(VcsBundle.message("outdated.version.show.diff.action"), "Compare.LastVersion");
createActionLabel(VcsBundle.message("outdated.version.update.project.action"), "Vcs.UpdateProject");
myChangeList = changeList;
updateLabelText(c);
}
private void updateLabelText(final Change c) {
String comment = myChangeList.getComment();
int pos = comment.indexOf("\n");
if (pos >= 0) {
comment = comment.substring(0, pos).trim() + "...";
}
final String formattedDate = DateFormatUtil.formatPrettyDateTime(myChangeList.getCommitDate());
final boolean dateIsPretty = ! formattedDate.contains("/");
final String key = c.getType() == Change.Type.DELETED ? "outdated.version.text.deleted" :
(dateIsPretty ? "outdated.version.pretty.date.text" : "outdated.version.text");
myLabel.setText(VcsBundle.message(key, myChangeList.getCommitterName(), formattedDate, comment));
}
public void setChangeList(final CommittedChangeList changeList, final Change c) {
myChangeList = changeList;
updateLabelText(c);
}
}
private static boolean isIncomingChangesSupported(@NotNull CommittedChangeList list) {
CachingCommittedChangesProvider provider = list.getVcs().getCachingCommittedChangesProvider();
return provider != null && provider.supportsIncomingChanges();
}
}
| {
"content_hash": "fef2e7f2c2c2625d7f658d72b389a549",
"timestamp": "",
"source": "github",
"line_count": 174,
"max_line_length": 140,
"avg_line_length": 39.206896551724135,
"alnum_prop": 0.7115215479331575,
"repo_name": "paplorinc/intellij-community",
"id": "04cacae0164e435a3b5c3daafffed97297abb9ae",
"size": "6822",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "platform/vcs-impl/src/com/intellij/openapi/vcs/changes/committed/OutdatedVersionNotifier.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
const old = {
cups01: [
"Ace of Cups",
"Ace of cups is the card for new love, compassion, joy and creativity. If this card shows up with Ace of Pentacles it often means moving in together in a relationship.",
"Ace of Cups reversed indicates blocked creativity and blocked emotions. Access to the subconscious mind and psychic ability is also blocked."
],
cups02: [
"Two of Cups",
"Two of cups is the card for being in love and being in a close relationship, There is real intimacy in the relationship, and you know and understand each other on a deep level.",
"Two of Cups reversed indicates being afraid of love and relationship. The seeker might be dreaming of love, but when it comes down to actually having one, the fear of rejection and abandonment gets in the way."
],
cups03: [
"Three of Cups",
"Three of cups is the card for celebration, going out with friends, having a good time and being part of a community. This card often shows up when someone is getting engaged or married.",
"Three of Cups reversed can indicate celebration gone wrong, negative talk, jealousy and competition."
],
cups04: [
"Four of Cups",
"Four of cups is the card for contemplation. It often shows up when the querent is dissatisfied about something and doesn’t fully notice what they are being offered.",
"Four of Cups reversed indicates the seeker has become unseated and is avoiding something and/or someone important."
],
cups05: [
"Five of Cups",
"Five of cups is the card for regrets and disappointment, especially in love. A relationship might not have turned out the way you would have liked it to.",
"Five of Cups reversed indicates disappointment in love and emotional matters. The two cups that still upright spill out when this card shows up reversed which denotes the seeker might be emotionally totally drained, usually by relationships."
],
cups06: [
"Six of Cups",
"Six of cups is the card for sensuality and pleasure, memories, innocence, nostalgia and childhood. Sometimes this card shows up when someone from the past is on their way back into your life again.",
"Six of Cups reversed indicates a difficult childhood and haunting, even disturbing childhood memories. Memories of all kinds can be an issue when this card shows up reversed, even memory loss."
],
cups07: [
"Seven of Cups",
"Seven of cups is the card for day dreaming, illusions, wishful thinking, and fantasies. This card usually shows up when you have plenty of choices and need a vision to make them a reality.",
"Seven of Cups reversed indicates the seeker’s imagination is blocked. Daydreaming has turned into thoughts of fears and anxieties."
],
cups08: [
"Eight of Cups",
"Eight of cups is the card for turning your back at something to go and follow your dream. The day-dreaming that happened in Seven of cups has materialized in a vision that the querent is going to pursuit.",
"Eight of Cups reversed indicates the seeker has given up their dream to surrender to a reality that is uncomfortable, loveless and miserable. The seeker might have surrendered their life to please someone else, sell their business to work at a job they dislike."
],
cups09: [
"Nine of Cups",
"Nine of cups is the card for getting what you want and having a wish come true. This card speaks of abundance and satisfaction, and also about being proud of what you have achieved.",
"Nine of Cups reversed indicates that the seeker is not going to get what they wish for. Family and friendship might be falling apart. There are disintegrating and separation, often due to lifestyle choices."
],
cups10: [
"Ten of Cups",
"Ten of cups is the card for total spiritual bliss experienced in your relationship, home and family life. This card is about being in alignment with your true nature and everything in your life is in harmony with your higher self and purpose on this planet.",
"Ten of Cups reversed indicates disruption in the harmony, something or someone is making it hard to maintain the love. The seeker might be pretending everything is still wonderful in the hope that it will continue forever."
],
cupsPage: [
"Page of Cups",
"Page of cups denotes a young person with gentle and sensitive nature. This is someone who lives in wonder and can be quite naive at times.",
"Page of Cups reversed indicates, someone who is hard to motivate, they are feeling sad and bring down others with their gloomy nature. They might promise a lot, but deliver little if any."
],
cupsKnight: [
"Knight of Cups",
"Knight of cups denotes a person on a quest to declare his love. This is your knight in shining armor. He is a singer, poet, and writer. He paints and creates wherever he goes. He is artistic and incredibly lovable.",
"Knight of Cups reversed indicates a person who is walking away from a relationship and/or a creative venture. The emotional state of the seeker might be far from romantic, instead it is more likely to be cynical and use their insights and intuition to make others hurt as much as they do."
],
cupsQueen: [
"Queen of Cups",
"Queen of cups denotes a woman who is highly intuitive and sensitive. She is in touch with her emotions, her subconscious and the universe. She is compassionate and cares deeply about her life and those in it.",
"Queen of Cups reversed indicates someone with blocked psychic abilities and an emotionally unstable nature. This person might be very numb or even worse, has very dark feelings."
],
cupsKing: [
"King of Cups",
"King of cups denotes a warm, honest and generous man who is kind and fair. This is someone who is in control over his own emotions.",
"King of Cups reversed indicates someone who is blocked expressing their feelings, is unable to motivate and be motivated. This is someone with a selfish streak, often born from fear of rejection."
],
pentacles01: [
"Ace of Pentacles",
"Ace of Pentacles symbolises a new beginning in your financial situation and an opportunity to deepen your security.",
"Ace of Pentacles reversed indicates financial losses and decrease in security. There might have been anticipation in regards to increased income and wealth which are not becoming a reality."
],
pentacles02: [
"Two of Pentacles",
"Two of Pentacles symbolises juggling with finances. You might have income from more than one source. Two of Pentacles also indicates investing money into different projects, or bartering.",
"Two of Pentacles reversed indicates the seeker is unable to juggle the demands of life. He loses sight of his finances and practical aspects of life."
],
pentacles03: [
"Three of Pentacles",
"Three of Pentacles symbolises your work, especially where team work or listening to clients/customers are concerned. This is a positive card which indicates job satisfaction and taking pride in your work, but you must put in the effort to see results.",
"Three of Pentacles reversed indicates lack of quality in work performance."
],
pentacles04: [
"Four of Pentacles",
"Four of Pentacles symbolises the need for security and recognition in your life, to have control over your possession and to keep abundance and money increasing. This card shows stubbornness in the situation or in the querent.",
"Four of Pentacles reversed indicates lack of something solid and dependable. There is nothing really reliable to hold on to."
],
pentacles05: [
"Five of Pentacles",
"Five of Pentacles symbolises financial loss or hardship. It can also mean you are in a place where you feel there is no security and your health might be suffering. ",
"Five of Pentacles reversed indicates disorder and chaos. Not only is there no money, but there is also a lack of spirituality and friendship."
],
pentacles06: [
"Six of Pentacles",
"Six of Pentacles symbolises generosity towards those who has less than you. It can also mean receiving generosity from others.",
"Six of Pentacles reversed indicates a lack of generosity. There might be greediness rather than sharing of wealth."
],
pentacles07: [
"Seven of Pentacles",
"Seven of Pentacles symbolises a vision that will pay off in the future. You are planting the seeds so that you will be able to harvest a more secure and abundant future for yourself.",
"Seven of Pentacles reversed indicates impatience and moving forward before the time is ripe. This card reversed can also mean unemployment."
],
pentacles08: [
"Eight of Pentacles",
"Eight of Pentacles symbolise craftsmanship in regards to work. It can also mean doing an apprenticeship and/or learning a new skill.",
"Eight of Pentacles reversed indicates tedious work with little gains. The seeker might be overdue for a promotion they deserve but are not getting."
],
pentacles09: [
"Nine of Pentacles",
"Nine of Pentacles symbolises luxury, financial security and being on a lavish holiday.",
"Nine of Pentacles reversed indicates loneliness and unhappiness. The home is neither secure nor very comfortable. The seeker might feel like a prisoner in their own home."
],
pentacles10: [
"Ten of Pentacles",
"Ten of Pentacles symbolises the type of wealth you get when you inherit something, being it your own retirement money, hand me downs, or possessions from someone who has passes away. ",
"Ten of Pentacles reversed indicates fortunes or legacies wasted or lost, or on a lesser note, delayed. There might be restrictive ties that become a burden."
],
pentaclesPage: [
"Page of Pentacles",
"Page of Pentacles indicates reinventing yourself in some way. It often denotes an opportunity to start something new, whether it is a creative venture, studying, business or a new job offer. Page of pentacles is not yet an expert in the field of choice, but has a clear goal and dream to achieve.",
"Page of Pentacles reversed indicates issues with learning and problems with studies. It denotes wasted talents, unrealistic ambitions and/or intellectual snobbery."
],
pentaclesKnight: [
"Knight of Pentacles",
"Knight of Pentacles denotes being of service and doing the actual work (in contrast to Page of Pentacles who enjoys daydreaming about the idea rather than actual living it). Knight of Pentacles is comfortable with routine and is efficient and conservative.",
"Knight of Pentacles reversed indicates sloppiness, bitterness and envy. This is someone who is sucking up to those who can help them climb the ladder to wealth and success, but will do nothing for those who haven’t got money or connections."
],
pentaclesQueen: [
"Queen of Pentacles",
"Queen of Pentacles is someone with a down to earth and practical approach to life and situations. It is important to have work/home balance, in fact if you could work from home you probably would. This card takes enjoyment in material pleasures and success.",
"Queen of Pentacles reversed indicates poor taste and lack of sensitivity to other people’s needs."
],
pentaclesKing: [
"King of Pentacles",
"King of Pentacles symbolises a successful business man or a person in a manager position. This is a stable and authoritative character, who is hard-working and dependable.",
"King of Pentacles reversed indicates someone who is too conservative and who won’t take any chances. He is reluctant in making any changes in the way things are. He is likely to be a miser and a hoarder."
],
swords01: [
"Ace of Swords",
"Ace of swords is the card for a new thought and belief system. It is the potential of mental energy used to create clarity and often also justice.",
"Ace of Swords reversed indicates that the stirring of the aces is blocked. Ideas and communication are blocked."
],
swords02: [
"Two of Swords",
"Two of Swords is the card for compromise, passiveness, keeping the peace (as in not rocking the boat), stalemate, indecision and avoiding conflict.",
"Two of Swords reversed indicates conflicts are unavoidable and compromises are not reached. The querent might be exhibiting too much personality and creates drama just to have something to do."
],
swords03: [
"Three of Swords",
"Three of Swords denotes heartbreak. sorrow, pain and separation. Sometimes the separation is only temporary, other times it is final.",
"Three of Swords reversed indicates there is blocked grief stored in the person’s heart. The querent might be afraid of grieving and is internalising. "
],
swords04: [
"Four of Swords",
"Four of Swords is about rest and rejuvenation, getting enough sleep and taking time out to meditate.",
"Four of Swords reversed denotes restlessness and burn outs. Thoughts and beliefs interrupt the person from recuperating."
],
swords05: [
"Five of Swords",
"Five of Swords is the card for defeat and betrayal, conflict and unhealthy competition. Words will be hurtful, lies will be told and your weaknesses used against you.",
"Five of Swords reversed denotes conflict and arguments remaining unresolved, often dragging on indefinitely."
],
swords06: [
"Six of Swords",
"Six of Swords is about crossing the troubled sea and entering into calmer water. This is the card for finding solutions and implementing them, often bringing other people with you in the process, ie, your family, friends, and colleagues.",
"Six of Swords reversed indicates travel plans being held up or delayed. It also means difficulty in problem solving, especially mental tasks like maths and science."
],
swords07: [
"Seven of Swords",
"Seven of Swords denotes someone is moving forward in less than honourable ways. There is often dishonesty connected with this card, and trying to get away with something or trying to get out of something by lying.",
"Seven of Swords reversed indicates clumsiness and forgetfulness, especially when it comes to recollecting what lies have been told and to whom."
],
swords08: [
"Eight of Swords",
"Eight of Swords is the card of being stuck and unable to move on due to confusion and not knowing what is going on. Often people draw this card when their own gut feeling is being overruled by other people.",
"Eight of Swords reversed indicates a person who is unable to move forward due to self-doubts, fear, and isolation. The person knows the way forward, yet chooses to stay put, escaping in their own heads."
],
swords09: [
"Nine of Swords",
"Nine of Swords denotes worry and anxiety, sleeplessness and being overwhelmed by negative emotions such as guilt and regrets.",
"Nine of Swords reversed indicates that issues and problems have been ignored rather than dealt with and when they resurface the querent might not know how to deal with them."
],
swords10: [
"Ten of Swords",
"Ten of Swords is the card for endings and loss, backstabbing and lack of support. Sometimes this card denotes hitting rock bottom. It has the mentality of ‘when it rains it pours’, and the querent might be feeling there is no end of the suffering.",
"Ten of Swords reversed indicates a person who is holding on to pain often inflicted by others. This querent might not be able to let go of what other people have inflicted and is feeling no support. Not just is there no support, there might even be deliberate sabotage."
],
swordsPage: [
"Page of Swords",
"Page of Swords denotes a young and mentally very active and clever person. This is someone who can concentrate over long periods of time and who learns new skills easily, especially mental skills.",
"Page of Swords reversed indicates a person who lies, gossips and being a know it all. This is someone who says inappropriate things and wastes his time in chat rooms. They don’t keep secrets or promises."
],
swordsKnight: [
"Knight of Swords",
"Knight of Swords denotes a communicative, strong-minded and at times an opinionated person who is very action oriented and thrive on change. This is someone with a competitive streak and doesn’t like to let go of his/hers position in an argument.",
"Knight of Swords reversed indicates a person with a speech impediment or learning disabilities. This is someone who is intelligent but for some reason is unable to express themselves."
],
swordsQueen: [
"Queen of Swords",
"Queen of Swords denotes a woman who is cold, professional and smart. She is witty and funny in an intelligent way (no toilet humour). She often represents single women who have been hurt in love, and is bitter and hurt, but a master at covering it up.",
"Queen of Swords reversed indicates a woman who has problems with problem solving and communication. This is the type of person who will make accusations without checking the facts."
],
swordsKing: [
"King of Swords",
"King of Swords denotes a professional man who is at the top of his game. This is someone who is an expert in his field and would have had to study to acquire this knowledge.",
"King of Swords reversed indicates a man who will manipulate facts to get his own ways. There is a block when it comes to integrity and objectivity. This is someone opinionated and biased."
],
wands01: [
"Ace of Wands",
"Ace of wands speaks of new beginnings. Be bold and start something new. Follow your inspiration. Ace of Wands speaks of births of all kinds; the birth of enterprises and job opportunities, and also the birth of a baby.",
"Ace of Wands reversed indicates that new beginnings are blocked. Ideas and enterprises do not take hold and there is little if any growth."
],
wands02: [
"Two of Wands",
"Two of Wands is about manifesting using the will and strength of your mind. You might have to weigh up your options before deciding on the one that is best for you.",
"Two of Wands reversed indicates difficulties in making a decision, possibly due to the fear of making the wrong choice."
],
wands03: [
"Three of Wands",
"Three of Wands is the card for writers, and writing jobs and freelancers. It is also the card that follows the manifesting the querent did in Two of Wand, and the querent has now lived a new and exciting opportunity or dream.",
"Three of Wands reversed indicates there is a delay in rewards and a delay in a payoff. The seeker might be out of their league, unable to cope with the demands."
],
wands04: [
"Four of Wands",
"Four of Wands is the card for harmony and developing on a larger scale, often expanding your living situation, and also being stronger connected to a community.",
"Four of Wands reversed indicates the foundation not laid or not ready."
],
wands05: [
"Five of Wands",
"Five of Wands is about standing up for what is important to you, even if it means meeting some opposition.",
"Five of Wands reversed indicates loss in individuality. There is a struggle to stand out among others equally talented."
],
wands06: [
"Six of Wands",
"Six of Wands is the card for popularity, progress, victory and success, self-confidence and getting what you want.",
"Six of Wands reversed indicates not getting the rewards that are owed, success delayed of even defeat."
],
wands07: [
"Seven of Wands",
"Seven of Wands denotes being defensive and putting up barriers and boundaries. You are protecting your point of view and your position.",
"Seven of Wands reversed indicates an inability to hold your ground, especially if it is not popular. There is a lack of defending oneself."
],
wands08: [
"Eight of Wands",
"Eight of Wands speaks of swift action and progress. It often shows up when there is a visitor coming, or when the querent is visiting someone.",
"Eight of Wands reversed indicates lack of energy and slowness, and things are not moving in the right direction. There might be poor time management and delays."
],
wands09: [
"Nine of Wands",
"Nine of Wands is the card for strength, courage, resilience and endurance. Never give up and never surrender.",
"Nine of Wands reversed indicates weakness and stubbornness rather than strength and willpower. There is a waste of energy or lack of energy to save something."
],
wands10: [
"Ten of Wands",
"Ten of Wands is the card for hard work and taking on more responsibility.",
"Ten of Wands reversed indicates fear of responsibilities, and incapability to keep on top of things. The seeker might be unmotivated and ready to walk away from their duties."
],
wandsPage: [
"Page of Wands",
"Page of Wands denotes an enthusiastic young person who is eager to explore and gain life experience.",
"Ppage of wands reversedage of Wands reversed indicates a bully and a mean-tempered person who likes to show off and is demanding attention."
],
wandsKnight: [
"Knight of Wands",
"Knight of Wands denotes a person who is travelling through life at a high-speed, living life in the fast lane. This is someone who will be the life of the party.",
"Knight of Wands reversed indicates a bully who wants to win at any costs. This is someone with acting talent who can turn his charm on and off and manipulate to get his way."
],
wandsQueen: [
"Queen of Wands",
"Queen of Wands denotes a warm, kind and passionate woman. She is goal oriented and determined. She is also a metaphysic who can use her mind both to create harmony and havoc.",
"Queen of Wands reversed indicates intimidation and domination. There is a lack of faith or even worse, faith in black magic and darkness."
],
wandsKing: [
"King of Wands",
"King of Wands denotes a married man who is a natural and charismatic leader. He has entrepreneurial skills and loves to run a new and exciting project.",
"King of Wands reversed indicates dictatorship. This is someone with a god complex and a bad temper, often very violent."
],
majorFool: [
"Fool",
"Fool represents new beginning, having faith in the future, being inexperienced, not knowing what to expect, having beginners luck, improvising, believing that the Universe provides, having no strings attached, being carefree.",
"Fool reversed indicates new beginnings being blocked, the path is hidden and the querent is having difficulties seeing the world with fresh eyes."
],
majorMagician: [
"Magician",
"Magician represents your ability to communicate clearly, to ‘sell’ yourself and to be innovative. The Magician has all the tools and resources available to manifest his desired outcome, so it is a good card to get if you want to create.",
"Magician reversed indicates empty promises, false possibilities, a con man, misunderstandings and a lack of substance to make possibilities become a reality."
],
majorHighPriestess: [
"High Priestess",
"High Priestess represents secrets, mystery, intuition, wisdom, making the impossible become possible, and magic.",
"High Priestess reversed indicates blocked psychic abilities, and little to no awareness of the subconscious influence on our reality. Secrets are kept, answers are not found and instincts are wrong."
],
majorEmpress: [
"Empress",
"Empress represents feminine power, a nurturer and a family oriented person, our mother or a mother figure, abundance, femininity, fertility and the love of the home and family.",
"Empress reversed indicates neglect and a lack of attention where there should be nurturing. She can represent a mother who gives little affection and hardly any protection to her child. The child can also symbolise a project, a relationship, an enterprise, the home and a business that need attention but are instead being left unattended."
],
majorEmperor: [
"Emperor",
"Emperor represents masculine energy, the ruler, the head of the household, head of a company, organisation and communities. The Emperor is an authority figure that creates a solid foundation to build and create on.",
"Emperor reversed denotes someone with a childish streak, who is also inconsistent and unpredictable. If this card represents the querent then something is blocking the energy that gives the person authority."
],
majorHierophant: [
"Hierophant",
"Hierophant represents group consciousness, religion, your belief system, ceremony, traditions, kindness, charity, giving guidance in the form of spiritual counselling.",
"Hierophant reversed denotes prudence, silliness and hypocrisy. There are rules but no knowledge of why these rules are of importance. The ego is without guidance. There is an inflexibility in the system and in the people of the system. It can be an institution who controls information and the leaders make themselves rich while the poor remain poor."
],
majorLovers: [
"Lovers",
"Lovers represents love and relationship, soul mates, physical attractions, choices to be made, The Lovers represents doing the things that make us feel whole, being with the people who make us feel whole.",
"Lovers reversed indicates a breakup between partners, families and friends. Whatever it is, the people who split up are not creating the same magic and chemistry on their own and become less whole. Lovers reversed can also indicate a wrong choice being made."
],
majorChariot: [
"Chariot",
"Chariot represents your willpower and determination. It represents victory. The Chariot gives you the green light to charge ahead and take control in your life or an area of your life that needs your attention.",
"Chariot reversed indicates defeat and cowardice. Instead of charging ahead and taking control of the inner and outer forces, there is the feeling of giving up before you give it a go. ‘What is the use’ is the energy in Chariot reversed."
],
majorStrength: [
"Strength",
"Strength represents our courage, passions, strength, self-confidence, patience and compassion. Strength reminds us to follow our passions, to take the time to do the things that make us tick, that makes us strong within ourselves and which builds confidence and self-worth.",
"Strength reversed denotes a lack of courage, lack of passion,fear, even timidity and impatience. Weak will and lack of backbone are indicated when this card shows up reversed. The lion remains untamed, often due to a fear of standing out due to peer pressure."
],
majorHermit: [
"Hermit",
"Hermit represents spending time alone, being a lone wolf, soul-searching, seeking spiritual guidance, introspection.",
"Hermit reversed indicates isolation and paranoia. There is no insight rather there is a twisted and vicious side to the person. This also denotes someone who is very lonely and is ‘loosing’ their grip on reality due to the amount of time they spend by themselves."
],
majorWheelOfFortune: [
"Wheel of Fortune",
"Wheel of Fortune is the Big destiny card in the tarot deck. What is meant to be is meant to be. In the tarot when the Wheel of Fortune turns up, it means that the events and people in your life are in your life due to it being pre-decided by destiny.",
"Wheel of fortune reversed indicates bad luck and misfortune. Instead of hitting the top of the wheel and moving forward, you are hitting the bottom, often stagnating. The wheel might not be turning at all and much-needed change is eluding you."
],
majorJustice: [
"Justice",
"Justice represents all kinds of legal matters, the spiritual laws of truth and cause and effect. When the Justice card shows up it reminds us to be lawful and fair to achieve the best result.",
"Justice reversed denotes injustice, unfairness, imbalance. You are either getting too much or too little of what you need. Something might be preventing the energy of fairness and balance from succeeding."
],
majorHangedMan: [
"Hanged Man",
"Hanged Man represents being temporarily suspended. Life is on hold, but it serves a purpose.",
"Hanged Man reversed indicates stubbornness and selfishness, refusing to give up your perspective to gain new insight. This card reversed denotes someone who is feeling apart from the world and unable to communicate their point of view and their perspective to others."
],
majorDeath: [
"Death",
"Death represents transformation, endings and new beginnings. When the Death card shows up it tells you that things will not be the same again. A transformation is taking place, you are growing and changing with the circumstances you find yourself in.",
"Death reversed indicates that something that should have come to a blessed end for some reason persists. ‘Not death’ is not a desired thing as it is not living either. For some reason, the person is holding on. Blocked grief is often a factor."
],
majorTemperance: [
"Temperance",
"Temperance represents balanced interaction between the elements to create something new and fresh. Temperance includes all the elements in such a way that it brings out the best of each substance. When the Temperance card shows up in your life there is great balance and strength between the different areas and people in your life that are working together.",
"Temperance reversed indicates that the balance between two opposing elements to create a third goes terribly wrong. This card often shows up when two different people who could bring out the best in each other instead bring out the worst."
],
majorDevil: [
"Devil",
"Devil represents the primal source of behaviour that shows itself in the form of our desires and earthly needs. It also represents our fears that causes addiction and compulsive behaviour.",
"Devil reversed indicate temptations resisted, stricter moral kept and they escape the chains from the devil. The querent might be too restricted in their life, and they have little or no desires that drive them."
],
majorTower: [
"Tower",
"Tower represent disaster, emotional ‘meltdowns’ and/or tantrums, anger issues, upheaval, sudden change that is caused by disruption and revelations that rock the foundation of the person, household, organisation or even country, depending on the nature of the question.",
"Tower reversed denotes secrets and lies that would have brought down the false structures remain hidden and there is no shake-up. There is no destruction and the Tower remains standing."
],
majorStar: [
"Star",
"Star represents hope, a bright future, joy, optimism, guidance, having answers to your questions, being and feeling the connection to the divine, serenity and inspiration. The Star shines so brightly that when it shows up in a reading it tells you that you are being the light in someone’s life.",
"Star reversed indicates that any hope or promise offered is going to be false. There is leading astray rather than finding one’s way. There is a feeling of being lost with no way out."
],
majorMoon: [
"Moon",
"Moon represents illusions, intuition, fantasies, fears and anxiety. When the Moon appears things might not be quite as they seem. Your insecurities might be running high or you find yourself on the receiving end of other people’s insecurities.",
"Moon reversed indicates primitive forces at play, a long dark night of the soul. Intuition and creativity are blocked, a sexual block is also possible."
],
majorSun: [
"Sun",
"Sun represents success, joy, sunshine, day, warmth and happiness. The Sun shows up when life is sunny and you are enjoying your time with the people you love. Life is simple rather than complicated. Relationships are blossoming and you are feeling loved.",
"Sun reversed indicates new beginnings, success and happiness being blocked. Success is blocked due to reaching the wrong conclusions and having bad reasoning and poor logic. Things are frustrating and unclear. There might be some problems with pregnancy or raising young children."
],
majorJudgement: [
"Judgement",
"Judgement represents taking responsibility for your actions and your life, being a good judge of character, seeing the truth and knowing what you want. The Judgement card often shows up when you need to step up and be a leader, speaking the truth and being more assertive.",
"Judgement reversed indicates taken on burdens, digging oneself deeper into the old life, being haunted by the past and unable to let go. There is something blocking the querent from renewing themselves."
],
majorWorld: [
"World",
"World is the final Major Arcana card and represents fulfilment and successful completion of a cycle. You know your place in the world, and your life lessons have made you smart and accomplished. The World shows up when the world is ready for you and want what you have to offer.",
"World reversed indicates staying at home secluded within the comfort zones, projects and ventures remain incomplete. The querent is unable to finish what they started."
]
}
var json = Object.keys(old).map(key => {
var card = old[key]
var assetName = key
var name = card[0]
var description = card[1]
var reverseDescription = card[2]
return {
assetName: assetName,
name: name,
description: description,
reverseDescription: reverseDescription,
}
})
console.log(JSON.stringify(json, null, 2))
| {
"content_hash": "84aa24ed434744b12ba9ab885c7d5c4b",
"timestamp": "",
"source": "github",
"line_count": 408,
"max_line_length": 365,
"avg_line_length": 82.00490196078431,
"alnum_prop": 0.7561719170303066,
"repo_name": "mKleinCreative/acidic-duck",
"id": "2bfec127a267322bb18036ade0e65729f373ea0c",
"size": "33504",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "convert.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3140"
},
{
"name": "HTML",
"bytes": "1230"
},
{
"name": "JavaScript",
"bytes": "39358"
}
],
"symlink_target": ""
} |
package org.gluewine.console.impl;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeSet;
import org.gluewine.console.CLICommand;
import org.gluewine.console.CommandContext;
import org.gluewine.console.CommandProvider;
import org.gluewine.core.Glue;
import org.gluewine.core.RepositoryListener;
import org.gluewine.core.glue.RepositoryImpl;
/**
* CommandProvider that interacts with the repository.
*
* @author fks/Serge de Schaetzen
*
*/
public class ReposCommandProvider implements CommandProvider
{
// ===========================================================================
/**
* The object repository.
*/
@Glue
private RepositoryImpl repos = null;
// ===========================================================================
@Override
public List<CLICommand> getCommands()
{
List<CLICommand> commands = new ArrayList<CLICommand>();
commands.add(new CLICommand("repos_info", "Shows the number of registered objects and listeners in the repository."));
commands.add(new CLICommand("repos_objects", "Lists the registered objects."));
commands.add(new CLICommand("repos_listeners", "Lists the registered listeners."));
return commands;
}
// ===========================================================================
/**
* Displays the list of registered objects.
*
* @param cc The list of registered objects.
* @throws Throwable If a problem occurs.
*/
public void _repos_objects(CommandContext cc) throws Throwable
{
cc.tableHeader("Object");
for (String s : repos.getRegisteredObjects())
cc.tableRow(s);
cc.printTable();
}
// ===========================================================================
/**
* Displays the list of registered listeners.
*
* @param cc The list of registered listeners.
* @throws Throwable If a problem occurs.
*/
public void _repos_listeners(CommandContext cc) throws Throwable
{
cc.tableHeader("Listener");
Set<String> sl = new TreeSet<String>();
for (RepositoryListener<?> l : repos.getRegisteredListeners())
sl.add(l.toString());
for (String s : sl)
cc.tableRow(s);
cc.printTable();
}
// ===========================================================================
/**
* Shows the count of registered objects and listeners.
*
* @param cc The current context.
* @throws Throwable If a problem occurs.
*/
public void _repos_info(CommandContext cc) throws Throwable
{
cc.tableHeader("Type", "Amount");
int o = repos.getRegisteredObjectCount();
int l = repos.getRegisteredListenerCount();
cc.tableRow("Objects", Integer.toString(o));
cc.tableRow("Listeners", Integer.toString(l));
cc.printTable();
}
// ===========================================================================
/**
* Shows the source (jar file) of all registered objects and listeners.
*
* @param cc The current context.
* @throws Throwable If a problem occurs.
*/
public void _repos_source(CommandContext cc) throws Throwable
{
cc.tableHeader("Object", "Class", "Source");
Map<String, Object> obs = repos.getRegisteredObjectMap();
for (Entry<String, Object> e : obs.entrySet())
{
Class<?> clazz = e.getValue().getClass();
if (clazz.getName().indexOf("$$EnhancerByCGLIB$$") >= 0) clazz = clazz.getSuperclass();
String source = clazz.getProtectionDomain().getCodeSource().getLocation().getFile();
cc.tableRow(e.getKey(), clazz.getName(), source);
}
cc.printTable();
}
}
| {
"content_hash": "820a36506c91406ca57c0ff0e7dea6a3",
"timestamp": "",
"source": "github",
"line_count": 118,
"max_line_length": 126,
"avg_line_length": 33.016949152542374,
"alnum_prop": 0.5587782340862423,
"repo_name": "sergeds/Gluewine",
"id": "a381836a857a5ab097103c33b839940de31c4fc7",
"size": "4700",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "imp/src/java/org/gluewine/console/impl/ReposCommandProvider.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "6876"
},
{
"name": "CSS",
"bytes": "185"
},
{
"name": "HTML",
"bytes": "2211742"
},
{
"name": "Java",
"bytes": "939958"
},
{
"name": "Shell",
"bytes": "59784"
},
{
"name": "XSLT",
"bytes": "205334"
}
],
"symlink_target": ""
} |
DROP TABLE IF EXISTS `cot_bbcode`; | {
"content_hash": "04002729a68e5c01f2d04183ac0c5f7a",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 34,
"avg_line_length": 34,
"alnum_prop": 0.7647058823529411,
"repo_name": "Cotonti/valencia",
"id": "9494c5b00a84ce9040f932e15c02d2619598c384",
"size": "34",
"binary": false,
"copies": "11",
"ref": "refs/heads/master",
"path": "plugins/bbcode/setup/bbcode.uninstall.sql",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "125"
},
{
"name": "CSS",
"bytes": "89775"
},
{
"name": "HTML",
"bytes": "4667"
},
{
"name": "JavaScript",
"bytes": "63677"
},
{
"name": "PHP",
"bytes": "2824162"
},
{
"name": "SQLPL",
"bytes": "1573"
},
{
"name": "Smarty",
"bytes": "318865"
}
],
"symlink_target": ""
} |
require 'delegate'
module Cequel
module Model
module Collection
extend ActiveSupport::Concern
extend Forwardable
def_delegators :@model, :loaded?, :updater, :deleter
attr_reader :column_name
included do
private
define_method(
:method_missing,
BasicObject.instance_method(:method_missing))
end
def initialize(model, column_name)
@model, @column_name = model, column_name
end
def inspect
__getobj__.inspect
end
def loaded!
modifications.each { |modification| modification.() }.clear
end
def persisted!
modifications.clear
end
protected
def __getobj__
@model.__send__(:read_attribute, @column_name) ||
@model.__send__(:write_attribute, @column_name, self.class.empty)
end
def __setobj__(obj)
raise "Attempted to call __setobj__ on read-only delegate!"
end
private
def to_modify(&block)
if loaded? then block.()
else modifications << block
end
self
end
def modifications
@modifications ||= []
end
end
class List < DelegateClass(Array)
include Collection
NON_ATOMIC_MUTATORS = [
:collect!,
:delete_if,
:fill,
:flatten!,
:insert,
:keep_if,
:map!,
:pop,
:reject!,
:reverse!,
:rotate!,
:select!,
:shift,
:shuffle!,
:slice!,
:sort!,
:sort_by!,
:uniq!
]
NON_ATOMIC_MUTATORS.
each { |method| undef_method(method) if method_defined? method }
def self.empty; []; end
def []=(position, *args)
if Range === position then first, count = position.first, position.count
else first, count = position, args[-2]
end
element = args[-1]
if first < 0
raise ArgumentError,
"Bad index #{position}: CQL lists do not support negative indices"
end
if count.nil?
updater.list_replace(column_name, first, element)
else
element = Array.wrap(element)
count.times do |i|
if i < element.length
updater.list_replace(column_name, first+i, element[i])
else
deleter.list_remove_at(column_name, first+i)
end
end
end
to_modify { super }
end
def clear
deleter.delete_columns(column_name)
to_modify { super }
end
def concat(array)
updater.list_append(column_name, array)
to_modify { super }
end
def delete(object)
updater.list_remove(column_name, object)
to_modify { super }
end
def delete_at(index)
deleter.list_remove_at(column_name, index)
to_modify { super }
end
def push(object)
updater.list_append(column_name, object)
to_modify { super }
end
alias_method :<<, :push
def replace(array)
updater.set(column_name => array)
to_modify { super }
end
def unshift(*objs)
updater.list_prepend(column_name, objs.reverse)
to_modify { super }
end
end
class Set < DelegateClass(::Set)
include Collection
NON_ATOMIC_MUTATORS = [
:add?,
:collect!,
:delete?,
:delete_if,
:flatten!,
:keep_if,
:map!,
:reject!,
:select!
]
NON_ATOMIC_MUTATORS.
each { |method| undef_method(method) if method_defined? method }
def add(object)
updater.set_add(column_name, object)
to_modify { super }
end
def clear
deleter.delete_columns(column_name)
to_modify { super }
end
def delete(object)
updater.set_remove(column_name, object)
to_modify { super }
end
def replace(set)
updater.set(column_name => set)
to_modify { super }
end
end
class Map < DelegateClass(::Hash)
include Collection
NON_ATOMIC_MUTATORS = [
:default,
:default=,
:default_proc,
:default_proc=,
:delete_if,
:deep_merge!,
:except!,
:extract!,
:keep_if,
:reject!,
:reverse_merge!,
:reverse_update,
:select!,
:shift,
:slice!,
:stringify_keys!,
:symbolize_keys!,
:to_options!,
:transform_keys!
]
NON_ATOMIC_MUTATORS.
each { |method| undef_method(method) if method_defined? method }
def []=(key, value)
updater.map_update(column_name, key => value)
to_modify { super }
end
alias_method :store, :[]=
def clear
deleter.delete_columns(column_name)
to_modify { super }
end
def delete(key)
deleter.map_remove(column_name, key)
to_modify { super }
end
def merge!(hash)
updater.map_update(column_name, hash)
to_modify { super }
end
alias_method :update, :merge!
def replace(hash)
updater.set(column_name => hash)
to_modify { super }
end
end
end
end
| {
"content_hash": "63f41317e42f399ddf6d3a2ce6e2d0d5",
"timestamp": "",
"source": "github",
"line_count": 255,
"max_line_length": 80,
"avg_line_length": 20.976470588235294,
"alnum_prop": 0.5242101327350907,
"repo_name": "outoftime/cequel",
"id": "fd06f183d256cf61beced363436e0ea30e3f17db",
"size": "5349",
"binary": false,
"copies": "1",
"ref": "refs/heads/1.0",
"path": "lib/cequel/model/collection.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "319905"
}
],
"symlink_target": ""
} |
/* When AHB bus frequency is 150MHz */
#define CLOCK_TICK_RATE 38000000
| {
"content_hash": "4f0aca615ee9b642351ecbcf8587e5a2",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 38,
"avg_line_length": 18.5,
"alnum_prop": 0.7297297297297297,
"repo_name": "OLIMEX/DIY-LAPTOP",
"id": "dc5690ba975c04d9c5eca1f15fd859461fcb78e2",
"size": "445",
"binary": false,
"copies": "12350",
"ref": "refs/heads/rel3",
"path": "SOFTWARE/A64-TERES/linux-a64/arch/arm/mach-gemini/include/mach/timex.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "11134321"
},
{
"name": "Awk",
"bytes": "19031"
},
{
"name": "Batchfile",
"bytes": "8351"
},
{
"name": "C",
"bytes": "567314664"
},
{
"name": "C++",
"bytes": "490541"
},
{
"name": "CSS",
"bytes": "3924"
},
{
"name": "Classic ASP",
"bytes": "4528"
},
{
"name": "Dockerfile",
"bytes": "652"
},
{
"name": "GDB",
"bytes": "21755"
},
{
"name": "Lex",
"bytes": "55791"
},
{
"name": "M4",
"bytes": "3388"
},
{
"name": "Makefile",
"bytes": "2068526"
},
{
"name": "PHP",
"bytes": "54081"
},
{
"name": "Perl",
"bytes": "701416"
},
{
"name": "Python",
"bytes": "307470"
},
{
"name": "Raku",
"bytes": "3727"
},
{
"name": "Roff",
"bytes": "63487"
},
{
"name": "Scilab",
"bytes": "21433"
},
{
"name": "Shell",
"bytes": "328623"
},
{
"name": "SmPL",
"bytes": "69316"
},
{
"name": "Tcl",
"bytes": "967"
},
{
"name": "UnrealScript",
"bytes": "6113"
},
{
"name": "XS",
"bytes": "1240"
},
{
"name": "XSLT",
"bytes": "445"
},
{
"name": "Yacc",
"bytes": "101755"
},
{
"name": "sed",
"bytes": "3126"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "0311cdfd8983c4566f3e4b67d5ef464c",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "a9359a04bb2963fda8b7d45f71f810416dc061cb",
"size": "172",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Lamiaceae/Nosema/Nosema capitatum/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
"""Disallow seconds in durations
Revision ID: 178d297eae7e
Revises: cf9e1b4e2f5f
Create Date: 2021-05-27 13:14:59.253773
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = '178d297eae7e'
down_revision = 'cf9e1b4e2f5f'
branch_labels = None
depends_on = None
def upgrade():
op.execute('''
UPDATE events.contributions SET duration = date_trunc('minute', duration) WHERE date_trunc('minute', duration) != duration;
UPDATE events.subcontributions SET duration = date_trunc('minute', duration) WHERE date_trunc('minute', duration) != duration;
UPDATE events.breaks SET duration = date_trunc('minute', duration) WHERE date_trunc('minute', duration) != duration;
UPDATE events.session_blocks SET duration = date_trunc('minute', duration) WHERE date_trunc('minute', duration) != duration;
UPDATE events.sessions SET default_contribution_duration = date_trunc('minute', default_contribution_duration) WHERE date_trunc('minute', default_contribution_duration) != default_contribution_duration;
''')
# force execution of trigger events
op.execute('SET CONSTRAINTS ALL IMMEDIATE')
op.create_check_constraint(
'duration_no_seconds',
'breaks',
"date_trunc('minute', duration) = duration",
schema='events'
)
op.create_check_constraint(
'duration_no_seconds',
'contributions',
"date_trunc('minute', duration) = duration",
schema='events'
)
op.create_check_constraint(
'duration_no_seconds',
'session_blocks',
"date_trunc('minute', duration) = duration",
schema='events'
)
op.create_check_constraint(
'duration_no_seconds',
'subcontributions',
"date_trunc('minute', duration) = duration",
schema='events'
)
op.create_check_constraint(
'default_contribution_duration_no_seconds',
'sessions',
"date_trunc('minute', default_contribution_duration) = default_contribution_duration",
schema='events'
)
def downgrade():
op.drop_constraint('ck_breaks_duration_no_seconds', 'breaks', schema='events')
op.drop_constraint('ck_contributions_duration_no_seconds', 'contributions', schema='events')
op.drop_constraint('ck_session_blocks_duration_no_seconds', 'session_blocks', schema='events')
op.drop_constraint('ck_subcontributions_duration_no_seconds', 'subcontributions', schema='events')
op.drop_constraint('ck_sessions_default_contribution_duration_no_seconds', 'sessions', schema='events')
| {
"content_hash": "e22d4e08cb1e6695edf94d89527eb8bb",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 210,
"avg_line_length": 38.492537313432834,
"alnum_prop": 0.6793330748352074,
"repo_name": "ThiefMaster/indico",
"id": "71e9328684c4b474ab09b2edfe27bda9521e0577",
"size": "2579",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "indico/migrations/versions/20210527_1314_178d297eae7e_disallow_seconds_in_durations.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "34704"
},
{
"name": "HTML",
"bytes": "1411006"
},
{
"name": "JavaScript",
"bytes": "2083786"
},
{
"name": "Mako",
"bytes": "1527"
},
{
"name": "Python",
"bytes": "5133951"
},
{
"name": "SCSS",
"bytes": "476568"
},
{
"name": "Shell",
"bytes": "3877"
},
{
"name": "TeX",
"bytes": "23327"
},
{
"name": "XSLT",
"bytes": "1504"
}
],
"symlink_target": ""
} |
<?xml version="1.0"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<metainfo>
<schemaVersion>2.0</schemaVersion>
<services>
<service>
<name>AMBARI_METRICS</name>
<displayName>Ambari Metrics</displayName>
<version>1.0</version>
<comment>A system for metrics collection that provides storage and retrieval capability for metrics collected from the cluster
</comment>
<components>
<component>
<name>METRICS_COLLECTOR</name>
<displayName>Metrics Collector</displayName>
<category>MASTER</category>
<cardinality>1</cardinality>
<versionAdvertised>false</versionAdvertised>
<dependencies>
<dependency>
<name>ZOOKEEPER/ZOOKEEPER_SERVER</name>
<scope>cluster</scope>
<auto-deploy>
<enabled>true</enabled>
</auto-deploy>
</dependency>
</dependencies>
<commandScript>
<script>scripts/metrics_collector.py</script>
<scriptType>PYTHON</scriptType>
<timeout>1200</timeout>
</commandScript>
</component>
<component>
<name>METRICS_MONITOR</name>
<displayName>Metrics Monitor</displayName>
<category>SLAVE</category>
<cardinality>ALL</cardinality>
<versionAdvertised>false</versionAdvertised>
<auto-deploy>
<enabled>true</enabled>
</auto-deploy>
<commandScript>
<script>scripts/metrics_monitor.py</script>
<scriptType>PYTHON</scriptType>
<timeout>1200</timeout>
</commandScript>
</component>
</components>
<osSpecifics>
<osSpecific>
<osFamily>redhat5,redhat6,suse11</osFamily>
<packages>
<package>
<name>ambari-metrics-collector</name>
</package>
<package>
<name>ambari-metrics-monitor</name>
</package>
<package>
<name>ambari-metrics-hadoop-sink</name>
</package>
<package>
<name>gcc</name>
</package>
</packages>
</osSpecific>
<osSpecific>
<osFamily>ubuntu12</osFamily>
<packages>
<package>
<name>ambari-metrics-assembly</name>
</package>
<package>
<name>gcc</name>
</package>
</packages>
</osSpecific>
<osSpecific>
<osFamily>winsrv6</osFamily>
<packages>
<package>
<name>ambari-metrics-collector.msi</name>
</package>
<package>
<name>ambari-metrics-monitor.msi</name>
</package>
<package>
<name>ambari-metrics-hadoop-sink.msi</name>
</package>
</packages>
</osSpecific>
</osSpecifics>
<commandScript>
<script>scripts/service_check.py</script>
<scriptType>PYTHON</scriptType>
<timeout>300</timeout>
</commandScript>
<requiredServices>
<service>ZOOKEEPER</service>
</requiredServices>
<configuration-dependencies>
<config-type>ams-site</config-type>
<config-type>ams-log4j</config-type>
<config-type>ams-hbase-policy</config-type>
<config-type>ams-hbase-site</config-type>
<config-type>ams-hbase-security-site</config-type>
<config-type>ams-hbase-env</config-type>
<config-type>ams-hbase-log4j</config-type>
</configuration-dependencies>
</service>
</services>
</metainfo>
| {
"content_hash": "601a5b4f7af459cf600002a76e0a7259",
"timestamp": "",
"source": "github",
"line_count": 133,
"max_line_length": 132,
"avg_line_length": 33.69924812030075,
"alnum_prop": 0.5834448906738063,
"repo_name": "sekikn/ambari",
"id": "aea1252e4af4f4e97a07dc25fcc5c3c798e6d07b",
"size": "4482",
"binary": false,
"copies": "5",
"ref": "refs/heads/trunk",
"path": "ambari-server/src/test/resources/stacks/HDP/2.1.1/services/AMBARI_METRICS/metainfo.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "22734"
},
{
"name": "C",
"bytes": "109499"
},
{
"name": "C#",
"bytes": "182799"
},
{
"name": "CSS",
"bytes": "616806"
},
{
"name": "CoffeeScript",
"bytes": "4323"
},
{
"name": "Dockerfile",
"bytes": "8117"
},
{
"name": "HTML",
"bytes": "3725781"
},
{
"name": "Handlebars",
"bytes": "1594385"
},
{
"name": "Java",
"bytes": "26670585"
},
{
"name": "JavaScript",
"bytes": "14647486"
},
{
"name": "Jinja",
"bytes": "147938"
},
{
"name": "Less",
"bytes": "303080"
},
{
"name": "Makefile",
"bytes": "2407"
},
{
"name": "PHP",
"bytes": "149648"
},
{
"name": "PLpgSQL",
"bytes": "298247"
},
{
"name": "PowerShell",
"bytes": "2047735"
},
{
"name": "Python",
"bytes": "7226684"
},
{
"name": "R",
"bytes": "1457"
},
{
"name": "Shell",
"bytes": "350773"
},
{
"name": "TSQL",
"bytes": "42351"
},
{
"name": "Vim Script",
"bytes": "5813"
},
{
"name": "sed",
"bytes": "1133"
}
],
"symlink_target": ""
} |
require 'brazenhead/version'
require 'brazenhead/device'
require 'brazenhead/request'
require 'brazenhead/call_accumulator'
require 'brazenhead/server'
require 'brazenhead/core_ext/string'
require 'brazenhead/environment'
module Brazenhead
def method_missing(method, *args)
call_method_on_driver(method.to_s.to_java_call, args)
end
def chain_calls(&block)
accumulator.clear
block.call accumulator
@last_response = device.send(accumulator.message)
@last_response
end
def last_response
@last_response
end
def last_json
device.last_json
end
private
def call_method_on_driver(method, args)
message = request.build(method, args)
@last_response = device.send(message)
@last_response
end
def device
@device ||= Brazenhead::Device.new
end
def request
@request ||= Brazenhead::Request.new
end
def accumulator
@accumulator ||= Brazenhead::CallAccumulator.new
end
end
| {
"content_hash": "60496aa1fe7858205d0c35b037e45684",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 57,
"avg_line_length": 19.833333333333332,
"alnum_prop": 0.7184873949579832,
"repo_name": "leandog/brazenhead",
"id": "58f0b3701438c9b53797c23d84a3a5aa8a985267",
"size": "952",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/brazenhead.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "80086"
},
{
"name": "Ruby",
"bytes": "47179"
},
{
"name": "Shell",
"bytes": "233"
}
],
"symlink_target": ""
} |
(function(angular) {
"use strict";
angular.module("WidgetApp", [])
.controller("HomeCtrl", function($scope) {
function doSomething() {
console.dir(this);
}
doSomething();
var o = {
id: 2,
doSomething: doSomething
};
o.doSomething();
console.log(doSomething === o.doSomething);
var p = {
name: "Abdulaziz",
doSomething: doSomething
};
var c = Object.create(p);
c.name = "Khalid";
c.doSomething();
p.doSomething();
console.dir(c);
console.log(c.doSomething === p.doSomething);
var g = {
getFullName: function() {
}
}
});
})(angular);
| {
"content_hash": "8359a697723f651a691d1186eb341038",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 48,
"avg_line_length": 12.74,
"alnum_prop": 0.5667189952904239,
"repo_name": "training4developers/angular_03062015",
"id": "f7bd5ad88d849f580942432c03cb2a5b02041e19",
"size": "637",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "start/www/js/site_value_this.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2"
},
{
"name": "HTML",
"bytes": "17110"
},
{
"name": "JavaScript",
"bytes": "270464"
},
{
"name": "Smarty",
"bytes": "1705"
}
],
"symlink_target": ""
} |
#include "berryQtViewPart.h"
namespace berry
{
void QtViewPart::CreatePartControl(QWidget* parent)
{
this->CreateQtPartControl(static_cast<QWidget*>(parent));
}
}
| {
"content_hash": "42c32a4c05c9e418f7f6c21be772e2dd",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 59,
"avg_line_length": 13.076923076923077,
"alnum_prop": 0.7470588235294118,
"repo_name": "NifTK/MITK",
"id": "ade1706091c595ed74b23280584661256d02c6aa",
"size": "640",
"binary": false,
"copies": "10",
"ref": "refs/heads/niftk",
"path": "Plugins/org.blueberry.ui.qt/src/berryQtViewPart.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "2343401"
},
{
"name": "C++",
"bytes": "28797565"
},
{
"name": "CMake",
"bytes": "864932"
},
{
"name": "CSS",
"bytes": "117579"
},
{
"name": "HTML",
"bytes": "101835"
},
{
"name": "JavaScript",
"bytes": "167070"
},
{
"name": "Makefile",
"bytes": "25077"
},
{
"name": "Objective-C",
"bytes": "476388"
},
{
"name": "Python",
"bytes": "62916"
},
{
"name": "QMake",
"bytes": "5583"
},
{
"name": "Shell",
"bytes": "1261"
}
],
"symlink_target": ""
} |
title: Data Platforms Integration
tags: [integrations list]
permalink: dataplatforms.html
summary: Learn about the Wavefront Data Platforms Integration.
---
## Data Platforms Blueprints Integration
[Data Platform Blueprints available on the Bitnami catalog](https://bitnami.com/stack) provide you with fully automated deployment of your data platform, comprising of different combinations of software stacks on a Kubernetes cluster. The blueprints are validated and tested with engineered values of pod resources, such as CPU, Memory, and JVM, along with pod affinity and anti-affinity rules to provide recommended Kubernetes node count and associated node size and to facilitate cloud platform capacity planning.
This integration allows you to monitor different Data Platform Blueprints running in different Kubernetes clusters.
If you have already deployed the Data Platform Blueprint enabling Tanzu Observability by Wavefront Framework, this integration works out of the box. Otherwise, ensure that you deploy the data platform blueprint enabling Tanzu Observability by Wavefront Framework to trigger metrics ingestion to Wavefront.
Use the Blueprint-specific links below to enable metrics ingestion to Tanzu Observability by Wavefront. The data ingestion is done by using Wavefront Collectors.
[Data Platform Blueprint1 - Kafka-Spark-Solr](https://github.com/bitnami/charts/tree/master/bitnami/dataplatform-bp1#tanzu-observability-wavefront-chart-parameters)
[Data Platform Blueprint2 - Kafka-Spark-Elasticsearch](https://github.com/bitnami/charts/tree/master/bitnami/dataplatform-bp2#tanzu-observability-wavefront-parameters)
The image below is a sample of the Kafka-Spark-Solr Blueprint dashboard, that is provided as part of this integration. Some important sections in the dashboard are:
1. ***Mission Control***: This is the mission critical section that displays the high-level health and utilization of your data platform.
2. ***Data Platforms***: This section gives you a single shot view of the applications that form the data platform cluster together with their individual resource utilization.
3. ***ESXi Host***: This section gives you an overview of the ESXi Hosts underlying the Kubernetes cluster. It is rendered only when the ESXi metrics are flowing to Tanzu Observability.
4. ***Kubernetes Platform***: This section gives you a detailed overview of the underlying Kubernetes cluster and the Node to Pod mapping of the applications.
5. ***Individual Applications***: This section gives you a detailed view of the individual application metrics.
{% include image.md src="images/dashboard.png" width="80" %}
### Data Platform Blueprints Setup
Make sure "Bitnami Data Platform Blueprints" with Tanzu observability are deployed on your cluster. If not, follow the [Data Platforms Blueprint specific instructions on the Bitnami Catalog](https://bitnami.com/stacks) to enable observability for your data platform cluster running on Kubernetes cluster.
Use the Blueprint-specific links below to enable metrics ingestion to Tanzu Observability by Wavefront. The data ingestion is done by using Wavefront Collectors.
[Data Platform Blueprint1 - Kafka-Spark-Solr](https://github.com/bitnami/charts/tree/master/bitnami/dataplatform-bp1#tanzu-observability-wavefront-chart-parameters)
[Data Platform Blueprint2 - Kafka-Spark-Elasticsearch](https://github.com/bitnami/charts/tree/master/bitnami/dataplatform-bp2#tanzu-observability-wavefront-parameters)
See [Wavefront Collector for Kubernetes](https://github.com/wavefrontHQ/wavefront-collector-for-kubernetes) for more details about the Wavefront Collector.
### For using an existing Tanzu observibility deployment
- To enable the annotation discovery feature in wavefront for the existing wavefront deployment, make sure that auto discovery `enableDiscovery: true` and annotation based discovery `discovery.disable_annotation_discovery: false` are enabled in the Wavefront Collector ConfigMap. They should be enabled by default.
**NOTE**: The Wavefront Collector scrapes all the pods that have Prometheus annotation enabled.
See [annotation based discovery](https://github.com/wavefrontHQ/wavefront-collector-for-kubernetes/blob/main/docs/discovery.md#annotation-based-discovery) feature in Wavefront Collector for more information.
- If you wish not to use the annotation based discovery feature in wavefront, edit the Wavefront Collector ConfigMap To add rules based discovery to wavefront, add the following snippet under discovery plugins. Once done, restart the wavefront collectors DaemonSet.
{% raw %}
```console
$ kubectl edit configmap wavefront-collector-config -n wavefront
```
{% endraw %}
Add the below config:
{% raw %}
```yaml
discovery:
enable_runtime_plugins: true
plugins:
## auto-discover kafka-exporter
- name: kafka-discovery
type: prometheus
selectors:
images:
- '*bitnami/kafka-exporter*'
port: 9308
path: /metrics
scheme: http
prefix: kafka.
## auto-discover jmx exporter
- name: kafka-jmx-discovery
type: prometheus
selectors:
images:
- '*bitnami/jmx-exporter*'
port: 5556
path: /metrics
scheme: http
prefix: kafkajmx.
## auto-discover solr
- name: solr-discovery
type: prometheus
selectors:
images:
- '*bitnami/solr*'
port: 9983
path: /metrics
scheme: http
## auto-discover spark
- name: spark-worker-discovery
type: prometheus
selectors:
images:
- '*bitnami/spark*'
port: 8081
path: /metrics/
scheme: http
prefix: spark.
## auto-discover spark
- name: spark-master-discovery
type: prometheus
selectors:
images:
- '*bitnami/spark*'
port: 8080
path: /metrics/
scheme: http
prefix: spark.
```
{% endraw %}
Below is the command to restart the DaemonSets
{% raw %}
```console
$ kubectl rollout restart daemonsets wavefront-collector -n wavefront
```
{% endraw %}
Once you enable metrics ingestion into Tanzu Observability by Wavefront, the Wavefront Collector pods will collect the metrics from the individual applications of your data platform and will push them through the Wavefront proxy to your Wavefront environment.
Within a minute, you will be able to use the dashboards listed on the *Dashboards* tab, and see our default metrics sent from any Data Platform clusters created in that Kubernetes cluster.
## Metrics
### Kafka Metrics
|Metric Name|Description|
| :--- | :--- |
|kafkajmx.jmx.exporter.build.info||
|kafkajmx.jmx.config.reload.failure.total||
|kafkajmx.kafka.server.brokertopicmetrics.total.invalidoffsetorsequencerecordspersec.count||
|kafka.server.replicamanager.total.underreplicatedpartitions.value||
|kafka.server.fetchsessioncache.total.numincrementalfetchpartitionscached.value||
|kafkajmx.java.lang.operatingsystem.committedvirtualmemorysize||
|kafkajmx.kafka.controller.controllerstats.topicdeletionrateandtimems.count||
|kafkajmx.java.lang.memory.objectpendingfinalizationcount||
|kafkajmx.kafka.server.brokertopicmetrics.total.totalfetchrequestspersec.oneminuterate||
|kafkajmx.kafka.server.delayedoperationpurgatory.numdelayedoperations.produce.value||
|kafkajmx.java.lang.operatingsystem.systemcpuload||
|kafkajmx.kafka.server.brokertopicmetrics.total.messagesinpersec.count||
|kafkajmx.kafka.controller.controllerchannelmanager.totalqueuesize.value||
|kafkajmx.kafka.server.brokertopicmetrics.total.totalproducerequestspersec.oneminuterate||
|kafkajmx.kafka.controller.controllerstats.leaderandisrresponsereceivedrateandtimems.count||
|kafkajmx.java.lang.operatingsystem.availableprocessors||
|kafkajmx.kafka.server.brokertopicmetrics.total.failedfetchrequestspersec.oneminuterate||
|kafkajmx.kafka.controller.controllerstats.partitionreassignmentrateandtimems.count||
|kafkajmx.kafka.controller.kafkacontroller.activecontrollercount.value||
|kafkajmx.kafka.server.brokertopicmetrics.total.replicationbytesoutpersec.count||
|kafkajmx.kafka.server.delayedoperationpurgatory.numdelayedoperations.topic.value||
|kafkajmx.java.lang.threading.threadcputimeenabled||
|kafkajmx.kafka.server.request.queue.size||
|kafkajmx.kafka.server.kafkaserver.total.linux.disk.write.bytes.value||
|kafkajmx.kafka.server.sessionexpirelistener.total.zookeeperdisconnectspersec.oneminuterate||
|kafkajmx.java.lang.operatingsystem.totalphysicalmemorysize||
|kafkajmx.kafka.server.brokertopicmetrics.total.bytesoutpersec.count||
|kafkajmx.java.lang.threading.daemonthreadcount||
|kafkajmx.kafka.server.delayedoperationpurgatory.purgatorysize.fetch.value||
|kafkajmx.kafka.controller.controllerstats.controllershutdownrateandtimems.count||
|kafkajmx.java.lang.threading.currentthreadusertime||
|kafkajmx.kafka.server.replicafetchermanager.failedpartitionscount.value||
|kafkajmx.kafka.server.fetchsessioncache.total.incrementalfetchsessionevictionspersec.count||
|kafkajmx.kafka.controller.controllerstats.logdirchangerateandtimems.count||
|kafkajmx.java.lang.threading.synchronizerusagesupported||
|kafkajmx.kafka.controller.kafkacontroller.replicasineligibletodeletecount.value||
|kafkajmx.java.lang.memory.nonheapmemoryusage.committed||
|kafkajmx.kafka.server.fetchsessioncache.total.numincrementalfetchsessions.value||
|kafkajmx.kafka.server.sessionexpirelistener.total.zookeeperauthfailurespersec.oneminuterate||
|kafkajmx.kafka.server.replicamanager.total.underminisrpartitioncount.value||
|kafkajmx.kafka.server.produce.queue.size||
|kafkajmx.kafka.server.brokertopicmetrics.total.replicationbytesinpersec.count||
|kafkajmx.kafka.server.brokertopicmetrics.total.fetchmessageconversionspersec.oneminuterate||
|kafkajmx.java.lang.operatingsystem.processcputime||
|kafkajmx.kafka.server.brokertopicmetrics.total.invalidmagicnumberrecordspersec.oneminuterate||
|kafkajmx.kafka.server.replicamanager.total.offlinereplicacount.value||
|kafkajmx.java.lang.compilation.totalcompilationtime||
|kafkajmx.java.lang.memory.heapmemoryusage.used||
|kafkajmx.java.lang.threading.threadallocatedmemorysupported1||
|kafkajmx.kafka.controller.controllerstats.topicchangerateandtimems.count||
|kafkajmx.kafka.server.brokertopicmetrics.total.bytesrejectedpersec.count||
|kafkajmx.kafka.server.brokertopicmetrics.total.bytesinpersec.count||
|kafkajmx.java.lang.classloading.unloadedclasscount||
|kafkajmx.kafka.controller.controllerstats.leaderelectionrateandtimems.count||
|kafkajmx.kafka.controller.controllerstats.controlledshutdownrateandtimems.count||
|kafkajmx.kafka.server.brokertopicmetrics.total.failedfetchrequestspersec.count||
|kafkajmx.kafka.server.fetchsessioncache.total.incrementalfetchsessionevictionspersec.oneminuterate||
|kafkajmx.kafka.server.delayedoperationpurgatory.numdelayedoperations.fetch.value||
|kafkajmx.kafka.server.brokertopicmetrics.total.invalidmessagecrcrecordspersec.oneminuterate||
|kafkajmx.kafka.server.sessionexpirelistener.total.zookeeperreadonlyconnectspersec.count||
|kafkajmx.kafka.server.replicamanager.total.leadercount.value||
|kafkajmx.kafka.controller.controllerstats.uncleanleaderelectionenablerateandtimems.count||
|kafkajmx.java.lang.classloading.totalloadedclasscount||
|kafkajmx.kafka.controller.kafkacontroller.topicsineligibletodeletecount.value||
|kafkajmx.kafka.server.delayedoperationpurgatory.numdelayedoperations.deleterecords.value||
|kafkajmx.kafka.server.brokertopicmetrics.total.replicationbytesinpersec.oneminuterate||
|kafkajmx.kafka.server.brokertopicmetrics.total.nokeycompactedtopicrecordspersec.oneminuterate||
|kafkajmx.java.lang.operatingsystem.maxfiledescriptorcount||
|kafkajmx.kafka.server.brokertopicmetrics.total.bytesinpersec.oneminuterate||
|kafkajmx.kafka.server.replicafetchermanager.maxlag.value||
|kafkajmx.java.lang.threading.peakthreadcount||
|kafkajmx.kafka.server.brokertopicmetrics.total.replicationbytesoutpersec.oneminuterate||
|kafkajmx.java.lang.classloading.loadedclasscount||
|kafkajmx.kafka.server.brokertopicmetrics.total.reassignmentbytesinpersec.count||
|kafkajmx.kafka.controller.controllerstats.controllerchangerateandtimems.count||
|kafkajmx.java.lang.operatingsystem.freephysicalmemorysize||
|kafkajmx.java.lang.runtime.pid||
|kafkajmx.kafka.server.kafkaserver.total.brokerstate.value.value||
|kafkajmx.kafka.server.delayedoperationpurgatory.purgatorysize.electleader.value||
|kafkajmx.java.lang.threading.currentthreadallocatedbytes||
|kafkajmx.kafka.server.delayedoperationpurgatory.purgatorysize.deleterecords.value||
|kafkajmx.kafka.server.fetch.queue.size||
|kafkajmx.kafka.controller.controllerstats.updatefeaturesrateandtimems.count||
|kafkajmx.kafka.controller.kafkacontroller.globalpartitioncount.value||
|kafkajmx.kafka.server.controllermutation.queue.size||
|kafkajmx.kafka.server.sessionexpirelistener.total.zookeeperauthfailurespersec.count||
|kafkajmx.kafka.server.brokertopicmetrics.total.invalidmagicnumberrecordspersec.count||
|kafkajmx.kafka.network.processor.idlepercent.value||
|kafkajmx.kafka.controller.controllerstats.uncleanleaderelectionspersec.count||
|kafkajmx.kafka.server.replicamanager.total.atminisrpartitioncount.value||
|kafkajmx.kafka.server.brokertopicmetrics.total.reassignmentbytesoutpersec.oneminuterate||
|kafkajmx.java.lang.runtime.uptime||
|kafkajmx.kafka.server.replicaalterlogdirsmanager.total.maxlag.clientid.replicaalterlogdirs.value||
|kafkajmx.kafka.network.requestmetrics.requestspersec.count||
|kafkajmx.kafka.server.delayedoperationpurgatory.purgatorysize.topic.value||
|kafkajmx.kafka.controller.kafkacontroller.controllerstate.value||
|kafkajmx.java.lang.memory.nonheapmemoryusage.init||
|kafkajmx.kafka.server.replicamanager.total.isrshrinkspersec.oneminuterate||
|kafkajmx.kafka.server.brokertopicmetrics.total.bytesrejectedpersec.oneminuterat||
|kafkajmx.java.lang.operatingsystem.systemloadaverage||
|kafkajmx.java.lang.threading.objectmonitorusagesupported||
|kafkajmx.kafkajmx.kafka.server.kafkaserver.total.linux.disk.read.bytes.value||
|kafkajmx.kafkajmx.kafka.server.delayedoperationpurgatory.numdelayedoperations.heartbeat.value||
|kafkajmx.kafka.server.replicamanager.total.isrexpandspersec.oneminuterate||
|kafkajmx.kafka.server.delayedoperationpurgatory.purgatorysize.rebalance.value||
|kafkajmx.kafka.server.brokertopicmetrics.total.invalidoffsetorsequencerecordspersec.oneminuterate||
|kafkajmx.kafka.server.sessionexpirelistener.total.zookeepersyncconnectspersec.oneminuterate||
|kafkajmx.kafkajmx.java.lang.threading.threadcontentionmonitoringsupported||
|kafkajmx.kafka.server.brokertopicmetrics.total.producemessageconversionspersec.count||
|kafkajmx.java.lang.memory.nonheapmemoryusage.max||
|kafkajmx.kafka.server.brokertopicmetrics.total.failedproducerequestspersec.oneminuterate||
|kafkajmx.kafka.server.brokertopicmetrics.total.invalidmessagecrcrecordspersec.count||
|kafkajmx.kafka.server.sessionexpirelistener.total.zookeeperexpirespersec.count||
|kafkajmx.java.lang.threading.currentthreadcputim||
|kafkajmx.kafka.controller.controllerstats.listpartitionreassignmentrateandtimems.count||
|kafkajmx.java.lang.memory.heapmemoryusage.committed||
|kafkajmx.java.lang.threading.threadcputimesupported||
|kafkajmx.java.lang.operatingsystem.processcpuload||
|kafkajmx.kafka.server.replicamanager.total.reassigningpartitions.value||
|kafkajmx.kafka.server.kafkaserver.total.yammer.metrics.count.value||
|kafkajmx.kafka.server.delayedoperationpurgatory.purgatorysize.heartbeat.value||
|kafkajmx.kafka.server.delayedoperationpurgatory.numdelayedoperations.alteracls.valu||
|kafkajmx.kafka.server.brokertopicmetrics.total.totalfetchrequestspersec.count||
|kafkajmx.kafka.server.brokertopicmetrics.total.messagesinpersec.oneminuterate||
|kafkajmx.kafka.controller.kafkacontroller.offlinepartitionscount.value||
|kafkajmx.kafka.server.delayedoperationpurgatory.purgatorysize.alteracls.value||
|kafkajmx.kafka.server.kafkarequesthandlerpool.total.requesthandleravgidlepercent.count||
|kafkajmx.kafka.server.delayedoperationpurgatory.purgatorysize.produce.value||
|kafkajmx.kafka.server.brokertopicmetrics.total.producemessageconversionspersec.oneminuterate||
|kafkajmx.kafka.controller.kafkacontroller.globaltopiccount.value||
|kafkajmx.kafka.server.replicaalterlogdirsmanager.total.deadthreadcount.clientid.replicaalterlogdirs.value||
|kafkajmx.kafka.server.delayedoperationpurgatory.numdelayedoperations.electleader.value||
|kube.kafkajmxj.ava.lang.operatingsystem.totalswapspacesize||
|kafkajmx.kafka.server.replicaalterlogdirsmanager.total.minfetchrate.clientid.replicaalterlogdirs.value||
|kafkajmx.java.lang.memory.verbose||
|kafkajmx.kafka.server.sessionexpirelistener.total.zookeeperexpirespersec.oneminuterate||
|kafkajmx.java.lang.threading.threadallocatedmemoryenabled||
|kafkajmx.kafka.server.replicafetchermanager.deadthreadcount.value||
|kafkajmx.java.lang.threading.totalstartedthreadcount||
|kafkajmx.kafka.controller.kafkacontroller.topicstodeletecount.value||
|kafkajmx.kafka.server.replicamanager.total.failedisrupdatespersec.count||
|kafkajmx.kafka.server.zookeeperclientmetrics.total.zookeeperrequestlatencyms.count||
|kafkajmx.kafka.server.replicafetchermanager.minfetchrate.value{client.id="Replica",}||
|kafkajmx.kafka.server.replicamanager.total.partitioncount.value||
|kafkajmx.java.lang.memory.nonheapmemoryusage.used||
|kafkajmx.java.lang.classloading.verbose||
|kafkajmx.java.lang.runtime.bootclasspathsupported||
|kafkajmx.java.lang.operatingsystem.openfiledescriptorcount||
|kafkajmx.kafka.controller.kafkacontroller.replicastodeletecount.value||
|kafkajmx.kafka.controller.controllerstats.isrchangerateandtimems.count||
|kafkajmx.kafka.controller.kafkacontroller.preferredreplicaimbalancecount.value||
|kafkajmx.kafka.server.brokertopicmetrics.total.fetchmessageconversionspersec.count||
|kafkajmx.java.lang.memorkafkajmx.y.heapmemoryusage.max||
|kafkajmx.kafka.controller.controllerstats.autoleaderbalancerateandtimems.count||
|kafka.controller.controllerstats.topicuncleanleaderelectionenablerateandtimems.count||
|kafkajmx.kafka.server.replicaalterlogdirsmanager.total.failedpartitionscount.clientid.replicaalterlogdirs.value||
|kafkajmx.kafka.server.sessionexpirelistener.total.zookeepersaslauthenticationspersec.oneminuterate||
|kafkajmx.kafka.server.brokertopicmetrics.total.reassignmentbytesoutpersec.count||
|kafkajmx.java.lang.runtime.starttime||
|kafkajmx.kafka.server.brokertopicmetrics.total.nokeycompactedtopicrecordspersec.count||
|kafkajmx.java.lang.compilation.compilationtimemonitoringsupported||
|kafkajmx.kafka.server.brokertopicmetrics.total.totalproducerequestspersec.count||
|kafkajmx.java.lang.threading.threadcontentionmonitoringenabled||
|kafkajmx.java.lang.memory.heapmemoryusage.init||
|kafkajmx.kafka.server.sessionexpirelistener.total.zookeepersaslauthenticationspersec.count||
|kafkajmx.kafka.server.delayedoperationpurgatory.numdelayedoperations.rebalance.value||
|kafkajmx.kafka.server.replicamanager.total.failedisrupdatespersec.oneminuterate||
|kafkajmx.kafka.server.brokertopicmetrics.total.reassignmentbytesinpersec.oneminuterate||
|kafkajmx.kafka.server.kafkarequesthandlerpool.total.requesthandleravgidlepercent.oneminuterate||
|kafkajmx.java.lang.threading.threadcount||
|kafkajmx.kafka.server.sessionexpirelistener.total.zookeepersyncconnectspersec.count||
|kafkajmx.kafka.server.brokertopicmetrics.total.bytesoutpersec.oneminuterate||
|kafkajmx.java.lang.operatingsystem.freeswapspacesize||
|kafkajmx.kafka.server.replicamanager.total.isrexpandspersec.count||
|kafkajmx.java.lang.threading.currentthreadcputimesupported||
|kafkajmx.kafka.server.sessionexpirelistener.total.zookeeperreadonlyconnectspersec.oneminuterate||
|kafkajmx.kafka.server.sessionexpirelistener.total.zookeeperdisconnectspersec.count||
|kafkajmx.kafka.controller.controllerstats.manualleaderbalancerateandtimems.count||
|kafkajmx.jmx.scrape.duration.seconds||
|kafkajmx.jmx.scrape.error||
|kafkajmx.jmx.scrape.cached.beans||
|kafkajmx.jmx.config.reload.success.total||
|kafkajmx.jmx.config.reload.failure.created||
|kafkajmx.jmx.config.reload.success.created||
### Solr Metrics
|Metric Name|Description|
| :--- | :--- |
|solr.exporter.duration.seconds.bucket||
|solr.exporter.duration.seconds.count||
|solr.exporter.duration.seconds.sum||
|solr.metrics.core.query.mean.rate||
|solr.metrics.core.query.local.median.ms||
|solr.metrics..query.5minRate||
|solr.metrics.core.query.local.count||
|solr.metrics.core.query.1minRate||
|solr.metrics.core.searcher.cumulative.cache.total||
|solr.metrics.core.update.handler.splits.total||
|solr.collections.shard.leader||
|solr.collections.replica.state||
|solr.metrics.jvm.buffers||
|solr.metrics.core.query.p75.ms||
|solr.metrics.jvm.memory.heap.bytes||
|solr.metrics.core.update.handler.adds.total||
|solr.metrics.node.timeouts.total||
|solr.metrics.jvm.os.file.descriptors||
|solr.metrics.core.query.local.1minRate||
|solr.metrics.jvm.gc.seconds.total||
|solr.metrics.core.update.handler.adds||
|solr.metrics.core.update.handler.deletes.by.id.total˳||
|solr.collections.pull.replicas||
|solr.metrics.core.searcher.cache||
|solr.metrics.core.query.median.ms||
|solr.metrics.jvm.memory.pools.bytes||
|solr.metrics.core.field.cache.total||
|solr.metrics.core.searcher.cumulative.cache.ratio||
|solr.metrics.jetty.response.total||
|solr.metrics.core.update.handler.merges.total||
|solr.metrics.core.highlighter.request.total||
|solr.metrics.core.errors.total||
|solr.metrics.jvm.memory.non.heap.bytes||
|solr.collections.shard.state||
|solr.metrics.jvm.memory.bytes||
|solr.metrics.core.query.p99.ms||
|solr.metrics.jvm.os.cpu.load||
|solr.metrics.core.query.client.errors.1minRate||
|solr.metrics.core.searcher.cache.ratio||
|solr.metrics.node.cores||
|solr.metrics.core.query.p95.ms||
|solr.metrics.node.thread.pool.submitted.total||
|solr.metrics.core.searcher.documents||
|solr.metrics.node.thread.pool.completed.total||
|solr.metrics.jvm.os.load.average||
|solr.metrics.jvm.os.memory.bytes||
|solr.metrics.core.update.handler.expunge.deletes.total||
|solr.metrics.node.client.errors.total||
|solr.metrics.core.query.local.p95.ms||
|solr.metrics.core.update.handler.errors||
|solr.metrics.node.connections||
|solr.metrics.core.update.handler.auto.commits.total||
|solr.metrics.core.index.size.bytes||
|solr.metrics.core.searcher.warmup.time.seconds||
|solr.metrics.core.update.handler.rollbacks.total||
|solr.collections.tlog.replicas||
|solr.metrics.core.query.local.p99.ms||
|solr.metrics.core.fs.bytes||
|solr.collections.live.nodes||
|solr.metrics.jvm.os.cpu.time.seconds||
|solr.metrics.node.server.errors.total||
|solr.metrics.core.update.handler.optimizes.total||
|solr.ping||
|solr.metrics.core.timeouts.total||
|solr.metrics.jvm.gc.total||
|solr.metrics.node.requests.total||
|solr.metrics.core.query.errors.1minRate||
|solr.metrics.core.update.handler.pending.docs||
|solr.metrics.core.update.handler.soft.auto.commits.total||
|solr.metrics.jvm.buffers.bytes||
|solr.metrics.core.query.local.p75.ms||
|solr.metrics.core.client.errors.total||
|solr.metrics.jetty.requests.total||
|solr.metrics.node.time.seconds.total||
|solr.metrics.node.core.root.fs.bytes||
|solr.metrics.node.errors.total||
|solr.metrics.core.query.local.5minRate||
|solr.metrics.core.update.handler.commits.total||
|solr.metrics.jvm.threads||
|solr.metrics.node.thread.pool.running||
|solr.metrics.core.query.local.mean.rate||
|solr.collections.nrt.replicas||
|solr.metrics.core.update.handler.errors.total||
|solr.metrics.core.time.seconds.total||
|solr.metrics.core.update.handler.deletes.by.id||
|solr.metrics.core.update.handler.deletes.by.query||
|solr.metrics.overseer.collectionWorkQueueSize||
|solr.metrics.core.server.errors.total||
### Spark Metrics
|Metric Name|Description|
| :--- | :--- |
|spark.metrics.master.aliveWorkers.Number||
|spark.metrics.master.aliveWorkers.Value||
|spark.metrics.master.apps.Number||
|spark.metrics.master.apps.Value ||
|spark.metrics.master.waitingApps.Number||
|spark.metrics.master.waitingApps.Value||
|spark.metrics.master.workers.Number||
|spark.metrics.master.workers.Value||
|spark.metrics.HiveExternalCatalog.fileCacheHits.Count||
|spark.metrics.HiveExternalCatalog.filesDiscovered.Count||
|spark.metrics.HiveExternalCatalog.hiveClientCalls.Count||
|spark.metrics.HiveExternalCatalog.parallelListingJobCount.Count||
|spark.metrics.HiveExternalCatalog.partitionsFetched.Count||
|spark.metrics.CodeGenerator.compilationTime.Count||
|spark.metrics.CodeGenerator.compilationTime.Max||
|spark.metrics.CodeGenerator.compilationTime.Mean||
|spark.metrics.CodeGenerator.compilationTime.Min||
|spark.metrics.CodeGenerator.compilationTime.50thPercentile||
|spark.metrics.CodeGenerator.compilationTime.75thPercentile||
|spark.metrics.CodeGenerator.compilationTime.95thPercentile||
|spark.metrics.CodeGenerator.compilationTime.98thPercentile||
|spark.metrics.CodeGenerator.compilationTime.99thPercentile||
|spark.metrics.CodeGenerator.compilationTime.999thPercentile||
|spark.metrics.CodeGenerator.compilationTime.StdDev||
|spark.metrics.CodeGenerator.generatedClassSize.Count||
|spark.metrics.CodeGenerator.generatedClassSize.Max||
|spark.metrics.CodeGenerator.generatedClassSize.Mean||
|spark.metrics.CodeGenerator.generatedClassSize.Min||
|spark.metrics.CodeGenerator.generatedClassSize.50thPercentile||
|spark.metrics.CodeGenerator.generatedClassSize.75thPercentile||
|spark.metrics.CodeGenerator.generatedClassSize.95thPercentile||
|spark.metrics.CodeGenerator.generatedClassSize.98thPercentile||
|spark.metrics.CodeGenerator.generatedClassSize.99thPercentile||
|spark.metrics.CodeGenerator.generatedClassSize.999thPercentile||
|spark.metrics.CodeGenerator.generatedClassSize.StdDev||
|spark.metrics.CodeGenerator.generatedMethodSize.Count||
|spark.metrics.CodeGenerator.generatedMethodSize.Max||
|spark.metrics.CodeGenerator.generatedMethodSize.Mean||
|spark.metrics.CodeGenerator.generatedMethodSize.Min||
|spark.metrics.CodeGenerator.generatedMethodSize.50thPercentile||
|spark.metrics.CodeGenerator.generatedMethodSize.75thPercentile||
|spark.metrics.CodeGenerator.generatedMethodSize.95thPercentile||
|spark.metrics.CodeGenerator.generatedMethodSize.98thPercentile||
|spark.metrics.CodeGenerator.generatedMethodSize.99thPercentile||
|spark.metrics.CodeGenerator.generatedMethodSize.999thPercentile||
|spark.metrics.CodeGenerator.generatedMethodSize.StdDev||
|spark.metrics.CodeGenerator.sourceCodeSize.Count||
|spark.metrics.CodeGenerator.sourceCodeSize.Max||
|spark.metrics.CodeGenerator.sourceCodeSize.Mean||
|spark.metrics.CodeGenerator.sourceCodeSize.Min||
|spark.metrics.CodeGenerator.sourceCodeSize.50thPercentile||
|spark.metrics.CodeGenerator.sourceCodeSize.75thPercentile||
|spark.metrics.CodeGenerator.sourceCodeSize.95thPercentile||
|spark.metrics.CodeGenerator.sourceCodeSize.98thPercentile||
|spark.metrics.CodeGenerator.sourceCodeSize.99thPercentile||
|spark.metrics.CodeGenerator.sourceCodeSize.999thPercentile||
|spark.metrics.CodeGenerator.sourceCodeSize.StdDev||
|spark.metrics.worker.coresFree.Number||
|spark.metrics.worker.coresFree.Value||
|spark.metrics.worker.coresUsed.Number||
|spark.metrics.worker.coresUsed.Value||
|spark.metrics.worker.executors.Number||
|spark.metrics.worker.executors.Value||
|spark.metrics.worker.memFree.MB.Number||
|spark.metrics.worker.memFree.MB.Value||
|spark.metrics.worker.memUsed.MB.Number||
|spark.metrics.worker.memUsed.MB.Value||
|spark.metrics.HiveExternalCatalog.fileCacheHits.Count||
|spark.metrics.HiveExternalCatalog.filesDiscovered.Count||
|spark.metrics.HiveExternalCatalog.hiveClientCalls.Count||
|spark.metrics.HiveExternalCatalog.parallelListingJobCount.Count||
|spark.metrics.HiveExternalCatalog.partitionsFetched.Count||
|spark.metrics.CodeGenerator.compilationTime.Count||
|spark.metrics.CodeGenerator.compilationTime.Max||
|spark.metrics.CodeGenerator.compilationTime.Mean||
|spark.metrics.CodeGenerator.compilationTime.Min||
|spark.metrics.CodeGenerator.compilationTime.50thPercentile||
|spark.metrics.CodeGenerator.compilationTime.75thPercentile||
|spark.metrics.CodeGenerator.compilationTime.95thPercentile||
|spark.metrics.CodeGenerator.compilationTime.98thPercentile||
|spark.metrics.CodeGenerator.compilationTime.99thPercentile||
|spark.metrics.CodeGenerator.compilationTime.999thPercentile||
|spark.metrics.CodeGenerator.compilationTime.StdDev||
|spark.metrics.CodeGenerator.generatedClassSize.Count||
|spark.metrics.CodeGenerator.generatedClassSize.Max||
|spark.metrics.CodeGenerator.generatedClassSize.Mean||
|spark.metrics.CodeGenerator.generatedClassSize.Min||
|spark.metrics.CodeGenerator.generatedClassSize.50thPercentile||
|spark.metrics.CodeGenerator.generatedClassSize.75thPercentile||
|spark.metrics.CodeGenerator.generatedClassSize.95thPercentile||
|spark.metrics.CodeGenerator.generatedClassSize.98thPercentile||
|spark.metrics.CodeGenerator.generatedClassSize.99thPercentile||
|spark.metrics.CodeGenerator.generatedClassSize.999thPercentile||
|spark.metrics.CodeGenerator.generatedClassSize.StdDev||
|spark.metrics.CodeGenerator.generatedMethodSize.Count||
|spark.metrics.CodeGenerator.generatedMethodSize.Max||
|spark.metrics.CodeGenerator.generatedMethodSize.Mean||
|spark.metrics.CodeGenerator.generatedMethodSize.Min||
|spark.metrics.CodeGenerator.generatedMethodSize.50thPercentile||
|spark.metrics.CodeGenerator.generatedMethodSize.75thPercentile||
|spark.metrics.CodeGenerator.generatedMethodSize.95thPercentile||
|spark.metrics.CodeGenerator.generatedMethodSize.98thPercentile||
|spark.metrics.CodeGenerator.generatedMethodSize.99thPercentile||
|spark.metrics.CodeGenerator.generatedMethodSize.999thPercentile||
|spark.metrics.CodeGenerator.generatedMethodSize.StdDev||
|spark.metrics.CodeGenerator.sourceCodeSize.Count||
|spark.metrics.CodeGenerator.sourceCodeSize.Max||
|spark.metrics.CodeGenerator.sourceCodeSize.Mean||
|spark.metrics.CodeGenerator.sourceCodeSize.Min||
|spark.metrics.CodeGenerator.sourceCodeSize.50thPercentile||
|spark.metrics.CodeGenerator.sourceCodeSize.75thPercentile||
|spark.metrics.CodeGenerator.sourceCodeSize.95thPercentile||
|spark.metrics.CodeGenerator.sourceCodeSize.98thPercentile||
|spark.metrics.CodeGenerator.sourceCodeSize.99thPercentile||
|spark.metrics.CodeGenerator.sourceCodeSize.999thPercentile||
|spark.metrics.CodeGenerator.sourceCodeSize.StdDev||
| {
"content_hash": "68cbd0a5b33e8682f1b756a8b316bf73",
"timestamp": "",
"source": "github",
"line_count": 534,
"max_line_length": 515,
"avg_line_length": 57.166666666666664,
"alnum_prop": 0.8261866544370557,
"repo_name": "wavefrontHQ/docs",
"id": "dbd3ea6c624642c08f0aa383232b5bc8e997b70d",
"size": "30532",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "integrations/dataplatforms.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "169104"
},
{
"name": "Dockerfile",
"bytes": "431"
},
{
"name": "HTML",
"bytes": "48049"
},
{
"name": "JavaScript",
"bytes": "10093"
},
{
"name": "Ruby",
"bytes": "260"
}
],
"symlink_target": ""
} |
class Helper
# module HTMLEscapeHelper
# def h(text)
# Rack::Utils.escape_html(text)
# end
# end
module Support
def parameterize text, separator = '-'
text.gsub(/[^a-z0-9\-_]+/, separator)
end
end
end
| {
"content_hash": "d0dfc384e85c32e513767fa4660a2ecf",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 43,
"avg_line_length": 18.307692307692307,
"alnum_prop": 0.592436974789916,
"repo_name": "DmytroVasin/challenge",
"id": "e95962cd35b4573ff7924f65f92731a37784ee15",
"size": "238",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "helpers/helper.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "991"
},
{
"name": "HTML",
"bytes": "969"
},
{
"name": "JavaScript",
"bytes": "978"
},
{
"name": "Ruby",
"bytes": "4461"
}
],
"symlink_target": ""
} |
module Print3Flipped where
myGreeting :: String
myGreeting = (++) "hello " "world!"
hello :: String
hello = "hello"
world :: String
world = "world!"
main :: IO ()
main = do
putStrLn myGreeting
putStrLn secondGreeting
where secondGreeting = (++) hello ((++) " " world)
| {
"content_hash": "95a94bcc5538ba67155b5ba15b2e15d1",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 52,
"avg_line_length": 17.375,
"alnum_prop": 0.658273381294964,
"repo_name": "rasheedja/HaskellFromFirstPrinciples",
"id": "444754e0363b2843921bdf22b2b58a1aa9eff527",
"size": "278",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Chapter3/print3flipped.hs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Haskell",
"bytes": "11797"
}
],
"symlink_target": ""
} |
module Cryptoexchange::Exchanges
module Koinex
module Services
class Market < Cryptoexchange::Services::Market
class << self
def supports_individual_ticker_query?
false
end
end
def fetch
output = super(ticker_url)
adapt_all(output['stats']).flatten
end
def ticker_url
"#{Cryptoexchange::Exchanges::Koinex::Market::API_URL}/ticker"
end
def adapt_all(output)
output.map do |market|
market[1].map do |ticker|
market_pair = Cryptoexchange::Models::MarketPair.new(
base: ticker[0],
target: GetSymbol.get_symbol(market[0]),
market: Koinex::Market::NAME
)
adapt(market_pair, ticker[1])
end
end
end
def adapt(market_pair, output)
ticker = Cryptoexchange::Models::Ticker.new
ticker.base = market_pair.base
ticker.target = market_pair.target
ticker.market = Koinex::Market::NAME
ticker.ask = NumericHelper.to_d(output['lowest_ask'])
ticker.bid = NumericHelper.to_d(output['highest_bid'])
ticker.last = NumericHelper.to_d(output['last_traded_price'])
ticker.high = NumericHelper.to_d(output['max_24hrs'])
ticker.low = NumericHelper.to_d(output['min_24hrs'])
ticker.volume = NumericHelper.to_d(output['vol_24hrs'])
ticker.timestamp = nil
ticker.payload = output
ticker
end
end
end
end
end
| {
"content_hash": "7298adc8f073b1817de73326820ddf09",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 76,
"avg_line_length": 33.490196078431374,
"alnum_prop": 0.5275175644028103,
"repo_name": "coingecko/cryptoexchange",
"id": "bf44c6dc77e26dcf41944f069a695b7814d0b372",
"size": "1708",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/cryptoexchange/exchanges/koinex/services/market.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "3283949"
},
{
"name": "Shell",
"bytes": "131"
}
],
"symlink_target": ""
} |
/** \file pantheios/implicit_link/bec.file.WithCallback.h
*
* [C, C++] Implicitly links in the \ref page__backend__callbacks "callback" version of the
* \ref group__backend__stock_backends__file "Pantheios File Back-End Common Library"
* common implementation (that may be used by sole/local/remote back-end).
*/
#ifndef PANTHEIOS_INCL_PANTHEIOS_IMPLICIT_LINK_H_BEC_FILE_WITHCALLBACK
#define PANTHEIOS_INCL_PANTHEIOS_IMPLICIT_LINK_H_BEC_FILE_WITHCALLBACK
/* /////////////////////////////////////////////////////////////////////////
* Version information
*/
#ifndef PANTHEIOS_DOCUMENTATION_SKIP_SECTION
# define PANTHEIOS_VER_PANTHEIOS_IMPLICIT_LINK_H_BEC_FILE_WITHCALLBACK_MAJOR 1
# define PANTHEIOS_VER_PANTHEIOS_IMPLICIT_LINK_H_BEC_FILE_WITHCALLBACK_MINOR 0
# define PANTHEIOS_VER_PANTHEIOS_IMPLICIT_LINK_H_BEC_FILE_WITHCALLBACK_REVISION 1
# define PANTHEIOS_VER_PANTHEIOS_IMPLICIT_LINK_H_BEC_FILE_WITHCALLBACK_EDIT 5
#endif /* !PANTHEIOS_DOCUMENTATION_SKIP_SECTION */
/* /////////////////////////////////////////////////////////////////////////
* Includes
*/
#ifndef PANTHEIOS_INCL_PANTHEIOS_H_PANTHEIOS
# include <pantheios/pantheios.h>
#endif /* !PANTHEIOS_INCL_PANTHEIOS_H_PANTHEIOS */
#ifndef PANTHEIOS_INCL_PANTHEIOS_IMPLICIT_LINK_H_IMPLICIT_LINK_BASE_
# include <pantheios/implicit_link/implicit_link_base_.h>
#endif /* !PANTHEIOS_INCL_PANTHEIOS_IMPLICIT_LINK_H_IMPLICIT_LINK_BASE_ */
/* /////////////////////////////////////////////////////////////////////////
* Implicit-linking directives
*/
#ifdef PANTHEIOS_IMPLICIT_LINK_SUPPORT
# if defined(__BORLANDC__)
# elif defined(__COMO__)
# elif defined(__DMC__)
# elif defined(__GNUC__)
# elif defined(__INTEL_COMPILER)
# pragma comment(lib, PANTHEIOS_IMPL_LINK_LIBRARY_NAME_("bec.file.WithCallback"))
# pragma message(" " PANTHEIOS_IMPL_LINK_LIBRARY_NAME_("bec.file.WithCallback"))
# elif defined(__MWERKS__)
# elif defined(__WATCOMC__)
# elif defined(_MSC_VER)
# pragma comment(lib, PANTHEIOS_IMPL_LINK_LIBRARY_NAME_("bec.file.WithCallback"))
# pragma message(" " PANTHEIOS_IMPL_LINK_LIBRARY_NAME_("bec.file.WithCallback"))
# else /* ? compiler */
# error Compiler not recognised
# endif /* compiler */
#endif /* PANTHEIOS_IMPLICIT_LINK_SUPPORT */
/* ////////////////////////////////////////////////////////////////////// */
#endif /* !PANTHEIOS_INCL_PANTHEIOS_IMPLICIT_LINK_H_BEC_FILE_WITHCALLBACK */
/* ///////////////////////////// end of file //////////////////////////// */
| {
"content_hash": "075edb65aa3b4bde3c3b7e98469c442c",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 91,
"avg_line_length": 37.69117647058823,
"alnum_prop": 0.612173234490831,
"repo_name": "zvelo/pantheios",
"id": "52664815946dd35df243fe6722df461cdc8063a3",
"size": "4605",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "include/pantheios/implicit_link/bec.file.WithCallback.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "1497828"
},
{
"name": "C++",
"bytes": "3130548"
},
{
"name": "CSS",
"bytes": "3238"
},
{
"name": "Ruby",
"bytes": "24512"
}
],
"symlink_target": ""
} |
export class ItemMetrics {
itemObj: any;
itemName: string;
itemfrom: string;
itemLevel: string;
itemStatus: string;
itemTag: string[];
itemTime: string;
constructor(
itemObj: any,
itemName: string,
itemfrom: string,
itemLevel: string,
itemStatus: string,
itemTag: string[],
itemTime: string
) {
this.itemObj = itemObj;
this.itemName = itemName;
this.itemfrom = itemfrom;
this.itemLevel = itemLevel;
this.itemStatus = itemStatus;
this.itemTag = itemTag;
this.itemTime = itemTime;
}
}
export class ListMetrics {
listName: string;
listData: ItemMetrics[];
constructor(listName: string, listData: ItemMetrics[]) {
this.listName = listName;
this.listData = listData;
}
}
| {
"content_hash": "bbaf407165384b8c6ce534fd24ca1c1a",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 58,
"avg_line_length": 17.837209302325583,
"alnum_prop": 0.6597131681877445,
"repo_name": "DXCChina/pms",
"id": "f48c11b27d1ae7b9cb0755ff294ead63bf04e068",
"size": "767",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "app/src/app/pages/project/dashboard-view/card-data.entity.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "1027"
},
{
"name": "CSS",
"bytes": "149633"
},
{
"name": "HTML",
"bytes": "93419"
},
{
"name": "JavaScript",
"bytes": "1645"
},
{
"name": "Python",
"bytes": "66976"
},
{
"name": "TypeScript",
"bytes": "224878"
}
],
"symlink_target": ""
} |
package org.cagrid.gaards.dorian.idp;
import gov.nih.nci.cagrid.common.FaultUtil;
import junit.framework.TestCase;
import org.cagrid.gaards.dorian.common.Lifetime;
import org.cagrid.gaards.dorian.stubs.types.DorianInternalFault;
import org.cagrid.gaards.dorian.test.Utils;
import org.cagrid.tools.database.Database;
public class TestPasswordSecurityManager extends TestCase {
private Database db;
public void testGetAndDeleteEntry() {
PasswordSecurityManager psm = null;
try {
psm = new PasswordSecurityManager(db, getPolicy());
String uid = "user";
assertEquals(false, psm.entryExists(uid));
PasswordSecurity entry = psm.getEntry(uid);
assertEquals(true, psm.entryExists(uid));
validateEntry(entry, 0, 0, false, PasswordStatus.Valid);
assertEquals(PasswordStatus.Valid, psm.getPasswordStatus(uid));
psm.deleteEntry(uid);
assertEquals(false, psm.entryExists(uid));
} catch (Exception e) {
FaultUtil.printFault(e);
assertTrue(false);
} finally {
try {
psm.clearDatabase();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void testSuspendedPassword() {
PasswordSecurityManager psm = null;
try {
PasswordSecurityPolicy policy = getPolicy();
psm = new PasswordSecurityManager(db, policy);
for (int j = 0; j < 2; j++) {
String uid = "user" + j;
assertEquals(false, psm.entryExists(uid));
validateEntry(psm.getEntry(uid), 0, 0, false,
PasswordStatus.Valid);
assertEquals(true, psm.entryExists(uid));
assertEquals(PasswordStatus.Valid, psm.getPasswordStatus(uid));
int localCount = 0;
boolean expiredOnce = false;
for (int i = 1; i <= (policy.getTotalInvalidLogins() + 1); i++) {
psm.reportInvalidLoginAttempt(uid);
localCount = localCount + 1;
if (i >= policy.getTotalInvalidLogins()) {
if (localCount == policy.getConsecutiveInvalidLogins()) {
localCount = 0;
}
validateEntry(psm.getEntry(uid), localCount, i,
expiredOnce, PasswordStatus.LockedUntilChanged);
assertEquals(PasswordStatus.LockedUntilChanged, psm
.getPasswordStatus(uid));
} else if (localCount != policy
.getConsecutiveInvalidLogins()) {
validateEntry(psm.getEntry(uid), localCount, i,
expiredOnce, PasswordStatus.Valid);
assertEquals(PasswordStatus.Valid, psm
.getPasswordStatus(uid));
} else {
localCount = 0;
expiredOnce = true;
validateEntry(psm.getEntry(uid), localCount, i,
expiredOnce, PasswordStatus.Locked);
assertEquals(PasswordStatus.Locked, psm
.getPasswordStatus(uid));
psm.reportSuccessfulLoginAttempt(uid);
validateEntry(psm.getEntry(uid), localCount, i,
expiredOnce, PasswordStatus.Locked);
assertEquals(PasswordStatus.Locked, psm
.getPasswordStatus(uid));
Thread
.sleep((policy.getLockout().getSeconds() * 1000) + 100);
assertEquals(PasswordStatus.Valid, psm
.getPasswordStatus(uid));
validateEntry(psm.getEntry(uid), localCount, i,
expiredOnce, PasswordStatus.Valid);
}
}
}
} catch (Exception e) {
FaultUtil.printFault(e);
assertTrue(false);
} finally {
try {
psm.clearDatabase();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void testResetPassword() {
PasswordSecurityManager psm = null;
try {
PasswordSecurityPolicy policy = getPolicy();
psm = new PasswordSecurityManager(db, policy);
String uid = "user";
assertEquals(false, psm.entryExists(uid));
validateEntry(psm.getEntry(uid), 0, 0, false, PasswordStatus.Valid);
assertEquals(PasswordStatus.Valid, psm.getPasswordStatus(uid));
psm.reportInvalidLoginAttempt(uid);
validateEntry(psm.getEntry(uid), 1, 1, false, PasswordStatus.Valid);
assertEquals(PasswordStatus.Valid, psm.getPasswordStatus(uid));
psm.reportInvalidLoginAttempt(uid);
validateEntry(psm.getEntry(uid), 2, 2, false, PasswordStatus.Valid);
assertEquals(PasswordStatus.Valid, psm.getPasswordStatus(uid));
psm.reportSuccessfulLoginAttempt(uid);
validateEntry(psm.getEntry(uid), 0, 2, false, PasswordStatus.Valid);
assertEquals(PasswordStatus.Valid, psm.getPasswordStatus(uid));
} catch (Exception e) {
FaultUtil.printFault(e);
assertTrue(false);
} finally {
try {
psm.clearDatabase();
} catch (Exception e) {
e.printStackTrace();
}
}
}
protected void validateEntry(PasswordSecurity entry, long count,
long totalCount, boolean expired, PasswordStatus status) {
assertEquals(count, entry.getConsecutiveInvalidLogins());
assertEquals(totalCount, entry.getTotalInvalidLogins());
assertEquals(status, entry.getPasswordStatus());
if (expired) {
if (entry.getLockoutExpiration() <= 0) {
fail("Password should be locked.");
}
} else {
assertEquals(0, entry.getLockoutExpiration());
}
}
private PasswordSecurityPolicy getPolicy() throws DorianInternalFault {
Lifetime time = new Lifetime();
time.setHours(0);
time.setMinutes(0);
time.setSeconds(3);
PasswordSecurityPolicy policy = new PasswordSecurityPolicy();
policy.setLockout(time);
policy.setConsecutiveInvalidLogins(3);
policy.setTotalInvalidLogins(8);
return policy;
}
protected void setUp() throws Exception {
super.setUp();
try {
db = Utils.getDB();
assertEquals(0, db.getUsedConnectionCount());
} catch (Exception e) {
FaultUtil.printFault(e);
assertTrue(false);
}
}
protected void tearDown() throws Exception {
super.setUp();
try {
assertEquals(0, db.getUsedConnectionCount());
} catch (Exception e) {
FaultUtil.printFault(e);
assertTrue(false);
}
}
}
| {
"content_hash": "5af6f5c18a6ff2c567d0d0b3b8156649",
"timestamp": "",
"source": "github",
"line_count": 191,
"max_line_length": 72,
"avg_line_length": 30.81151832460733,
"alnum_prop": 0.6759558198810536,
"repo_name": "NCIP/cagrid-core",
"id": "a9a6e46b5e149b2e842b6b3308c4eb9843de27e0",
"size": "6374",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "caGrid/projects/dorian/test/src/org/cagrid/gaards/dorian/idp/TestPasswordSecurityManager.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "124236"
},
{
"name": "Java",
"bytes": "17856338"
},
{
"name": "JavaScript",
"bytes": "62288"
},
{
"name": "Perl",
"bytes": "100792"
},
{
"name": "Scala",
"bytes": "405"
},
{
"name": "Shell",
"bytes": "3487"
},
{
"name": "XSLT",
"bytes": "6524"
}
],
"symlink_target": ""
} |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2019.07.02 at 03:35:23 PM MSK
//
package ru.gov.zakupki.fz44.ws.priz;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="sender">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <maxLength value="200"/>
* <minLength value="1"/>
* </restriction>
* </simpleType>
* </element>
* <element name="senderType" type="{http://zakupki.gov.ru/fz44/ws/priz}partnerType"/>
* <element name="code" type="{http://zakupki.gov.ru/fz44/ws/priz}spzNumType"/>
* <element name="consRegistryNum" type="{http://zakupki.gov.ru/fz44/ws/priz}consRegistryNumType" minOccurs="0"/>
* <element name="documentKind" type="{http://zakupki.gov.ru/fz44/ws/priz}RPZDocumentKindType" minOccurs="0"/>
* <element name="regNumber" type="{http://zakupki.gov.ru/fz44/ws/priz}shortNameType" minOccurs="0"/>
* <element name="fromDate" type="{http://www.w3.org/2001/XMLSchema}dateTime"/>
* <element name="toDate" type="{http://www.w3.org/2001/XMLSchema}dateTime"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"sender",
"senderType",
"code",
"consRegistryNum",
"documentKind",
"regNumber",
"fromDate",
"toDate"
})
@XmlRootElement(name = "getRPZObjectListRequest")
public class GetRPZObjectListRequest {
@XmlElement(required = true)
protected String sender;
@XmlElement(required = true)
@XmlSchemaType(name = "string")
protected PartnerType senderType;
@XmlElement(required = true)
protected String code;
protected String consRegistryNum;
@XmlSchemaType(name = "string")
protected RPZDocumentKindType documentKind;
protected String regNumber;
@XmlElement(required = true)
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar fromDate;
@XmlElement(required = true)
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar toDate;
/**
* Gets the value of the sender property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSender() {
return sender;
}
/**
* Sets the value of the sender property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSender(String value) {
this.sender = value;
}
/**
* Gets the value of the senderType property.
*
* @return
* possible object is
* {@link PartnerType }
*
*/
public PartnerType getSenderType() {
return senderType;
}
/**
* Sets the value of the senderType property.
*
* @param value
* allowed object is
* {@link PartnerType }
*
*/
public void setSenderType(PartnerType value) {
this.senderType = value;
}
/**
* Gets the value of the code property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCode() {
return code;
}
/**
* Sets the value of the code property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCode(String value) {
this.code = value;
}
/**
* Gets the value of the consRegistryNum property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getConsRegistryNum() {
return consRegistryNum;
}
/**
* Sets the value of the consRegistryNum property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setConsRegistryNum(String value) {
this.consRegistryNum = value;
}
/**
* Gets the value of the documentKind property.
*
* @return
* possible object is
* {@link RPZDocumentKindType }
*
*/
public RPZDocumentKindType getDocumentKind() {
return documentKind;
}
/**
* Sets the value of the documentKind property.
*
* @param value
* allowed object is
* {@link RPZDocumentKindType }
*
*/
public void setDocumentKind(RPZDocumentKindType value) {
this.documentKind = value;
}
/**
* Gets the value of the regNumber property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRegNumber() {
return regNumber;
}
/**
* Sets the value of the regNumber property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRegNumber(String value) {
this.regNumber = value;
}
/**
* Gets the value of the fromDate property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getFromDate() {
return fromDate;
}
/**
* Sets the value of the fromDate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setFromDate(XMLGregorianCalendar value) {
this.fromDate = value;
}
/**
* Gets the value of the toDate property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getToDate() {
return toDate;
}
/**
* Sets the value of the toDate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setToDate(XMLGregorianCalendar value) {
this.toDate = value;
}
}
| {
"content_hash": "dcc3de141bbd4926bde5e41b8f7bf591",
"timestamp": "",
"source": "github",
"line_count": 277,
"max_line_length": 124,
"avg_line_length": 25.404332129963898,
"alnum_prop": 0.5770925110132159,
"repo_name": "simokhov/schemas44",
"id": "cc70fc8bac24396e36c977bb638f5482a6681841",
"size": "7037",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/ru/gov/zakupki/fz44/ws/priz/GetRPZObjectListRequest.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "22048974"
}
],
"symlink_target": ""
} |
package org.springframework.security.web.authentication.logout;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AbstractAuthenticationTargetUrlRequestHandler;
/**
* Handles the navigation on logout by delegating to the {@link AbstractAuthenticationTargetUrlRequestHandler}
* base class logic.
*
* @author Luke Taylor
* @since 3.0
*/
public class SimpleUrlLogoutSuccessHandler extends AbstractAuthenticationTargetUrlRequestHandler
implements LogoutSuccessHandler {
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
throws IOException, ServletException {
super.handle(request, response, authentication);
}
}
| {
"content_hash": "2bd5950bd62838f4ed3d7d4ad330f384",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 120,
"avg_line_length": 35,
"alnum_prop": 0.8137566137566138,
"repo_name": "justinedelson/spring-security",
"id": "440410f5b20b1b141d86fd212aaa0e0ad53cfa63",
"size": "945",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "web/src/main/java/org/springframework/security/web/authentication/logout/SimpleUrlLogoutSuccessHandler.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "3537252"
},
{
"name": "Perl",
"bytes": "4066"
},
{
"name": "Python",
"bytes": "134"
},
{
"name": "Shell",
"bytes": "6332"
}
],
"symlink_target": ""
} |
import {LogService} from '../log.service';
const LONGITUDE_EXTENT = 180;
const LATITUDE_EXTENT = 75;
const GRID_EXTENT_X = 2000;
const GRID_EXTENT_Y = 1000;
const GRID_DIAGONAL = 2236; // 2236 is the length of the diagonal of the 2000x1000 box
const GRID_CENTRE_X = 500;
const GRID_CENTRE_Y = 500;
/**
* A model of the map bounds bottom left to top right in lat and long
*/
export interface MapBounds {
lngMin: number;
latMin: number;
lngMax: number;
latMax: number;
}
/**
* model of the topo2CurrentRegion Loc part of the MetaUi below
*/
export interface LocMeta {
lng: number;
lat: number;
}
/**
* model of the topo2CurrentRegion MetaUi from Device below
*/
export interface MetaUi {
equivLoc: LocMeta;
x: number;
y: number;
}
/**
* Model of the Zoom preferences
*/
export interface TopoZoomPrefs {
tx: number;
ty: number;
sc: number;
}
/**
* Utility class with static functions for scaling maps
*
* This is left as a class, so that the functions are loaded only as needed
*/
export class ZoomUtils {
static convertGeoToCanvas(location: LocMeta ): MetaUi {
const calcX = (LONGITUDE_EXTENT + location.lng) / (LONGITUDE_EXTENT * 2) * GRID_EXTENT_X - GRID_CENTRE_X;
const calcY = (LATITUDE_EXTENT - location.lat) / (LATITUDE_EXTENT * 2) * GRID_EXTENT_Y;
return <MetaUi>{
x: calcX,
y: calcY,
equivLoc: {
lat: location.lat,
lng: location.lng
}
};
}
static convertXYtoGeo(x: number, y: number): MetaUi {
const calcLong: number = (x + GRID_CENTRE_X) * 2 * LONGITUDE_EXTENT / GRID_EXTENT_X - LONGITUDE_EXTENT;
const calcLat: number = -(y * 2 * LATITUDE_EXTENT / GRID_EXTENT_Y - LATITUDE_EXTENT);
return <MetaUi>{
x: x,
y: y,
equivLoc: <LocMeta>{
lat: (calcLat === -0) ? 0 : calcLat,
lng: calcLong
}
};
}
/**
* This converts the bounds of a map loaded from a TopoGson file that has been
* converted in to a GEOJson format by d3
*
* The bounds are in latitude and longitude from bottom left (min) to top right (max)
*
* First they are converted in to SVG viewbox coordinates 0,0 top left 1000x1000
*
* The the zoom level is calculated by scaling to the grid diagonal
*
* Finally the translation is calculated by applying the zoom first, and then
* translating on the zoomed coordinate system
* @param mapBounds - the bounding box of the chosen map in lat and long
* @param log The LogService
*/
static convertBoundsToZoomLevel(mapBounds: MapBounds, log?: LogService): TopoZoomPrefs {
const min: MetaUi = this.convertGeoToCanvas(<LocMeta>{
lng: mapBounds.lngMin,
lat: mapBounds.latMin
});
const max: MetaUi = this.convertGeoToCanvas(<LocMeta>{
lng: mapBounds.lngMax,
lat: mapBounds.latMax
});
const diagonal = Math.sqrt(Math.pow(max.x - min.x, 2) + Math.pow(max.y - min.y, 2));
const centreX = (max.x - min.x) / 2 + min.x;
const centreY = (max.y - min.y) / 2 + min.y;
// Zoom works from the top left of the 1000x1000 viewbox
// The scale is applied first and then the translate is on the scaled coordinates
const zoomscale = 0.5 * GRID_DIAGONAL / ((diagonal < 100) ? 100 : diagonal); // Don't divide by zero
const zoomx = -centreX * zoomscale + GRID_CENTRE_X;
const zoomy = -centreY * zoomscale + GRID_CENTRE_Y;
// log.debug('MapBounds', mapBounds, 'XYMin', min, 'XYMax', max, 'Diag', diagonal,
// 'Centre', centreX, centreY, 'translate', zoomx, zoomy, 'Scale', zoomscale);
return <TopoZoomPrefs>{tx: zoomx, ty: zoomy, sc: zoomscale};
}
/**
* Calculate Zoom settings to fit the 1000x1000 grid in to the available window height
* less the banner height
*
* Scaling always happens from the top left 0,0
* If the height is greater than the width then no scaling is required - grid will
* need to fill the SVG canvas
* @param bannerHeight - the top band of the screen for the mast
* @param innerWidth - the actual width of the screen
* @param innerHeight - the actual height of the screen
* @return Zoom settings - scale and translate
*/
static zoomToWindowSize(bannerHeight: number, innerWidth: number, innerHeight: number): TopoZoomPrefs {
const newHeight = innerHeight - bannerHeight;
if (newHeight > innerWidth) {
return <TopoZoomPrefs>{
sc: 1.0,
tx: 0,
ty: 0
};
} else {
const scale = newHeight / innerWidth;
return <TopoZoomPrefs>{
sc: scale,
tx: (500 / scale - 500) * scale,
ty: 0
};
}
}
}
| {
"content_hash": "f9d6e99bc5763564c9ecfb069fff458f",
"timestamp": "",
"source": "github",
"line_count": 154,
"max_line_length": 113,
"avg_line_length": 32.53896103896104,
"alnum_prop": 0.6016763121133506,
"repo_name": "oplinkoms/onos",
"id": "1150c39a6ade3cbaf2fc444cc13042d54deb80bc",
"size": "5628",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "web/gui2-fw-lib/lib/svg/zoomutils.ts",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "364443"
},
{
"name": "Dockerfile",
"bytes": "2443"
},
{
"name": "HTML",
"bytes": "319812"
},
{
"name": "Java",
"bytes": "46767333"
},
{
"name": "JavaScript",
"bytes": "4022973"
},
{
"name": "Makefile",
"bytes": "1658"
},
{
"name": "P4",
"bytes": "171319"
},
{
"name": "Python",
"bytes": "977954"
},
{
"name": "Ruby",
"bytes": "8615"
},
{
"name": "Shell",
"bytes": "336303"
},
{
"name": "TypeScript",
"bytes": "894995"
}
],
"symlink_target": ""
} |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="GameServerState.cs" company="Exit Games GmbH">
// Copyright (c) Exit Games GmbH. All rights reserved.
// </copyright>
// <summary>
// Defines the GameServerState type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
using Photon.Common.LoadBalancer.LoadShedding;
namespace Photon.LoadBalancing.MasterServer.GameServer
{
#region using directives
using System;
#endregion
public class GameServerState : IComparable<GameServerState>
{
public GameServerState(FeedbackLevel loadLevel, int peerCount)
{
this.LoadLevel = loadLevel;
this.PeerCount = peerCount;
}
public FeedbackLevel LoadLevel { get; private set; }
public int PeerCount { get; private set; }
public static bool operator >(GameServerState a, GameServerState b)
{
if (a.LoadLevel > b.LoadLevel)
{
return true;
}
return a.PeerCount > b.PeerCount;
}
public static bool operator <(GameServerState a, GameServerState b)
{
if (a.LoadLevel < b.LoadLevel)
{
return true;
}
return a.PeerCount < b.PeerCount;
}
public int CompareTo(GameServerState other)
{
if (this < other)
{
return -1;
}
if (this > other)
{
return 1;
}
return 0;
}
}
} | {
"content_hash": "4d67c5973d32ecccf5be52a5b657856a",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 120,
"avg_line_length": 25.895522388059703,
"alnum_prop": 0.46455331412103745,
"repo_name": "tienrocker/server",
"id": "37a9b94f12c63cb406b236733f7cf9b5822a2e1c",
"size": "1737",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "LoadBalancing/MasterServer/GameServer/GameServerState.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "1111181"
}
],
"symlink_target": ""
} |
layout: post
title: Первый секс
---
Мы просто разденемся, залезем в кровать, а дальше — будь что будет
## Главное правило
Секс — это то, от чего **все присутствующие** получают удовольствие.
«Матрица» и «пикап» ошибочно считают (даже если не любят в этом признаваться или даже утверждают обратное), что секса нужно добиваться, или что это одолжение, которое женщина делает мужчине.
## Второе главное правило
Хороший секс построен на избыточности и отдавании. Это означает, что партнёры вкладываются друг в друга, стараясь доставить удовольствие другому. Каждый получает много. Такой секс часто бывает в длительных отношениях.
Плохой секс построен на недостаточности и забирании. Это означает, что каждый старается в первую очередь сам получить удовольствие, экономит. И из-за этого сам недополучает. Такой секс часто бывает в отношениях на одну ночь.
Однако! Это не значит, что длительные отношения = хороший секс, а короткие = плохой. Чаще бывает наоборот, хороший секс приводит к тому, что хочется ещё, а плохой — к разочарованию и сожалениям.
## Как сделать секс классным
1. Все присутствующие хотят друг друга
2. Все присутствующие вкладываются и заботятся об удовольствии друг друга
## А что если она не вкладывается
1. «Начни с себя». Возбуди, доставляй удовольствие.
2. Не требуй ничего взамен, хорошая девушка сама вернёт, плохая — нет
3. Плохая, не вкладывающаяся в секс девушка недостойна того, чтобы ты ей перезванивал
## Как вкладываться
Точка входа — поцелуй. Дальше — эскалация.
| {
"content_hash": "d70214178755d93278875a1f9f5e6fa1",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 224,
"avg_line_length": 44.3235294117647,
"alnum_prop": 0.7883211678832117,
"repo_name": "amoral-ninja/amoral-ninja.github.io",
"id": "3c26e6cee094972c21c9538bd9f8f3e54dc8950d",
"size": "2697",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_posts/2015-04-18-laying.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "56043"
},
{
"name": "HTML",
"bytes": "19921"
}
],
"symlink_target": ""
} |
/* globals describe, ddescribe, beforeEach, inject, it, expect, iit, module */
'use strict';
describe('progressBar directive', function () {
var $compile;
var $rootScope;
var directiveElement;
var scope;
var ProgressBarsStorage;
beforeEach(module('pg.progress-bars'));
beforeEach(inject(function (_$compile_, _$rootScope_, $injector) {
$compile = _$compile_;
$rootScope = _$rootScope_;
scope = $rootScope;
ProgressBarsStorage = $injector.get('ProgressBarsStorage');
directiveElement = $compile('<pg-progress-bar name="test" minimum="15" speed="350" trickle-rate="4" trickle-speed="400" animation="linear"></pg-progress-bar>')(scope);
}));
describe('ProgressBar instantiating', function () {
it('Should throw error when not passed name attribute', function () {
expect(function errorFunctionWrapper() {
$compile('<pg-progress-bar></pg-progress-bar>')($rootScope);
}).toThrowError(/specify/);
});
it('Should add id attribute to element', function () {
expect(directiveElement.attr('id')).toEqual('progress-bar-' + 'test');
});
it('Should register in storage instance of ProgressBar', function () {
expect(ProgressBarsStorage.get('test')).not.toBeNull();
});
it('Options of saved in storage progress bar should be equal to set through directive attributes', function () {
expect(ProgressBarsStorage.get('test').options.minimum).toEqual(15);
expect(ProgressBarsStorage.get('test').options.speed).toEqual(350);
expect(ProgressBarsStorage.get('test').options.trickleRate).toEqual(4);
expect(ProgressBarsStorage.get('test').options.trickleSpeed).toEqual(400);
expect(ProgressBarsStorage.get('test').options.animation).toEqual('linear');
});
it('Should unregistered from storage when directive destroyed', function () {
expect(ProgressBarsStorage.get('test')).not.toBeNull();
scope.$destroy();
expect(ProgressBarsStorage.get('test')).toBeNull();
})
});
});
| {
"content_hash": "dda904928fcf907da7cc056a20072ef5",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 175,
"avg_line_length": 44.40816326530612,
"alnum_prop": 0.6309742647058824,
"repo_name": "PSDCoder/progress-bars",
"id": "236b63727318abbd8b638472497d49de2cde8f2b",
"size": "2176",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/unit/progressBarDirective.spec.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "7872"
},
{
"name": "HTML",
"bytes": "9108"
},
{
"name": "JavaScript",
"bytes": "46772"
}
],
"symlink_target": ""
} |
package com.intellij.java.codeInsight.intention;
import com.intellij.codeInsight.daemon.LightIntentionActionTestCase;
/**
* @author ven
*/
public class MoveInitializerToConstructorActionTest extends LightIntentionActionTestCase {
public void test() throws Exception { doAllTests(); }
@Override
protected String getBasePath() {
return "/codeInsight/daemonCodeAnalyzer/quickFix/moveInitializerToConstructor";
}
}
| {
"content_hash": "41fb65ba9c5731c2f32f0df05bbfa4b4",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 90,
"avg_line_length": 26.8125,
"alnum_prop": 0.7948717948717948,
"repo_name": "asedunov/intellij-community",
"id": "c64c1718b1399d9e39db02d1cc87cfd3b7394a04",
"size": "1029",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "java/java-tests/testSrc/com/intellij/java/codeInsight/intention/MoveInitializerToConstructorActionTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AMPL",
"bytes": "20665"
},
{
"name": "AspectJ",
"bytes": "182"
},
{
"name": "Batchfile",
"bytes": "60827"
},
{
"name": "C",
"bytes": "211454"
},
{
"name": "C#",
"bytes": "1264"
},
{
"name": "C++",
"bytes": "199030"
},
{
"name": "CMake",
"bytes": "1675"
},
{
"name": "CSS",
"bytes": "201445"
},
{
"name": "CoffeeScript",
"bytes": "1759"
},
{
"name": "Erlang",
"bytes": "10"
},
{
"name": "Groovy",
"bytes": "3250629"
},
{
"name": "HLSL",
"bytes": "57"
},
{
"name": "HTML",
"bytes": "1899872"
},
{
"name": "J",
"bytes": "5050"
},
{
"name": "Java",
"bytes": "165745831"
},
{
"name": "JavaScript",
"bytes": "570364"
},
{
"name": "Jupyter Notebook",
"bytes": "93222"
},
{
"name": "Kotlin",
"bytes": "4687386"
},
{
"name": "Lex",
"bytes": "147047"
},
{
"name": "Makefile",
"bytes": "2352"
},
{
"name": "NSIS",
"bytes": "51039"
},
{
"name": "Objective-C",
"bytes": "27861"
},
{
"name": "Perl",
"bytes": "903"
},
{
"name": "Perl6",
"bytes": "26"
},
{
"name": "Protocol Buffer",
"bytes": "6680"
},
{
"name": "Python",
"bytes": "25459263"
},
{
"name": "Roff",
"bytes": "37534"
},
{
"name": "Ruby",
"bytes": "1217"
},
{
"name": "Shell",
"bytes": "66338"
},
{
"name": "Smalltalk",
"bytes": "338"
},
{
"name": "TeX",
"bytes": "25473"
},
{
"name": "Thrift",
"bytes": "1846"
},
{
"name": "TypeScript",
"bytes": "9469"
},
{
"name": "Visual Basic",
"bytes": "77"
},
{
"name": "XSLT",
"bytes": "113040"
}
],
"symlink_target": ""
} |
/* Cover
============================================================================= */
:root {
--cover-color : ;
--cover-margin : 0 auto;
--cover-max-width : 40em;
--cover-text-align : center;
/* Background */
--cover-background-blend-mode : ;
--cover-background-color : var(--base-background-color);
--cover-background-image : ;
--cover-background-mask-color : var(--base-background-color);
--cover-background-mask-opacity : 0.8;
--cover-background-mask-visibility : ;
--cover-background-position : center center;
--cover-background-repeat : no-repeat;
--cover-background-size : cover;
/* Blockquote (Subtitle) */
--cover-blockquote-color : ;
--cover-blockquote-font-size : var(--font-size-l);
/* Border */
--cover-border-inset : ;
--cover-border-color : var(--theme-color);
--cover-border-width : ;
/* Buttons */
--cover-button-background : ;
--cover-button-background--hover : ;
--cover-button-border : 1px solid var(--theme-color);
--cover-button-border--hover : ;
--cover-button-border-radius : var(--border-radius-m);
--cover-button-box-shadow : ;
--cover-button-box-shadow--hover : ;
--cover-button-color : var(--theme-color);
--cover-button-color--hover : ;
--cover-button-padding : 0.5em 2rem;
--cover-button-text-decoration : none;
--cover-button-text-decoration--hover : ;
--cover-button-text-decoration-color : ;
--cover-button-text-decoration-color--hover : ;
--cover-button-transition : all var(--duration-fast) ease-in-out;
/* Buttons - Primary */
--cover-button-primary-background : var(--theme-color);
--cover-button-primary-background--hover : ;
--cover-button-primary-border : 1px solid var(--theme-color);
--cover-button-primary-border--hover : ;
--cover-button-primary-box-shadow : ;
--cover-button-primary-box-shadow--hover : ;
--cover-button-primary-color : #fff;
--cover-button-primary-color--hover : ;
--cover-button-primary-text-decoration : ;
--cover-button-primary-text-decoration--hover : ;
--cover-button-primary-text-decoration-color : ;
--cover-button-primary-text-decoration-color--hover: ;
/* Heading */
--cover-heading-color : var(--theme-color);
--cover-heading-font-size : var(--font-size-xxl);
--cover-heading-font-size-min : ;
--cover-heading-font-size-max : ;
--cover-heading-font-weight : ;
/* Links */
--cover-link-border-bottom : ;
--cover-link-border-bottom--hover : ;
--cover-link-color : ;
--cover-link-color--hover : ;
--cover-link-text-decoration : underline;
--cover-link-text-decoration--hover : ;
--cover-link-text-decoration-color : ;
--cover-link-text-decoration-color--hover : ;
}
| {
"content_hash": "3937ba6602db1cbadd8d3b6a9aabb5a1",
"timestamp": "",
"source": "github",
"line_count": 76,
"max_line_length": 94,
"avg_line_length": 53.05263157894737,
"alnum_prop": 0.42485119047619047,
"repo_name": "mojo2012/spot-framework",
"id": "9263a473b1842c1796780443680b9ed307a9c18a",
"size": "4032",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "docs/node_modules/docsify-themeable/src/scss/themes/defaults/_cover.css",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "10146"
},
{
"name": "HTML",
"bytes": "10317"
},
{
"name": "Java",
"bytes": "997187"
}
],
"symlink_target": ""
} |
package geek.lawsof.physics.network.proxy
/**
* Created by anshuman on 28-05-2014.
*/
class ServerProxy extends ModProxy {
override def preInit(): Unit = {}
override def init(): Unit = {}
}
| {
"content_hash": "ed7467d879eac17ba49d681e1c3d40b7",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 41,
"avg_line_length": 19.8,
"alnum_prop": 0.6818181818181818,
"repo_name": "GeckoTheGeek42/TheLawsOfPhysics",
"id": "c40546beb2dda42342d204093e4d8e6462937302",
"size": "198",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/scala/geek/lawsof/physics/network/proxy/ServerProxy.scala",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Groovy",
"bytes": "3458"
},
{
"name": "Java",
"bytes": "347"
},
{
"name": "Scala",
"bytes": "94411"
},
{
"name": "Shell",
"bytes": "79"
}
],
"symlink_target": ""
} |
Czecoin-qt: Qt5 GUI for Czecoin
===============================
Build instructions
===================
Debian
-------
First, make sure that the required packages for Qt5 development of your
distribution are installed, for Debian and Ubuntu these are:
::
apt-get install qt5-default qt5-qmake qtbase5-dev-tools qttools5-dev-tools \
build-essential libboost-dev libboost-system-dev \
libboost-filesystem-dev libboost-program-options-dev libboost-thread-dev \
libssl-dev libdb++-dev
then execute the following:
::
qmake
make
Alternatively, install Qt Creator and open the `Czecoin-qt.pro` file.
An executable named `Czecoin-qt` will be built.
Windows
--------
Windows build instructions:
- Download the `QT Windows SDK`_ and install it. You don't need the Symbian stuff, just the desktop Qt.
- Download and extract the `dependencies archive`_ [#]_, or compile openssl, boost and dbcxx yourself.
- Copy the contents of the folder "deps" to "X:\\QtSDK\\mingw", replace X:\\ with the location where you installed the Qt SDK. Make sure that the contents of "deps\\include" end up in the current "include" directory.
- Open the .pro file in QT creator and build as normal (ctrl-B)
.. _`QT Windows SDK`: http://qt.nokia.com/downloads/sdk-windows-cpp
.. _`dependencies archive`: https://download.visucore.com/Czecoin/qtgui_deps_1.zip
.. [#] PGP signature: https://download.visucore.com/Czecoin/qtgui_deps_1.zip.sig (signed with RSA key ID `610945D0`_)
.. _`610945D0`: http://pgp.mit.edu:11371/pks/lookup?op=get&search=0x610945D0
Mac OS X
--------
- Download and install the `Qt Mac OS X SDK`_. It is recommended to also install Apple's Xcode with UNIX tools.
- Download and install `MacPorts`_.
- Execute the following commands in a terminal to get the dependencies:
::
sudo port selfupdate
sudo port install boost db48 miniupnpc
- Open the .pro file in Qt Creator and build as normal (cmd-B)
.. _`Qt Mac OS X SDK`: http://qt.nokia.com/downloads/sdk-mac-os-cpp
.. _`MacPorts`: http://www.macports.org/install.php
Build configuration options
============================
UPNnP port forwarding
---------------------
To use UPnP for port forwarding behind a NAT router (recommended, as more connections overall allow for a faster and more stable Czecoin experience), pass the following argument to qmake:
::
qmake "USE_UPNP=1"
(in **Qt Creator**, you can find the setting for additional qmake arguments under "Projects" -> "Build Settings" -> "Build Steps", then click "Details" next to **qmake**)
This requires miniupnpc for UPnP port mapping. It can be downloaded from
http://miniupnp.tuxfamily.org/files/. UPnP support is not compiled in by default.
Set USE_UPNP to a different value to control this:
+------------+--------------------------------------------------------------------------+
| USE_UPNP=- | no UPnP support, miniupnpc not required; |
+------------+--------------------------------------------------------------------------+
| USE_UPNP=0 | (the default) built with UPnP, support turned off by default at runtime; |
+------------+--------------------------------------------------------------------------+
| USE_UPNP=1 | build with UPnP support turned on by default at runtime. |
+------------+--------------------------------------------------------------------------+
Notification support for recent (k)ubuntu versions
---------------------------------------------------
To see desktop notifications on (k)ubuntu versions starting from 10.04, enable usage of the
FreeDesktop notification interface through DBUS using the following qmake option:
::
qmake "USE_DBUS=1"
Generation of QR codes
-----------------------
libqrencode may be used to generate QRCode images for payment requests.
It can be downloaded from http://fukuchi.org/works/qrencode/index.html.en, or installed via your package manager. Pass the USE_QRCODE
flag to qmake to control this:
+--------------+--------------------------------------------------------------------------+
| USE_QRCODE=0 | (the default) No QRCode support - libarcode not required |
+--------------+--------------------------------------------------------------------------+
| USE_QRCODE=1 | QRCode support enabled |
+--------------+--------------------------------------------------------------------------+
Berkely DB version warning
==========================
A warning for people using the *static binary* version of Czecoin on a Linux/UNIX-ish system (tl;dr: **Berkely DB databases are not forward compatible**).
The static binary version of Czecoin is linked against libdb 5.0 (see also `this Debian issue`_).
Now the nasty thing is that databases from 5.X are not compatible with 4.X.
If the globally installed development package of Berkely DB installed on your system is 5.X, any source you
build yourself will be linked against that. The first time you run with a 5.X version the database will be upgraded,
and 4.X cannot open the new format. This means that you cannot go back to the old statically linked version without
significant hassle!
.. _`this Debian issue`: http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=621425
Ubuntu 11.10 warning
====================
Ubuntu 11.10 has a package called 'qt-at-spi' installed by default. At the time of writing, having that package
installed causes Czecoin-qt to crash intermittently. The issue has been reported as `launchpad bug 857790`_, but
isn't yet fixed.
Until the bug is fixed, you can remove the qt-at-spi package to work around the problem, though this will presumably
disable screen reader functionality for Qt apps:
::
sudo apt-get remove qt-at-spi
.. _`launchpad bug 857790`: https://bugs.launchpad.net/ubuntu/+source/qt-at-spi/+bug/857790
| {
"content_hash": "34800e822a483083e946c8cfef1f974e",
"timestamp": "",
"source": "github",
"line_count": 152,
"max_line_length": 216,
"avg_line_length": 38.671052631578945,
"alnum_prop": 0.6236815243280027,
"repo_name": "Czecoin-project/Czecoin-master",
"id": "1269db1da17a4b1681b3df9fbc67748fe272ac66",
"size": "5878",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/readme-qt.rst",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "51312"
},
{
"name": "C",
"bytes": "3074674"
},
{
"name": "C++",
"bytes": "3428116"
},
{
"name": "CSS",
"bytes": "1127"
},
{
"name": "Objective-C++",
"bytes": "3538"
},
{
"name": "Python",
"bytes": "11646"
},
{
"name": "Shell",
"bytes": "1026"
},
{
"name": "TypeScript",
"bytes": "7758981"
}
],
"symlink_target": ""
} |
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
/**
* DescribeLicenses.java
*
* This file was auto-generated from WSDL
* by the Apache Axis2 version: 1.5.6 Built on : Aug 30, 2011 (10:01:01 CEST)
*/
package com.amazon.ec2;
/**
* DescribeLicenses bean class
*/
public class DescribeLicenses
implements org.apache.axis2.databinding.ADBBean{
public static final javax.xml.namespace.QName MY_QNAME = new javax.xml.namespace.QName(
"http://ec2.amazonaws.com/doc/2012-08-15/",
"DescribeLicenses",
"ns1");
private static java.lang.String generatePrefix(java.lang.String namespace) {
if(namespace.equals("http://ec2.amazonaws.com/doc/2012-08-15/")){
return "ns1";
}
return org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix();
}
/**
* field for DescribeLicenses
*/
protected com.amazon.ec2.DescribeLicensesType localDescribeLicenses ;
/**
* Auto generated getter method
* @return com.amazon.ec2.DescribeLicensesType
*/
public com.amazon.ec2.DescribeLicensesType getDescribeLicenses(){
return localDescribeLicenses;
}
/**
* Auto generated setter method
* @param param DescribeLicenses
*/
public void setDescribeLicenses(com.amazon.ec2.DescribeLicensesType param){
this.localDescribeLicenses=param;
}
/**
* isReaderMTOMAware
* @return true if the reader supports MTOM
*/
public static boolean isReaderMTOMAware(javax.xml.stream.XMLStreamReader reader) {
boolean isReaderMTOMAware = false;
try{
isReaderMTOMAware = java.lang.Boolean.TRUE.equals(reader.getProperty(org.apache.axiom.om.OMConstants.IS_DATA_HANDLERS_AWARE));
}catch(java.lang.IllegalArgumentException e){
isReaderMTOMAware = false;
}
return isReaderMTOMAware;
}
/**
*
* @param parentQName
* @param factory
* @return org.apache.axiom.om.OMElement
*/
public org.apache.axiom.om.OMElement getOMElement (
final javax.xml.namespace.QName parentQName,
final org.apache.axiom.om.OMFactory factory) throws org.apache.axis2.databinding.ADBException{
org.apache.axiom.om.OMDataSource dataSource =
new org.apache.axis2.databinding.ADBDataSource(this,MY_QNAME){
public void serialize(org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
DescribeLicenses.this.serialize(MY_QNAME,factory,xmlWriter);
}
};
return new org.apache.axiom.om.impl.llom.OMSourcedElementImpl(
MY_QNAME,factory,dataSource);
}
public void serialize(final javax.xml.namespace.QName parentQName,
final org.apache.axiom.om.OMFactory factory,
org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter)
throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{
serialize(parentQName,factory,xmlWriter,false);
}
public void serialize(final javax.xml.namespace.QName parentQName,
final org.apache.axiom.om.OMFactory factory,
org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter,
boolean serializeType)
throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{
//We can safely assume an element has only one type associated with it
if (localDescribeLicenses==null){
throw new org.apache.axis2.databinding.ADBException("Property cannot be null!");
}
localDescribeLicenses.serialize(MY_QNAME,factory,xmlWriter);
}
/**
* Util method to write an attribute with the ns prefix
*/
private void writeAttribute(java.lang.String prefix,java.lang.String namespace,java.lang.String attName,
java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{
if (xmlWriter.getPrefix(namespace) == null) {
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
xmlWriter.writeAttribute(namespace,attName,attValue);
}
/**
* Util method to write an attribute without the ns prefix
*/
private void writeAttribute(java.lang.String namespace,java.lang.String attName,
java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{
if (namespace.equals(""))
{
xmlWriter.writeAttribute(attName,attValue);
}
else
{
registerPrefix(xmlWriter, namespace);
xmlWriter.writeAttribute(namespace,attName,attValue);
}
}
/**
* Util method to write an attribute without the ns prefix
*/
private void writeQNameAttribute(java.lang.String namespace, java.lang.String attName,
javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
java.lang.String attributeNamespace = qname.getNamespaceURI();
java.lang.String attributePrefix = xmlWriter.getPrefix(attributeNamespace);
if (attributePrefix == null) {
attributePrefix = registerPrefix(xmlWriter, attributeNamespace);
}
java.lang.String attributeValue;
if (attributePrefix.trim().length() > 0) {
attributeValue = attributePrefix + ":" + qname.getLocalPart();
} else {
attributeValue = qname.getLocalPart();
}
if (namespace.equals("")) {
xmlWriter.writeAttribute(attName, attributeValue);
} else {
registerPrefix(xmlWriter, namespace);
xmlWriter.writeAttribute(namespace, attName, attributeValue);
}
}
/**
* method to handle Qnames
*/
private void writeQName(javax.xml.namespace.QName qname,
javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
java.lang.String namespaceURI = qname.getNamespaceURI();
if (namespaceURI != null) {
java.lang.String prefix = xmlWriter.getPrefix(namespaceURI);
if (prefix == null) {
prefix = generatePrefix(namespaceURI);
xmlWriter.writeNamespace(prefix, namespaceURI);
xmlWriter.setPrefix(prefix,namespaceURI);
}
if (prefix.trim().length() > 0){
xmlWriter.writeCharacters(prefix + ":" + org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
} else {
// i.e this is the default namespace
xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
}
} else {
xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
}
}
private void writeQNames(javax.xml.namespace.QName[] qnames,
javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
if (qnames != null) {
// we have to store this data until last moment since it is not possible to write any
// namespace data after writing the charactor data
java.lang.StringBuffer stringToWrite = new java.lang.StringBuffer();
java.lang.String namespaceURI = null;
java.lang.String prefix = null;
for (int i = 0; i < qnames.length; i++) {
if (i > 0) {
stringToWrite.append(" ");
}
namespaceURI = qnames[i].getNamespaceURI();
if (namespaceURI != null) {
prefix = xmlWriter.getPrefix(namespaceURI);
if ((prefix == null) || (prefix.length() == 0)) {
prefix = generatePrefix(namespaceURI);
xmlWriter.writeNamespace(prefix, namespaceURI);
xmlWriter.setPrefix(prefix,namespaceURI);
}
if (prefix.trim().length() > 0){
stringToWrite.append(prefix).append(":").append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i]));
} else {
stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i]));
}
} else {
stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i]));
}
}
xmlWriter.writeCharacters(stringToWrite.toString());
}
}
/**
* Register a namespace prefix
*/
private java.lang.String registerPrefix(javax.xml.stream.XMLStreamWriter xmlWriter, java.lang.String namespace) throws javax.xml.stream.XMLStreamException {
java.lang.String prefix = xmlWriter.getPrefix(namespace);
if (prefix == null) {
prefix = generatePrefix(namespace);
while (xmlWriter.getNamespaceContext().getNamespaceURI(prefix) != null) {
prefix = org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix();
}
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
return prefix;
}
/**
* databinding method to get an XML representation of this object
*
*/
public javax.xml.stream.XMLStreamReader getPullParser(javax.xml.namespace.QName qName)
throws org.apache.axis2.databinding.ADBException{
//We can safely assume an element has only one type associated with it
return localDescribeLicenses.getPullParser(MY_QNAME);
}
/**
* Factory class that keeps the parse method
*/
public static class Factory{
/**
* static method to create the object
* Precondition: If this object is an element, the current or next start element starts this object and any intervening reader events are ignorable
* If this object is not an element, it is a complex type and the reader is at the event just after the outer start element
* Postcondition: If this object is an element, the reader is positioned at its end element
* If this object is a complex type, the reader is positioned at the end element of its outer element
*/
public static DescribeLicenses parse(javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception{
DescribeLicenses object =
new DescribeLicenses();
int event;
java.lang.String nillableValue = null;
java.lang.String prefix ="";
java.lang.String namespaceuri ="";
try {
while (!reader.isStartElement() && !reader.isEndElement())
reader.next();
// Note all attributes that were handled. Used to differ normal attributes
// from anyAttributes.
java.util.Vector handledAttributes = new java.util.Vector();
while(!reader.isEndElement()) {
if (reader.isStartElement() ){
if (reader.isStartElement() && new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2012-08-15/","DescribeLicenses").equals(reader.getName())){
object.setDescribeLicenses(com.amazon.ec2.DescribeLicensesType.Factory.parse(reader));
} // End of if for expected property start element
else{
// A start element we are not expecting indicates an invalid parameter was passed
throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getLocalName());
}
} else {
reader.next();
}
} // end of while loop
} catch (javax.xml.stream.XMLStreamException e) {
throw new java.lang.Exception(e);
}
return object;
}
}//end of factory class
}
| {
"content_hash": "21712e2ef1afa315d2d23982d50f164c",
"timestamp": "",
"source": "github",
"line_count": 378,
"max_line_length": 186,
"avg_line_length": 41.85978835978836,
"alnum_prop": 0.5285344119319977,
"repo_name": "mufaddalq/cloudstack-datera-driver",
"id": "84fa595a5f9920c92f111c4ecfd873a2884f54bc",
"size": "15823",
"binary": false,
"copies": "1",
"ref": "refs/heads/4.2",
"path": "awsapi/src/com/amazon/ec2/DescribeLicenses.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "250"
},
{
"name": "Batchfile",
"bytes": "6317"
},
{
"name": "CSS",
"bytes": "302008"
},
{
"name": "FreeMarker",
"bytes": "4917"
},
{
"name": "HTML",
"bytes": "38671"
},
{
"name": "Java",
"bytes": "79758943"
},
{
"name": "JavaScript",
"bytes": "4237188"
},
{
"name": "Perl",
"bytes": "1879"
},
{
"name": "Python",
"bytes": "5187499"
},
{
"name": "Shell",
"bytes": "803262"
}
],
"symlink_target": ""
} |
<?php
/**
* WPSEO plugin file.
*
* @package WPSEO\Internals
* @since 3.6
*/
/**
* This class checks if the wpseo option doesn't exists. In the case it doesn't it will set a property that is
* accessible via a method to check if the installation is fresh.
*/
class WPSEO_Installation {
/**
* Checks if Yoast SEO is installed for the first time.
*/
public function __construct() {
$is_first_install = $this->is_first_install();
if ( $is_first_install && WPSEO_Utils::is_api_available() ) {
add_action( 'wpseo_activate', array( $this, 'set_first_install_options' ) );
}
}
/**
* When the option doesn't exist, it should be a new install.
*
* @return bool
*/
private function is_first_install() {
return ( get_option( 'wpseo' ) === false );
}
/**
* Sets the options on first install for showing the installation notice and disabling of the settings pages.
*/
public function set_first_install_options() {
$options = get_option( 'wpseo' );
$options['show_onboarding_notice'] = true;
$options['first_activated_on'] = time();
update_option( 'wpseo', $options );
}
}
| {
"content_hash": "ffbf853bee90838baa45238277aacee1",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 110,
"avg_line_length": 24.41304347826087,
"alnum_prop": 0.6500445235975066,
"repo_name": "mandino/hotelmilosantabarbara.com",
"id": "f94592732af08007fd3c1b229bb2b970d5b6afee",
"size": "1123",
"binary": false,
"copies": "39",
"ref": "refs/heads/master",
"path": "wp-content/plugins/wordpress-seo/inc/class-wpseo-installation.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4421076"
},
{
"name": "HTML",
"bytes": "377475"
},
{
"name": "JavaScript",
"bytes": "6259360"
},
{
"name": "PHP",
"bytes": "30321979"
},
{
"name": "Ruby",
"bytes": "2879"
},
{
"name": "Shell",
"bytes": "1145"
},
{
"name": "Smarty",
"bytes": "200578"
},
{
"name": "XSLT",
"bytes": "9376"
}
],
"symlink_target": ""
} |
package com.doctor.dubbo.demo.api;
import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ProtocolConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import com.alibaba.dubbo.config.ServiceConfig;
/**
* @author sdcuike
*
* 编程API暴露服务
* Create At 2016年4月12日 上午10:36:28
*/
public class DubboDemoProvider {
static String address = "127.0.0.1:2181";
public static void main(String[] args) {
// 服务实现
DemoService demoService = new DemoServiceImpl();
// 当前应用配置
ApplicationConfig applicationConfig = new ApplicationConfig("demoService");
applicationConfig.setLogger("slf4j");
applicationConfig.setCompiler("javassist");
// 连接注册中心配置
RegistryConfig registryConfig = new RegistryConfig(address);
registryConfig.setClient("curator");
registryConfig.setGroup("dubbo");
registryConfig.setProtocol("zookeeper");
// 服务提供者协议配置
ProtocolConfig protocolConfig = new ProtocolConfig("resteasy", 7788);
protocolConfig.setIothreads(2);
protocolConfig.setThreads(3);
protocolConfig.setServer("netty");
protocolConfig.setHost("0.0.0.0");
// 服务提供者暴露服务配置
ServiceConfig<DemoService> demoServiceConfig = new ServiceConfig<>();
demoServiceConfig.setApplication(applicationConfig);
demoServiceConfig.setRegistry(registryConfig);
demoServiceConfig.setProtocol(protocolConfig);
demoServiceConfig.setInterface(DemoService.class);
demoServiceConfig.setRef(demoService);
demoServiceConfig.export();
}
}
| {
"content_hash": "28a63ca2de946425866bac975be376e5",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 83,
"avg_line_length": 34.104166666666664,
"alnum_prop": 0.6939523518631643,
"repo_name": "sdcuike/book-reading",
"id": "026e8742b299fc8a86e27ba83f755e10eda4eadf",
"size": "1735",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spring-learning/src/main/java/com/doctor/dubbo/demo/api/DubboDemoProvider.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "129839"
},
{
"name": "JavaScript",
"bytes": "5205"
},
{
"name": "Lua",
"bytes": "6726"
},
{
"name": "Shell",
"bytes": "240"
}
],
"symlink_target": ""
} |
package com.flat502.rox.marshal;
/**
* An interface representing a generalized RPC method
* call fault.
* <p>
* This interface is patterned after XML-RPC and extends
* the {@link com.flat502.rox.marshal.RpcResponse} interface
* by adding the idea of a fault code and fault string.
*/
public interface RpcFault extends RpcResponse {
/**
* Get the fault code for this RPC fault.
* <P>
* Fault codes are implementation-dependent.
* @return
* The fault code for this RPC fault.
*/
int getFaultCode();
/**
* Get the fault string describing the fault
* code and the fault in more detail.
* <p>
* Fault strings are implementation-dependent.
* In general fault codes should be used for
* programmatic handling of faults and fault
* strings for display only.
* @return
* The fault string for this RPC fault.
*/
String getFaultString();
}
| {
"content_hash": "f4430fea4ee87bacb06600273f12559d",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 60,
"avg_line_length": 26.545454545454547,
"alnum_prop": 0.704337899543379,
"repo_name": "cameronbraid/rox",
"id": "cdc0594c7114a4d21df1488618a5a28a0a2b944f",
"size": "876",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/main/java/com/flat502/rox/marshal/RpcFault.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Java",
"bytes": "953998"
}
],
"symlink_target": ""
} |
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace BoardUtils {
public interface IPiece {
int Id {
get;
}
int ColorId {
get;
}
}
static public class Utils {
// http://www.dotnetperls.com/fisher-yates-shuffle
static public void Shuffle<T>(T[] array, int targetLength = int.MaxValue)
{
System.Random random = new System.Random();
int n = System.Math.Min(array.Length, targetLength);
for (int i = 0; i < n; i++)
{
// NextDouble returns a random number between 0 and 1.
// ... It is equivalent to Math.random() in Java.
int r = i + (int)(random.NextDouble() * (n - i));
T t = array[r];
array[r] = array[i];
array[i] = t;
}
}
}
} | {
"content_hash": "bd61a19d7dfde615f3ecc4c58a10add2",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 75,
"avg_line_length": 21.5,
"alnum_prop": 0.6224350205198358,
"repo_name": "maxtangli/ChinaChess",
"id": "03978a6dab5d3756e6872cfe6b2f2a640d14353a",
"size": "731",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ChinaChess/ChinaChess/BoardUtil/Utils.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "51591"
}
],
"symlink_target": ""
} |
angular.module('wedSite.links',[
'ui.router'
])
.config(['$stateProvider',function config( $stateProvider ) {
$stateProvider.state( 'links', {
url: '/links',
views: {
"main": {
controller: 'LinksCtrl',
templateUrl: 'links/links.tpl.html'
}
},
data:{ pageTitle: 'Links' }
});
}])
.controller('LinksCtrl',[
'$scope',
function($scope){
}
])
; | {
"content_hash": "e4a9ae956d1215d9666d1c04e7a62d57",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 61,
"avg_line_length": 19.583333333333332,
"alnum_prop": 0.4702127659574468,
"repo_name": "Lein-Haz/wedsite",
"id": "52909a5a51674fc007daab5029354748ceab67e9",
"size": "470",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/links/links.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "24704"
},
{
"name": "HTML",
"bytes": "10611"
},
{
"name": "JavaScript",
"bytes": "51524"
}
],
"symlink_target": ""
} |
typedef NS_ENUM(NSUInteger, YGPulseViewAnimationType) {
YGPulseViewAnimationTypeRegularPulsing,
YGPulseViewAnimationTypeRadarPulsing
};
@interface UIView (YGPulseView)
- (void)startPulseWithColor:(UIColor *)color;
- (void)startPulseWithColor:(UIColor *)color animation:(YGPulseViewAnimationType)animationType;
- (void)startPulseWithColor:(UIColor *)color scaleFrom:(CGFloat)initialScale to:(CGFloat)finishScale frequency:(CGFloat)frequency opacity:(CGFloat)opacity animation:(YGPulseViewAnimationType)animationType;
- (void)stopPulse;
@end
| {
"content_hash": "81aebc8cecd7b40a574264e3b9892728",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 205,
"avg_line_length": 34.625,
"alnum_prop": 0.8194945848375451,
"repo_name": "LQJJ/demo",
"id": "95ed373d37c7808c903c6feca440c60a539b1854",
"size": "790",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "86-DZMeBookRead-master/DZMeBookRead/DZMeBookRead/other/thirdParty/YGPulseView/UIView+YGPulseView.h",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "5910716"
},
{
"name": "C++",
"bytes": "113072"
},
{
"name": "CSS",
"bytes": "10791"
},
{
"name": "Dockerfile",
"bytes": "934"
},
{
"name": "Go",
"bytes": "40121403"
},
{
"name": "Groovy",
"bytes": "347"
},
{
"name": "HTML",
"bytes": "359263"
},
{
"name": "JavaScript",
"bytes": "545384"
},
{
"name": "Makefile",
"bytes": "6671"
},
{
"name": "Mathematica",
"bytes": "14565"
},
{
"name": "Objective-C",
"bytes": "14900720"
},
{
"name": "Objective-C++",
"bytes": "20070"
},
{
"name": "PureBasic",
"bytes": "4152"
},
{
"name": "Python",
"bytes": "4490569"
},
{
"name": "Ruby",
"bytes": "44850"
},
{
"name": "Shell",
"bytes": "33251"
},
{
"name": "Swift",
"bytes": "463286"
},
{
"name": "TSQL",
"bytes": "108861"
}
],
"symlink_target": ""
} |
require 'spec_helper'
RSpec.describe OneviewSDK::API600::C7000::Scope, integration: true, type: UPDATE do
include_context 'integration api600 context'
subject(:item) { described_class.get_all($client_600).first }
subject(:enclosure) { OneviewSDK::API600::C7000::Enclosure.get_all($client_600).first }
subject(:server_hardware) { OneviewSDK::API600::C7000::ServerHardware.get_all($client_600).first }
include_examples 'ScopeUpdateExample', 'integration api600 context'
describe '::replace_resource_assigned_scope' do
it 'should replace the resource scope' do
options = {
name: 'new scope',
description: 'Sample Scope description'
}
scope = described_class.new($client_600, options)
scope.create
new_scopes = [scope['uri']]
old_scopes = described_class.get_resource_scopes($client_600, server_hardware)
expect { described_class.replace_resource_assigned_scopes($client_600, server_hardware, scopes: new_scopes) }.to_not raise_error
server_hardware.refresh
updated_resource_scopes = described_class.get_resource_scopes($client_600, server_hardware)['scopeUris']
expect(new_scopes).to match_array(updated_resource_scopes)
# Update the resource with old scopes
described_class.replace_resource_assigned_scopes($client_600, server_hardware, old_scopes)
current_scopes = described_class.get_resource_scopes($client_600, server_hardware)
expect(current_scopes).to match_array(old_scopes)
end
end
describe '::resource_patch' do
it 'should update the scope of resource' do
options = {
name: 'test scope',
description: 'Sample Scope description'
}
scope = described_class.new($client_600, options)
scope.create
old_scopes = described_class.get_resource_scopes($client_600, server_hardware)
expect { described_class.resource_patch($client_600, server_hardware, add_scopes: [scope], remove_scopes: [item]) }.to_not raise_error
new_scopes = described_class.get_resource_scopes($client_600, server_hardware)['scopeUris']
expect(new_scopes).to include(scope['uri'])
# scope_index = new_scopes.find_index { |uri| uri == scope['uri'] }
expect { described_class.resource_patch($client_600, server_hardware, add_scopes: [item], remove_scopes: [scope]) }.to_not raise_error
new_scopes = described_class.get_resource_scopes($client_600, server_hardware)
expect(old_scopes).to match_array(new_scopes)
end
end
end
| {
"content_hash": "74612b3f931b1ead659d7c2f9d575ae1",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 140,
"avg_line_length": 47.528301886792455,
"alnum_prop": 0.7018658197697499,
"repo_name": "HewlettPackard/oneview-sdk-ruby",
"id": "908abc48d8848dc7215f100fad9a181289e64c33",
"size": "3119",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "spec/integration/resource/api600/c7000/scope/update_spec.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Ruby",
"bytes": "2891159"
}
],
"symlink_target": ""
} |
"""Checker functions for filtering."""
from warnings import warn
import numpy as np
###################################################################################################
###################################################################################################
def check_filter_definition(pass_type, f_range):
"""Check a filter definition for validity, and get f_lo and f_hi.
Parameters
----------
pass_type : {'bandpass', 'bandstop', 'lowpass', 'highpass'}
Which kind of filter to apply:
* 'bandpass': apply a bandpass filter
* 'bandstop': apply a bandstop (notch) filter
* 'lowpass': apply a lowpass filter
* 'highpass' : apply a highpass filter
f_range : tuple of (float, float) or float
Cutoff frequency(ies) used for filter, specified as f_lo & f_hi.
For 'bandpass' & 'bandstop', must be a tuple.
For 'lowpass' or 'highpass', can be a float that specifies pass frequency, or can be
a tuple and is assumed to be (None, f_hi) for 'lowpass', and (f_lo, None) for 'highpass'.
Returns
-------
f_lo : float or None
The lower frequency range of the filter, specifying the highpass frequency, if specified.
f_hi : float or None
The higher frequency range of the filter, specifying the lowpass frequency, if specified.
"""
if pass_type not in ['bandpass', 'bandstop', 'lowpass', 'highpass']:
raise ValueError('Filter passtype not understood.')
## Check that frequency cutoff inputs are appropriate
# For band filters, 2 inputs required & second entry must be > first
if pass_type in ('bandpass', 'bandstop'):
if isinstance(f_range, tuple) and f_range[0] >= f_range[1]:
raise ValueError('Second cutoff frequency must be greater than first.')
elif isinstance(f_range, (int, float)) or len(f_range) != 2:
raise ValueError('Two cutoff frequencies required for bandpass and bandstop filters')
# Map f_range to f_lo and f_hi
f_lo, f_hi = f_range
# For lowpass and highpass can be tuple or int/float
if pass_type == 'lowpass':
if isinstance(f_range, (int, float)):
f_hi = f_range
elif isinstance(f_range, tuple):
f_hi = f_range[1]
f_lo = None
if pass_type == 'highpass':
if isinstance(f_range, (int, float)):
f_lo = f_range
elif isinstance(f_range, tuple):
f_lo = f_range[0]
f_hi = None
# Make sure pass freqs are floats
f_lo = float(f_lo) if f_lo else f_lo
f_hi = float(f_hi) if f_hi else f_hi
return f_lo, f_hi
def check_filter_properties(b_vals, a_vals, fs, pass_type, f_range, transitions=(-20, -3), verbose=True):
"""Check a filters properties, including pass band and transition band.
Parameters
----------
b_vals : 1d array
B value filter coefficients for a filter.
a_vals : 1d array
A value filter coefficients for a filter.
fs : float
Sampling rate, in Hz.
pass_type : {'bandpass', 'bandstop', 'lowpass', 'highpass'}
Which kind of filter to apply:
* 'bandpass': apply a bandpass filter
* 'bandstop': apply a bandstop (notch) filter
* 'lowpass': apply a lowpass filter
* 'highpass' : apply a highpass filter
f_range : tuple of (float, float) or float
Cutoff frequency(ies) used for filter, specified as f_lo & f_hi.
For 'bandpass' & 'bandstop', must be a tuple.
For 'lowpass' or 'highpass', can be a float that specifies pass frequency, or can be
a tuple and is assumed to be (None, f_hi) for 'lowpass', and (f_lo, None) for 'highpass'.
transitions : tuple of (float, float), optional, default: (-20, -3)
Cutoffs, in dB, that define the transition band.
verbose : bool, optional, default: True
Whether to print out transition and pass bands.
Returns
-------
passes : bool
Whether all the checks pass. False if one or more checks fail.
"""
# Import utility functions inside function to avoid circular imports
from neurodsp.filt.utils import (compute_frequency_response,
compute_pass_band, compute_transition_band)
# Initialize variable to keep track if all checks pass
passes = True
# Compute the frequency response
f_db, db = compute_frequency_response(b_vals, a_vals, fs)
# Check that frequency response goes below transition level (has significant attenuation)
if np.min(db) >= transitions[0]:
passes = False
warn('The filter attenuation never goes below {} dB.'\
'Increase filter length.'.format(transitions[0]))
# If there is no attenuation, cannot calculate bands, so return here
return passes
# Check that both sides of a bandpass have significant attenuation
if pass_type == 'bandpass':
if db[0] >= transitions[0] or db[-1] >= transitions[0]:
passes = False
warn('The low or high frequency stopband never gets attenuated by'\
'more than {} dB. Increase filter length.'.format(abs(transitions[0])))
# Compute pass & transition bandwidth
pass_bw = compute_pass_band(fs, pass_type, f_range)
transition_bw = compute_transition_band(f_db, db, transitions[0], transitions[1])
# Raise warning if transition bandwidth is too high
if transition_bw > pass_bw:
passes = False
warn('Transition bandwidth is {:.1f} Hz. This is greater than the desired'\
'pass/stop bandwidth of {:.1f} Hz'.format(transition_bw, pass_bw))
# Print out transition bandwidth and pass bandwidth to the user
if verbose:
print('Transition bandwidth is {:.1f} Hz.'.format(transition_bw))
print('Pass/stop bandwidth is {:.1f} Hz.'.format(pass_bw))
return passes
| {
"content_hash": "e63b33b7fe5c6162bdcc32208355898d",
"timestamp": "",
"source": "github",
"line_count": 146,
"max_line_length": 105,
"avg_line_length": 40.66438356164384,
"alnum_prop": 0.6090618157318511,
"repo_name": "srcole/neurodsp",
"id": "4140e88ce28973f969cc9a7d8610c00a4114ce74",
"size": "5937",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "neurodsp/filt/checks.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "878"
},
{
"name": "Makefile",
"bytes": "1550"
},
{
"name": "Python",
"bytes": "192864"
},
{
"name": "Shell",
"bytes": "771"
},
{
"name": "TeX",
"bytes": "6424"
}
],
"symlink_target": ""
} |
var zlib = require('zlib');
var inherits = require('util').inherits;
var crc32 = require('crc').crc32;
var DeflateCRC32Stream = module.exports = function (options) {
zlib.DeflateRaw.call(this, options);
this.checksum = new Buffer(4);
this.checksum.writeInt32BE(0, 0);
this.rawSize = 0;
this.compressedSize = 0;
// BC v0.8
if (typeof zlib.DeflateRaw.prototype.push !== 'function') {
this.on('data', function(chunk) {
if (chunk) {
this.compressedSize += chunk.length;
}
});
}
};
inherits(DeflateCRC32Stream, zlib.DeflateRaw);
DeflateCRC32Stream.prototype.push = function(chunk, encoding) {
if (chunk) {
this.compressedSize += chunk.length;
}
return zlib.DeflateRaw.prototype.push.call(this, chunk, encoding);
};
DeflateCRC32Stream.prototype.write = function(chunk, enc, cb) {
if (chunk) {
this.checksum = crc32(chunk, this.checksum);
this.rawSize += chunk.length;
}
return zlib.DeflateRaw.prototype.write.call(this, chunk, enc, cb);
};
DeflateCRC32Stream.prototype.digest = function(encoding) {
var checksum = new Buffer(4);
checksum.writeUInt32BE(this.checksum >>> 0, 0);
return encoding ? checksum.toString(encoding) : checksum;
};
DeflateCRC32Stream.prototype.hex = function() {
return this.digest('hex').toUpperCase();
};
DeflateCRC32Stream.prototype.size = function(compressed) {
compressed = compressed || false;
if (compressed) {
return this.compressedSize;
} else {
return this.rawSize;
}
};
| {
"content_hash": "66f82e5ede459cce4a9f072fb25c9bc3",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 68,
"avg_line_length": 23.88888888888889,
"alnum_prop": 0.6857142857142857,
"repo_name": "kimyou7/MyDetail",
"id": "978a766fcca1d552087339bf203e4eee5e4fc3ad",
"size": "1700",
"binary": false,
"copies": "12",
"ref": "refs/heads/master",
"path": "node_modules/crc32-stream/lib/deflate-crc32-stream.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3050"
},
{
"name": "HTML",
"bytes": "35836"
},
{
"name": "JavaScript",
"bytes": "20642"
}
],
"symlink_target": ""
} |
function UserAndJobState(url, auth, auth_cb) {
this.url = url;
var _url = url;
var deprecationWarningSent = false;
function deprecationWarning() {
if (!deprecationWarningSent) {
deprecationWarningSent = true;
if (!window.console) return;
console.log(
"DEPRECATION WARNING: '*_async' method names will be removed",
"in a future version. Please use the identical methods without",
"the'_async' suffix.");
}
}
if (typeof(_url) != "string" || _url.length == 0) {
_url = "https://kbase.us/services/userandjobstate/";
}
var _auth = auth ? auth : { 'token' : '', 'user_id' : ''};
var _auth_cb = auth_cb;
this.set_state = function (service, key, value, _callback, _errorCallback) {
return json_call_ajax("UserAndJobState.set_state",
[service, key, value], 0, _callback, _errorCallback);
};
this.set_state_async = function (service, key, value, _callback, _error_callback) {
deprecationWarning();
return json_call_ajax("UserAndJobState.set_state", [service, key, value], 0, _callback, _error_callback);
};
this.set_state_auth = function (token, key, value, _callback, _errorCallback) {
return json_call_ajax("UserAndJobState.set_state_auth",
[token, key, value], 0, _callback, _errorCallback);
};
this.set_state_auth_async = function (token, key, value, _callback, _error_callback) {
deprecationWarning();
return json_call_ajax("UserAndJobState.set_state_auth", [token, key, value], 0, _callback, _error_callback);
};
this.get_state = function (service, key, auth, _callback, _errorCallback) {
return json_call_ajax("UserAndJobState.get_state",
[service, key, auth], 1, _callback, _errorCallback);
};
this.get_state_async = function (service, key, auth, _callback, _error_callback) {
deprecationWarning();
return json_call_ajax("UserAndJobState.get_state", [service, key, auth], 1, _callback, _error_callback);
};
this.remove_state = function (service, key, _callback, _errorCallback) {
return json_call_ajax("UserAndJobState.remove_state",
[service, key], 0, _callback, _errorCallback);
};
this.remove_state_async = function (service, key, _callback, _error_callback) {
deprecationWarning();
return json_call_ajax("UserAndJobState.remove_state", [service, key], 0, _callback, _error_callback);
};
this.remove_state_auth = function (token, key, _callback, _errorCallback) {
return json_call_ajax("UserAndJobState.remove_state_auth",
[token, key], 0, _callback, _errorCallback);
};
this.remove_state_auth_async = function (token, key, _callback, _error_callback) {
deprecationWarning();
return json_call_ajax("UserAndJobState.remove_state_auth", [token, key], 0, _callback, _error_callback);
};
this.list_state = function (service, auth, _callback, _errorCallback) {
return json_call_ajax("UserAndJobState.list_state",
[service, auth], 1, _callback, _errorCallback);
};
this.list_state_async = function (service, auth, _callback, _error_callback) {
deprecationWarning();
return json_call_ajax("UserAndJobState.list_state", [service, auth], 1, _callback, _error_callback);
};
this.list_state_services = function (auth, _callback, _errorCallback) {
return json_call_ajax("UserAndJobState.list_state_services",
[auth], 1, _callback, _errorCallback);
};
this.list_state_services_async = function (auth, _callback, _error_callback) {
deprecationWarning();
return json_call_ajax("UserAndJobState.list_state_services", [auth], 1, _callback, _error_callback);
};
this.create_job = function (_callback, _errorCallback) {
return json_call_ajax("UserAndJobState.create_job",
[], 1, _callback, _errorCallback);
};
this.create_job_async = function (_callback, _error_callback) {
deprecationWarning();
return json_call_ajax("UserAndJobState.create_job", [], 1, _callback, _error_callback);
};
this.start_job = function (job, token, status, desc, progress, est_complete, _callback, _errorCallback) {
return json_call_ajax("UserAndJobState.start_job",
[job, token, status, desc, progress, est_complete], 0, _callback, _errorCallback);
};
this.start_job_async = function (job, token, status, desc, progress, est_complete, _callback, _error_callback) {
deprecationWarning();
return json_call_ajax("UserAndJobState.start_job", [job, token, status, desc, progress, est_complete], 0, _callback, _error_callback);
};
this.create_and_start_job = function (token, status, desc, progress, est_complete, _callback, _errorCallback) {
return json_call_ajax("UserAndJobState.create_and_start_job",
[token, status, desc, progress, est_complete], 1, _callback, _errorCallback);
};
this.create_and_start_job_async = function (token, status, desc, progress, est_complete, _callback, _error_callback) {
deprecationWarning();
return json_call_ajax("UserAndJobState.create_and_start_job", [token, status, desc, progress, est_complete], 1, _callback, _error_callback);
};
this.update_job_progress = function (job, token, status, prog, est_complete, _callback, _errorCallback) {
return json_call_ajax("UserAndJobState.update_job_progress",
[job, token, status, prog, est_complete], 0, _callback, _errorCallback);
};
this.update_job_progress_async = function (job, token, status, prog, est_complete, _callback, _error_callback) {
deprecationWarning();
return json_call_ajax("UserAndJobState.update_job_progress", [job, token, status, prog, est_complete], 0, _callback, _error_callback);
};
this.update_job = function (job, token, status, est_complete, _callback, _errorCallback) {
return json_call_ajax("UserAndJobState.update_job",
[job, token, status, est_complete], 0, _callback, _errorCallback);
};
this.update_job_async = function (job, token, status, est_complete, _callback, _error_callback) {
deprecationWarning();
return json_call_ajax("UserAndJobState.update_job", [job, token, status, est_complete], 0, _callback, _error_callback);
};
this.get_job_description = function (job, _callback, _errorCallback) {
return json_call_ajax("UserAndJobState.get_job_description",
[job], 5, _callback, _errorCallback);
};
this.get_job_description_async = function (job, _callback, _error_callback) {
deprecationWarning();
return json_call_ajax("UserAndJobState.get_job_description", [job], 5, _callback, _error_callback);
};
this.get_job_status = function (job, _callback, _errorCallback) {
return json_call_ajax("UserAndJobState.get_job_status",
[job], 7, _callback, _errorCallback);
};
this.get_job_status_async = function (job, _callback, _error_callback) {
deprecationWarning();
return json_call_ajax("UserAndJobState.get_job_status", [job], 7, _callback, _error_callback);
};
this.complete_job = function (job, token, status, error, res, _callback, _errorCallback) {
return json_call_ajax("UserAndJobState.complete_job",
[job, token, status, error, res], 0, _callback, _errorCallback);
};
this.complete_job_async = function (job, token, status, error, res, _callback, _error_callback) {
deprecationWarning();
return json_call_ajax("UserAndJobState.complete_job", [job, token, status, error, res], 0, _callback, _error_callback);
};
this.get_results = function (job, _callback, _errorCallback) {
return json_call_ajax("UserAndJobState.get_results",
[job], 1, _callback, _errorCallback);
};
this.get_results_async = function (job, _callback, _error_callback) {
deprecationWarning();
return json_call_ajax("UserAndJobState.get_results", [job], 1, _callback, _error_callback);
};
this.get_detailed_error = function (job, _callback, _errorCallback) {
return json_call_ajax("UserAndJobState.get_detailed_error",
[job], 1, _callback, _errorCallback);
};
this.get_detailed_error_async = function (job, _callback, _error_callback) {
deprecationWarning();
return json_call_ajax("UserAndJobState.get_detailed_error", [job], 1, _callback, _error_callback);
};
this.get_job_info = function (job, _callback, _errorCallback) {
return json_call_ajax("UserAndJobState.get_job_info",
[job], 1, _callback, _errorCallback);
};
this.get_job_info_async = function (job, _callback, _error_callback) {
deprecationWarning();
return json_call_ajax("UserAndJobState.get_job_info", [job], 1, _callback, _error_callback);
};
this.list_jobs = function (services, filter, _callback, _errorCallback) {
return json_call_ajax("UserAndJobState.list_jobs",
[services, filter], 1, _callback, _errorCallback);
};
this.list_jobs_async = function (services, filter, _callback, _error_callback) {
deprecationWarning();
return json_call_ajax("UserAndJobState.list_jobs", [services, filter], 1, _callback, _error_callback);
};
this.list_job_services = function (_callback, _errorCallback) {
return json_call_ajax("UserAndJobState.list_job_services",
[], 1, _callback, _errorCallback);
};
this.list_job_services_async = function (_callback, _error_callback) {
deprecationWarning();
return json_call_ajax("UserAndJobState.list_job_services", [], 1, _callback, _error_callback);
};
this.share_job = function (job, users, _callback, _errorCallback) {
return json_call_ajax("UserAndJobState.share_job",
[job, users], 0, _callback, _errorCallback);
};
this.share_job_async = function (job, users, _callback, _error_callback) {
deprecationWarning();
return json_call_ajax("UserAndJobState.share_job", [job, users], 0, _callback, _error_callback);
};
this.unshare_job = function (job, users, _callback, _errorCallback) {
return json_call_ajax("UserAndJobState.unshare_job",
[job, users], 0, _callback, _errorCallback);
};
this.unshare_job_async = function (job, users, _callback, _error_callback) {
deprecationWarning();
return json_call_ajax("UserAndJobState.unshare_job", [job, users], 0, _callback, _error_callback);
};
this.get_job_owner = function (job, _callback, _errorCallback) {
return json_call_ajax("UserAndJobState.get_job_owner",
[job], 1, _callback, _errorCallback);
};
this.get_job_owner_async = function (job, _callback, _error_callback) {
deprecationWarning();
return json_call_ajax("UserAndJobState.get_job_owner", [job], 1, _callback, _error_callback);
};
this.get_job_shared = function (job, _callback, _errorCallback) {
return json_call_ajax("UserAndJobState.get_job_shared",
[job], 1, _callback, _errorCallback);
};
this.get_job_shared_async = function (job, _callback, _error_callback) {
deprecationWarning();
return json_call_ajax("UserAndJobState.get_job_shared", [job], 1, _callback, _error_callback);
};
this.delete_job = function (job, _callback, _errorCallback) {
return json_call_ajax("UserAndJobState.delete_job",
[job], 0, _callback, _errorCallback);
};
this.delete_job_async = function (job, _callback, _error_callback) {
deprecationWarning();
return json_call_ajax("UserAndJobState.delete_job", [job], 0, _callback, _error_callback);
};
this.force_delete_job = function (token, job, _callback, _errorCallback) {
return json_call_ajax("UserAndJobState.force_delete_job",
[token, job], 0, _callback, _errorCallback);
};
this.force_delete_job_async = function (token, job, _callback, _error_callback) {
deprecationWarning();
return json_call_ajax("UserAndJobState.force_delete_job", [token, job], 0, _callback, _error_callback);
};
/*
* JSON call using jQuery method.
*/
function json_call_ajax(method, params, numRets, callback, errorCallback) {
var deferred = $.Deferred();
if (typeof callback === 'function') {
deferred.done(callback);
}
if (typeof errorCallback === 'function') {
deferred.fail(errorCallback);
}
var rpc = {
params : params,
method : method,
version: "1.1",
id: String(Math.random()).slice(2),
};
var beforeSend = null;
var token = (_auth_cb && typeof _auth_cb === 'function') ? _auth_cb()
: (_auth.token ? _auth.token : null);
if (token != null) {
beforeSend = function (xhr) {
xhr.setRequestHeader("Authorization", token);
}
}
var xhr = jQuery.ajax({
url: _url,
dataType: "text",
type: 'POST',
processData: false,
data: JSON.stringify(rpc),
beforeSend: beforeSend,
success: function (data, status, xhr) {
var result;
try {
var resp = JSON.parse(data);
result = (numRets === 1 ? resp.result[0] : resp.result);
} catch (err) {
deferred.reject({
status: 503,
error: err,
url: _url,
resp: data
});
return;
}
deferred.resolve(result);
},
error: function (xhr, textStatus, errorThrown) {
var error;
if (xhr.responseText) {
try {
var resp = JSON.parse(xhr.responseText);
error = resp.error;
} catch (err) { // Not JSON
error = "Unknown error - " + xhr.responseText;
}
} else {
error = "Unknown Error";
}
deferred.reject({
status: 500,
error: error
});
}
});
var promise = deferred.promise();
promise.xhr = xhr;
return promise;
}
}
| {
"content_hash": "0413c1ea7b41539d38500e0911718a3b",
"timestamp": "",
"source": "github",
"line_count": 366,
"max_line_length": 148,
"avg_line_length": 40.58469945355191,
"alnum_prop": 0.5978187693550558,
"repo_name": "kbase/user_and_job_state",
"id": "3e288ffbb1ac452562b7d910cf3139d20e24589b",
"size": "14854",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "www/assets/external/kbase/js/userandjobstate.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "17581"
},
{
"name": "Dockerfile",
"bytes": "1880"
},
{
"name": "HTML",
"bytes": "127486"
},
{
"name": "Java",
"bytes": "544410"
},
{
"name": "JavaScript",
"bytes": "80688"
},
{
"name": "Makefile",
"bytes": "4304"
},
{
"name": "Perl",
"bytes": "122295"
},
{
"name": "Python",
"bytes": "78079"
},
{
"name": "Ruby",
"bytes": "16520"
},
{
"name": "Shell",
"bytes": "1117"
}
],
"symlink_target": ""
} |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file defines tests that implementations of GLImage should pass in order
// to be conformant.
#ifndef UI_GL_TEST_GL_IMAGE_TEST_TEMPLATE_H_
#define UI_GL_TEST_GL_IMAGE_TEST_TEMPLATE_H_
#include <stdint.h>
#include <memory>
#include "base/strings/stringize_macros.h"
#include "base/strings/stringprintf.h"
#include "build/build_config.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/gfx/buffer_format_util.h"
#include "ui/gfx/buffer_types.h"
#include "ui/gl/gl_bindings.h"
#include "ui/gl/gl_context.h"
#include "ui/gl/gl_helper.h"
#include "ui/gl/gl_image.h"
#include "ui/gl/gl_implementation.h"
#include "ui/gl/gl_surface.h"
#include "ui/gl/init/gl_factory.h"
#include "ui/gl/test/gl_image_test_support.h"
#include "ui/gl/test/gl_test_helper.h"
#if defined(OS_MACOSX)
#include "base/mac/mac_util.h"
#endif
namespace gl {
namespace {
// Compiles a fragment shader for sampling out of a texture of |size| bound to
// |target| and checks for compilation errors.
GLuint LoadFragmentShader(unsigned target, const gfx::Size& size) {
// clang-format off
const char kFragmentShader[] = STRINGIZE(
uniform SamplerType a_texture;
varying vec2 v_texCoord;
void main() {
gl_FragColor = TextureLookup(a_texture, v_texCoord * TextureScale);
}
);
const char kShaderFloatPrecision[] = STRINGIZE(
precision mediump float;
);
// clang-format on
bool is_gles = gfx::GetGLImplementation() == gfx::kGLImplementationEGLGLES2;
switch (target) {
case GL_TEXTURE_2D:
return gfx::GLHelper::LoadShader(
GL_FRAGMENT_SHADER,
base::StringPrintf("%s\n"
"#define SamplerType sampler2D\n"
"#define TextureLookup texture2D\n"
"#define TextureScale vec2(1.0, 1.0)\n"
"%s",
is_gles ? kShaderFloatPrecision : "",
kFragmentShader)
.c_str());
case GL_TEXTURE_RECTANGLE_ARB:
return gfx::GLHelper::LoadShader(
GL_FRAGMENT_SHADER,
base::StringPrintf("%s\n"
"#extension GL_ARB_texture_rectangle : require\n"
"#define SamplerType sampler2DRect\n"
"#define TextureLookup texture2DRect\n"
"#define TextureScale vec2(%f, %f)\n"
"%s",
is_gles ? kShaderFloatPrecision : "",
static_cast<double>(size.width()),
static_cast<double>(size.height()),
kFragmentShader)
.c_str());
default:
NOTREACHED();
return 0;
}
}
// Draws texture bound to |target| of texture unit 0 to the currently bound
// frame buffer.
void DrawTextureQuad(GLenum target, const gfx::Size& size) {
// clang-format off
const char kVertexShader[] = STRINGIZE(
attribute vec2 a_position;
varying vec2 v_texCoord;
void main() {
gl_Position = vec4(a_position.x, a_position.y, 0.0, 1.0);
v_texCoord = (a_position + vec2(1.0, 1.0)) * 0.5;
}
);
// clang-format on
GLuint vertex_shader =
gfx::GLHelper::LoadShader(GL_VERTEX_SHADER, kVertexShader);
GLuint fragment_shader = LoadFragmentShader(target, size);
GLuint program = gfx::GLHelper::SetupProgram(vertex_shader, fragment_shader);
EXPECT_NE(program, 0u);
glUseProgram(program);
GLint sampler_location = glGetUniformLocation(program, "a_texture");
ASSERT_NE(sampler_location, -1);
glUniform1i(sampler_location, 0);
GLuint vertex_buffer = gfx::GLHelper::SetupQuadVertexBuffer();
gfx::GLHelper::DrawQuad(vertex_buffer);
glDeleteShader(vertex_shader);
glDeleteShader(fragment_shader);
glDeleteProgram(program);
glDeleteBuffersARB(1, &vertex_buffer);
}
} // namespace
template <typename GLImageTestDelegate>
class GLImageTest : public testing::Test {
protected:
// Overridden from testing::Test:
void SetUp() override {
GLImageTestSupport::InitializeGL();
surface_ = gl::init::CreateOffscreenGLSurface(gfx::Size());
context_ = gl::init::CreateGLContext(nullptr, surface_.get(),
gfx::PreferIntegratedGpu);
context_->MakeCurrent(surface_.get());
}
void TearDown() override {
context_->ReleaseCurrent(surface_.get());
context_ = nullptr;
surface_ = nullptr;
GLImageTestSupport::CleanupGL();
}
protected:
scoped_refptr<gfx::GLSurface> surface_;
scoped_refptr<gfx::GLContext> context_;
GLImageTestDelegate delegate_;
};
TYPED_TEST_CASE_P(GLImageTest);
TYPED_TEST_P(GLImageTest, CreateAndDestroy) {
const gfx::Size small_image_size(4, 4);
const gfx::Size large_image_size(512, 512);
const uint8_t image_color[] = {0, 0xff, 0, 0xff};
// Create a small solid color green image of preferred format. This must
// succeed in order for a GLImage to be conformant.
scoped_refptr<gl::GLImage> small_image =
this->delegate_.CreateSolidColorImage(small_image_size, image_color);
ASSERT_TRUE(small_image);
// Create a large solid color green image of preferred format. This must
// succeed in order for a GLImage to be conformant.
scoped_refptr<gl::GLImage> large_image =
this->delegate_.CreateSolidColorImage(large_image_size, image_color);
ASSERT_TRUE(large_image);
// Verify that image size is correct.
EXPECT_EQ(small_image->GetSize().ToString(), small_image_size.ToString());
EXPECT_EQ(large_image->GetSize().ToString(), large_image_size.ToString());
// Verify that destruction of images work correctly both when we have a
// context and when we don't.
small_image->Destroy(true /* have_context */);
large_image->Destroy(false /* have_context */);
}
// The GLImageTest test case verifies the behaviour that is expected from a
// GLImage in order to be conformant.
REGISTER_TYPED_TEST_CASE_P(GLImageTest, CreateAndDestroy);
template <typename GLImageTestDelegate>
class GLImageZeroInitializeTest : public GLImageTest<GLImageTestDelegate> {};
// This test verifies that if an uninitialized image is bound to a texture, the
// result is zero-initialized.
TYPED_TEST_CASE_P(GLImageZeroInitializeTest);
TYPED_TEST_P(GLImageZeroInitializeTest, ZeroInitialize) {
#if defined(OS_MACOSX)
// This functionality is disabled on Mavericks because it breaks PDF
// rendering. https://crbug.com/594343.
if (base::mac::IsOSMavericks())
return;
#endif
const gfx::Size image_size(256, 256);
GLuint framebuffer =
GLTestHelper::SetupFramebuffer(image_size.width(), image_size.height());
ASSERT_TRUE(framebuffer);
glBindFramebufferEXT(GL_FRAMEBUFFER, framebuffer);
glViewport(0, 0, image_size.width(), image_size.height());
// Create an uninitialized image of preferred format.
scoped_refptr<gl::GLImage> image = this->delegate_.CreateImage(image_size);
// Create a texture that |image| will be bound to.
GLenum target = this->delegate_.GetTextureTarget();
GLuint texture = GLTestHelper::CreateTexture(target);
glBindTexture(target, texture);
// Bind |image| to |texture|.
bool rv = image->BindTexImage(target);
EXPECT_TRUE(rv);
// Draw |texture| to viewport.
DrawTextureQuad(target, image_size);
// Release |image| from |texture|.
image->ReleaseTexImage(target);
// Read back pixels to check expectations.
const uint8_t zero_color[] = {0, 0, 0, 0};
GLTestHelper::CheckPixels(0, 0, image_size.width(), image_size.height(),
zero_color);
// Clean up.
glDeleteTextures(1, &texture);
glDeleteFramebuffersEXT(1, &framebuffer);
image->Destroy(true /* have_context */);
}
REGISTER_TYPED_TEST_CASE_P(GLImageZeroInitializeTest, ZeroInitialize);
template <typename GLImageTestDelegate>
class GLImageBindTest : public GLImageTest<GLImageTestDelegate> {};
TYPED_TEST_CASE_P(GLImageBindTest);
TYPED_TEST_P(GLImageBindTest, BindTexImage) {
const gfx::Size image_size(256, 256);
const uint8_t image_color[] = {0x10, 0x20, 0, 0xff};
GLuint framebuffer =
GLTestHelper::SetupFramebuffer(image_size.width(), image_size.height());
ASSERT_TRUE(framebuffer);
glBindFramebufferEXT(GL_FRAMEBUFFER, framebuffer);
glViewport(0, 0, image_size.width(), image_size.height());
// Create a solid color green image of preferred format. This must succeed
// in order for a GLImage to be conformant.
scoped_refptr<gl::GLImage> image =
this->delegate_.CreateSolidColorImage(image_size, image_color);
ASSERT_TRUE(image);
// Initialize a blue texture of the same size as |image|.
unsigned target = this->delegate_.GetTextureTarget();
GLuint texture = GLTestHelper::CreateTexture(target);
glBindTexture(target, texture);
// Bind |image| to |texture|.
bool rv = image->BindTexImage(target);
EXPECT_TRUE(rv);
glClearColor(0.0f, 0.0f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
// Draw |texture| to viewport.
DrawTextureQuad(target, image_size);
// Read back pixels to check expectations.
GLTestHelper::CheckPixels(0, 0, image_size.width(), image_size.height(),
image_color);
// Clean up.
glDeleteTextures(1, &texture);
glDeleteFramebuffersEXT(1, &framebuffer);
image->Destroy(true /* have_context */);
}
REGISTER_TYPED_TEST_CASE_P(GLImageBindTest, BindTexImage);
template <typename GLImageTestDelegate>
class GLImageCopyTest : public GLImageTest<GLImageTestDelegate> {};
TYPED_TEST_CASE_P(GLImageCopyTest);
TYPED_TEST_P(GLImageCopyTest, CopyTexImage) {
const gfx::Size image_size(256, 256);
// These values are picked so that RGB -> YUV on the CPU converted
// back to RGB on the GPU produces the original RGB values without
// any error.
const uint8_t image_color[] = {0x10, 0x20, 0, 0xff};
const uint8_t texture_color[] = {0, 0, 0xff, 0xff};
GLuint framebuffer =
GLTestHelper::SetupFramebuffer(image_size.width(), image_size.height());
ASSERT_TRUE(framebuffer);
glBindFramebufferEXT(GL_FRAMEBUFFER, framebuffer);
glViewport(0, 0, image_size.width(), image_size.height());
// Create a solid color green image of preferred format. This must succeed
// in order for a GLImage to be conformant.
scoped_refptr<gl::GLImage> image =
this->delegate_.CreateSolidColorImage(image_size, image_color);
ASSERT_TRUE(image);
// Create a solid color blue texture of the same size as |image|.
unsigned target = this->delegate_.GetTextureTarget();
GLuint texture = GLTestHelper::CreateTexture(target);
std::unique_ptr<uint8_t[]> pixels(new uint8_t[BufferSizeForBufferFormat(
image_size, gfx::BufferFormat::RGBA_8888)]);
GLImageTestSupport::SetBufferDataToColor(
image_size.width(), image_size.height(),
static_cast<int>(RowSizeForBufferFormat(image_size.width(),
gfx::BufferFormat::RGBA_8888, 0)),
0, gfx::BufferFormat::RGBA_8888, texture_color, pixels.get());
glBindTexture(target, texture);
glTexImage2D(target, 0, GL_RGBA, image_size.width(), image_size.height(), 0,
GL_RGBA, GL_UNSIGNED_BYTE, pixels.get());
// Copy |image| to |texture|.
bool rv = image->CopyTexImage(target);
EXPECT_TRUE(rv);
// Draw |texture| to viewport.
DrawTextureQuad(target, image_size);
// Read back pixels to check expectations.
GLTestHelper::CheckPixels(0, 0, image_size.width(), image_size.height(),
image_color);
// Clean up.
glDeleteTextures(1, &texture);
glDeleteFramebuffersEXT(1, &framebuffer);
image->Destroy(true /* have_context */);
}
// The GLImageCopyTest test case verifies that the GLImage implementation
// handles CopyTexImage correctly.
REGISTER_TYPED_TEST_CASE_P(GLImageCopyTest, CopyTexImage);
} // namespace gl
#endif // UI_GL_TEST_GL_IMAGE_TEST_TEMPLATE_H_
| {
"content_hash": "07ecb7c23f17cd04d0f999e0f42a4397",
"timestamp": "",
"source": "github",
"line_count": 343,
"max_line_length": 80,
"avg_line_length": 35.119533527696795,
"alnum_prop": 0.6788975593558028,
"repo_name": "wuhengzhi/chromium-crosswalk",
"id": "543df8d735a7ceeed1f29b43616ca2818c8b3c86",
"size": "12046",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "ui/gl/test/gl_image_test_template.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
'use strict';
angular.module('participants').controller('HomepgController', ['$scope', '$location', 'Authentication',
function($scope, $location, Authentication) {
if(Authentication.user){
$location.path('/home');
}
}
]); | {
"content_hash": "895c6284efc6323961c566b8a619d961",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 103,
"avg_line_length": 26.1,
"alnum_prop": 0.6053639846743295,
"repo_name": "mhong777/svensicaBiggestLoser",
"id": "c3287931aec685a31f6e33f22b63a4eb87609652",
"size": "261",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/modules/participants/controllers/homepg.client.controller.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "620"
},
{
"name": "HTML",
"bytes": "39248"
},
{
"name": "JavaScript",
"bytes": "175282"
},
{
"name": "Perl",
"bytes": "48"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_02) on Tue Oct 20 05:53:13 CEST 2015 -->
<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title>DependentSourceSet (Gradle API 2.8)</title>
<meta name="date" content="2015-10-20">
<link rel="stylesheet" type="text/css" href="../../../../javadoc.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="DependentSourceSet (Gradle API 2.8)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev Class</li>
<li><a href="../../../../org/gradle/language/nativeplatform/HeaderExportingSourceSet.html" title="interface in org.gradle.language.nativeplatform"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/gradle/language/nativeplatform/DependentSourceSet.html" target="_top">Frames</a></li>
<li><a href="DependentSourceSet.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.gradle.language.nativeplatform</div>
<h2 title="Interface DependentSourceSet" class="title">Interface DependentSourceSet</h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Superinterfaces:</dt>
<dd><a href="../../../../org/gradle/api/Buildable.html" title="interface in org.gradle.api">Buildable</a>, <a href="../../../../org/gradle/api/BuildableModelElement.html" title="interface in org.gradle.api">BuildableModelElement</a>, <a href="../../../../org/gradle/language/base/LanguageSourceSet.html" title="interface in org.gradle.language.base">LanguageSourceSet</a>, <a href="../../../../org/gradle/api/Named.html" title="interface in org.gradle.api">Named</a></dd>
</dl>
<dl>
<dt>All Known Subinterfaces:</dt>
<dd><a href="../../../../org/gradle/language/cpp/CppSourceSet.html" title="interface in org.gradle.language.cpp">CppSourceSet</a>, <a href="../../../../org/gradle/language/c/CSourceSet.html" title="interface in org.gradle.language.c">CSourceSet</a>, <a href="../../../../org/gradle/language/objectivecpp/ObjectiveCppSourceSet.html" title="interface in org.gradle.language.objectivecpp">ObjectiveCppSourceSet</a>, <a href="../../../../org/gradle/language/objectivec/ObjectiveCSourceSet.html" title="interface in org.gradle.language.objectivec">ObjectiveCSourceSet</a></dd>
</dl>
<hr>
<br>
<pre><a href="../../../../org/gradle/api/Incubating.html" title="annotation in org.gradle.api">@Incubating</a>
public interface <span class="strong">DependentSourceSet</span>
extends <a href="../../../../org/gradle/language/base/LanguageSourceSet.html" title="interface in org.gradle.language.base">LanguageSourceSet</a></pre>
<div class="block">A source set that depends on one or more <a href="../../../../org/gradle/nativeplatform/NativeDependencySet.html" title="interface in org.gradle.nativeplatform"><code>NativeDependencySet</code></a>s to be built.</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== NESTED CLASS SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="nested_class_summary">
<!-- -->
</a>
<h3>Nested Class Summary</h3>
<ul class="blockList">
<li class="blockList"><a name="nested_classes_inherited_from_class_org.gradle.api.Named">
<!-- -->
</a>
<h3>Nested classes/interfaces inherited from interface org.gradle.api.<a href="../../../../org/gradle/api/Named.html" title="interface in org.gradle.api">Named</a></h3>
<code><a href="../../../../org/gradle/api/Named.Namer.html" title="class in org.gradle.api">Named.Namer</a></code></li>
</ul>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="https://docs.oracle.com/javase/6/docs/api/java/util/Collection.html?is-external=true" title="class or interface in java.util">Collection</a><?></code></td>
<td class="colLast"><code><strong><a href="../../../../org/gradle/language/nativeplatform/DependentSourceSet.html#getLibs()">getLibs</a></strong>()</code>
<div class="block">The libraries that this source set requires.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="https://docs.oracle.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td>
<td class="colLast"><code><strong><a href="../../../../org/gradle/language/nativeplatform/DependentSourceSet.html#getPreCompiledHeader()">getPreCompiledHeader</a></strong>()</code>
<div class="block">Returns the pre-compiled header configured for this source set.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../org/gradle/language/nativeplatform/DependentSourceSet.html#lib(java.lang.Object)">lib</a></strong>(<a href="https://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a> library)</code>
<div class="block">Adds a library that this source set requires.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../org/gradle/language/nativeplatform/DependentSourceSet.html#setPreCompiledHeader(java.lang.String)">setPreCompiledHeader</a></strong>(<a href="https://docs.oracle.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> header)</code>
<div class="block">Sets the pre-compiled header to be used when compiling sources in this source set.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_org.gradle.language.base.LanguageSourceSet">
<!-- -->
</a>
<h3>Methods inherited from interface org.gradle.language.base.<a href="../../../../org/gradle/language/base/LanguageSourceSet.html" title="interface in org.gradle.language.base">LanguageSourceSet</a></h3>
<code><a href="../../../../org/gradle/language/base/LanguageSourceSet.html#generatedBy(org.gradle.api.Task)">generatedBy</a>, <a href="../../../../org/gradle/language/base/LanguageSourceSet.html#getDisplayName()">getDisplayName</a>, <a href="../../../../org/gradle/language/base/LanguageSourceSet.html#getSource()">getSource</a>, <a href="../../../../org/gradle/language/base/LanguageSourceSet.html#source(org.gradle.api.Action)">source</a></code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_org.gradle.api.Named">
<!-- -->
</a>
<h3>Methods inherited from interface org.gradle.api.<a href="../../../../org/gradle/api/Named.html" title="interface in org.gradle.api">Named</a></h3>
<code><a href="../../../../org/gradle/api/Named.html#getName()">getName</a></code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_org.gradle.api.BuildableModelElement">
<!-- -->
</a>
<h3>Methods inherited from interface org.gradle.api.<a href="../../../../org/gradle/api/BuildableModelElement.html" title="interface in org.gradle.api">BuildableModelElement</a></h3>
<code><a href="../../../../org/gradle/api/BuildableModelElement.html#builtBy(java.lang.Object...)">builtBy</a>, <a href="../../../../org/gradle/api/BuildableModelElement.html#getBuildTask()">getBuildTask</a>, <a href="../../../../org/gradle/api/BuildableModelElement.html#hasBuildDependencies()">hasBuildDependencies</a>, <a href="../../../../org/gradle/api/BuildableModelElement.html#setBuildTask(org.gradle.api.Task)">setBuildTask</a></code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_org.gradle.api.Buildable">
<!-- -->
</a>
<h3>Methods inherited from interface org.gradle.api.<a href="../../../../org/gradle/api/Buildable.html" title="interface in org.gradle.api">Buildable</a></h3>
<code><a href="../../../../org/gradle/api/Buildable.html#getBuildDependencies()">getBuildDependencies</a></code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="getLibs()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getLibs</h4>
<pre><a href="https://docs.oracle.com/javase/6/docs/api/java/util/Collection.html?is-external=true" title="class or interface in java.util">Collection</a><?> getLibs()</pre>
<div class="block">The libraries that this source set requires.</div>
</li>
</ul>
<a name="lib(java.lang.Object)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>lib</h4>
<pre>void lib(<a href="https://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a> library)</pre>
<div class="block">Adds a library that this source set requires. This method accepts the following types:
<ul>
<li>A <a href="../../../../org/gradle/nativeplatform/NativeLibrarySpec.html" title="interface in org.gradle.nativeplatform"><code>NativeLibrarySpec</code></a></li>
<li>A <a href="../../../../org/gradle/nativeplatform/NativeDependencySet.html" title="interface in org.gradle.nativeplatform"><code>NativeDependencySet</code></a></li>
<li>A <a href="../../../../org/gradle/language/base/LanguageSourceSet.html" title="interface in org.gradle.language.base"><code>LanguageSourceSet</code></a></li>
<li>A <a href="https://docs.oracle.com/javase/6/docs/api/java/util/Map.html?is-external=true" title="class or interface in java.util"><code>Map</code></a> containing the library selector.</li>
</ul>
The Map notation supports the following String attributes:
<ul>
<li>project: the path to the project containing the library (optional, defaults to current project)</li>
<li>library: the name of the library (required)</li>
<li>linkage: the library linkage required ['shared'/'static'] (optional, defaults to 'shared')</li>
</ul></div>
</li>
</ul>
<a name="setPreCompiledHeader(java.lang.String)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setPreCompiledHeader</h4>
<pre>void setPreCompiledHeader(<a href="https://docs.oracle.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> header)</pre>
<div class="block">Sets the pre-compiled header to be used when compiling sources in this source set.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>header</code> - the header to precompile</dd></dl>
</li>
</ul>
<a name="getPreCompiledHeader()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>getPreCompiledHeader</h4>
<pre><a href="https://docs.oracle.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> getPreCompiledHeader()</pre>
<div class="block">Returns the pre-compiled header configured for this source set.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>the pre-compiled header</dd></dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev Class</li>
<li><a href="../../../../org/gradle/language/nativeplatform/HeaderExportingSourceSet.html" title="interface in org.gradle.language.nativeplatform"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/gradle/language/nativeplatform/DependentSourceSet.html" target="_top">Frames</a></li>
<li><a href="DependentSourceSet.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| {
"content_hash": "d958ae1a76ce2b76af90c64464650e12",
"timestamp": "",
"source": "github",
"line_count": 327,
"max_line_length": 571,
"avg_line_length": 47.53211009174312,
"alnum_prop": 0.6713633146754165,
"repo_name": "FinishX/coolweather",
"id": "c7a73b0613cbfb2a34486cd778c90f90f3bcec52",
"size": "15543",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gradle/gradle-2.8/docs/javadoc/org/gradle/language/nativeplatform/DependentSourceSet.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "277"
},
{
"name": "C",
"bytes": "97569"
},
{
"name": "C++",
"bytes": "912105"
},
{
"name": "CSS",
"bytes": "105486"
},
{
"name": "CoffeeScript",
"bytes": "201"
},
{
"name": "GAP",
"bytes": "212"
},
{
"name": "Groovy",
"bytes": "1162135"
},
{
"name": "HTML",
"bytes": "35827007"
},
{
"name": "Java",
"bytes": "12908568"
},
{
"name": "JavaScript",
"bytes": "195155"
},
{
"name": "Objective-C",
"bytes": "2977"
},
{
"name": "Objective-C++",
"bytes": "442"
},
{
"name": "Scala",
"bytes": "12789"
},
{
"name": "Shell",
"bytes": "5398"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="lang:clipboard.copy" content="Copy to clipboard">
<meta name="lang:clipboard.copied" content="Copied to clipboard">
<meta name="lang:search.language" content="en">
<meta name="lang:search.pipeline.stopwords" content="True">
<meta name="lang:search.pipeline.trimmer" content="True">
<meta name="lang:search.result.none" content="No matching documents">
<meta name="lang:search.result.one" content="1 matching document">
<meta name="lang:search.result.other" content="# matching documents">
<meta name="lang:search.tokenizer" content="[\s\-]+">
<link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin>
<link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet">
<style>
body,
input {
font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif
}
code,
kbd,
pre {
font-family: "Roboto Mono", "Courier New", Courier, monospace
}
</style>
<link rel="stylesheet" href="../_static/stylesheets/application.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/>
<link rel="stylesheet" href="../_static/fonts/material-icons.css"/>
<meta name="theme-color" content="#3f51b5">
<script src="../_static/javascripts/modernizr.js"></script>
<title>statsmodels.tsa.statespace.kalman_filter.KalmanFilter.memory_no_filtered_mean — statsmodels</title>
<link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png">
<link rel="manifest" href="../_static/icons/site.webmanifest">
<link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191">
<meta name="msapplication-TileColor" content="#2b5797">
<meta name="msapplication-config" content="../_static/icons/browserconfig.xml">
<link rel="stylesheet" href="../_static/stylesheets/examples.css">
<link rel="stylesheet" href="../_static/stylesheets/deprecation.css">
<link rel="stylesheet" type="text/css" href="../_static/pygments.css" />
<link rel="stylesheet" type="text/css" href="../_static/material.css" />
<link rel="stylesheet" type="text/css" href="../_static/graphviz.css" />
<link rel="stylesheet" type="text/css" href="../_static/plot_directive.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>
<script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script>
<link rel="shortcut icon" href="../_static/favicon.ico"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="next" title="statsmodels.tsa.statespace.kalman_filter.KalmanFilter.memory_no_forecast" href="statsmodels.tsa.statespace.kalman_filter.KalmanFilter.memory_no_forecast.html" />
<link rel="prev" title="statsmodels.tsa.statespace.kalman_filter.KalmanFilter.memory_no_filtered_cov" href="statsmodels.tsa.statespace.kalman_filter.KalmanFilter.memory_no_filtered_cov.html" />
</head>
<body dir=ltr
data-md-color-primary=indigo data-md-color-accent=blue>
<svg class="md-svg">
<defs data-children-count="0">
<svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg>
</defs>
</svg>
<input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer">
<input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search">
<label class="md-overlay" data-md-component="overlay" for="__drawer"></label>
<a href="#generated/statsmodels.tsa.statespace.kalman_filter.KalmanFilter.memory_no_filtered_mean" tabindex="1" class="md-skip"> Skip to content </a>
<header class="md-header" data-md-component="header">
<nav class="md-header-nav md-grid">
<div class="md-flex navheader">
<div class="md-flex__cell md-flex__cell--shrink">
<a href="../index.html" title="statsmodels"
class="md-header-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" height="26"
alt="statsmodels logo">
</a>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label>
</div>
<div class="md-flex__cell md-flex__cell--stretch">
<div class="md-flex__ellipsis md-header-nav__title" data-md-component="title">
<span class="md-header-nav__topic">statsmodels v0.13.0</span>
<span class="md-header-nav__topic"> statsmodels.tsa.statespace.kalman_filter.KalmanFilter.memory_no_filtered_mean </span>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--search md-header-nav__button" for="__search"></label>
<div class="md-search" data-md-component="search" role="dialog">
<label class="md-search__overlay" for="__search"></label>
<div class="md-search__inner" role="search">
<form class="md-search__form" action="../search.html" method="get" name="search">
<input type="text" class="md-search__input" name="q" placeholder="Search"
autocapitalize="off" autocomplete="off" spellcheck="false"
data-md-component="query" data-md-state="active">
<label class="md-icon md-search__icon" for="__search"></label>
<button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1">

</button>
</form>
<div class="md-search__output">
<div class="md-search__scrollwrap" data-md-scrollfix>
<div class="md-search-result" data-md-component="result">
<div class="md-search-result__meta">
Type to start searching
</div>
<ol class="md-search-result__list"></ol>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<div class="md-header-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
</div>
<script src="../_static/javascripts/version_dropdown.js"></script>
<script>
var json_loc = "../../versions-v2.json",
target_loc = "../../",
text = "Versions";
$( document ).ready( add_version_dropdown(json_loc, target_loc, text));
</script>
</div>
</nav>
</header>
<div class="md-container">
<nav class="md-tabs" data-md-component="tabs">
<div class="md-tabs__inner md-grid">
<ul class="md-tabs__list">
<li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li>
<li class="md-tabs__item"><a href="../statespace.html" class="md-tabs__link">Time Series Analysis by State Space Methods <code class="xref py py-mod docutils literal notranslate"><span class="pre">statespace</span></code></a></li>
<li class="md-tabs__item"><a href="statsmodels.tsa.statespace.kalman_filter.KalmanFilter.html" class="md-tabs__link">statsmodels.tsa.statespace.kalman_filter.KalmanFilter</a></li>
</ul>
</div>
</nav>
<main class="md-main">
<div class="md-main__inner md-grid" data-md-component="container">
<div class="md-sidebar md-sidebar--primary" data-md-component="navigation">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--primary" data-md-level="0">
<label class="md-nav__title md-nav__title--site" for="__drawer">
<a href="../index.html" title="statsmodels" class="md-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48">
</a>
<a href="../index.html"
title="statsmodels">statsmodels v0.13.0</a>
</label>
<div class="md-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../install.html" class="md-nav__link">Installing statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../gettingstarted.html" class="md-nav__link">Getting started</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html" class="md-nav__link">User Guide</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../user-guide.html#background" class="md-nav__link">Background</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../tsa.html" class="md-nav__link">Time Series analysis <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa</span></code></a>
</li>
<li class="md-nav__item">
<a href="../statespace.html" class="md-nav__link">Time Series Analysis by State Space Methods <code class="xref py py-mod docutils literal notranslate"><span class="pre">statespace</span></code></a>
</li>
<li class="md-nav__item">
<a href="../vector_ar.html" class="md-nav__link">Vector Autoregressions <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa.vector_ar</span></code></a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../examples/index.html" class="md-nav__link">Examples</a>
</li>
<li class="md-nav__item">
<a href="../api.html" class="md-nav__link">API Reference</a>
</li>
<li class="md-nav__item">
<a href="../about.html" class="md-nav__link">About statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../dev/index.html" class="md-nav__link">Developer Page</a>
</li>
<li class="md-nav__item">
<a href="../release/index.html" class="md-nav__link">Release Notes</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-sidebar md-sidebar--secondary" data-md-component="toc">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--secondary">
<ul class="md-nav__list" data-md-scrollfix="">
<li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.tsa.statespace.kalman_filter.KalmanFilter.memory_no_filtered_mean.rst.txt">Show Source</a> </li>
<li id="searchbox" class="md-nav__item"></li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-content">
<article class="md-content__inner md-typeset" role="main">
<h1 id="generated-statsmodels-tsa-statespace-kalman-filter-kalmanfilter-memory-no-filtered-mean--page-root">statsmodels.tsa.statespace.kalman_filter.KalmanFilter.memory_no_filtered_mean<a class="headerlink" href="#generated-statsmodels-tsa-statespace-kalman-filter-kalmanfilter-memory-no-filtered-mean--page-root" title="Permalink to this headline">¶</a></h1>
<dl class="py attribute">
<dt class="sig sig-object py" id="statsmodels.tsa.statespace.kalman_filter.KalmanFilter.memory_no_filtered_mean">
<span class="sig-prename descclassname"><span class="pre">KalmanFilter.</span></span><span class="sig-name descname"><span class="pre">memory_no_filtered_mean</span></span><em class="property"> <span class="pre">=</span> <span class="pre">False</span></em><a class="headerlink" href="#statsmodels.tsa.statespace.kalman_filter.KalmanFilter.memory_no_filtered_mean" title="Permalink to this definition">¶</a></dt>
<dd><p>(bool) Flag to prevent storing filtered states.</p>
</dd></dl>
</article>
</div>
</div>
</main>
</div>
<footer class="md-footer">
<div class="md-footer-nav">
<nav class="md-footer-nav__inner md-grid">
<a href="statsmodels.tsa.statespace.kalman_filter.KalmanFilter.memory_no_filtered_cov.html" title="statsmodels.tsa.statespace.kalman_filter.KalmanFilter.memory_no_filtered_cov"
class="md-flex md-footer-nav__link md-footer-nav__link--prev"
rel="prev">
<div class="md-flex__cell md-flex__cell--shrink">
<i class="md-icon md-icon--arrow-back md-footer-nav__button"></i>
</div>
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title">
<span class="md-flex__ellipsis">
<span
class="md-footer-nav__direction"> Previous </span> statsmodels.tsa.statespace.kalman_filter.KalmanFilter.memory_no_filtered_cov </span>
</div>
</a>
<a href="statsmodels.tsa.statespace.kalman_filter.KalmanFilter.memory_no_forecast.html" title="statsmodels.tsa.statespace.kalman_filter.KalmanFilter.memory_no_forecast"
class="md-flex md-footer-nav__link md-footer-nav__link--next"
rel="next">
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span
class="md-flex__ellipsis"> <span
class="md-footer-nav__direction"> Next </span> statsmodels.tsa.statespace.kalman_filter.KalmanFilter.memory_no_forecast </span>
</div>
<div class="md-flex__cell md-flex__cell--shrink"><i
class="md-icon md-icon--arrow-forward md-footer-nav__button"></i>
</div>
</a>
</nav>
</div>
<div class="md-footer-meta md-typeset">
<div class="md-footer-meta__inner md-grid">
<div class="md-footer-copyright">
<div class="md-footer-copyright__highlight">
© Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
</div>
Last updated on
Oct 06, 2021.
<br/>
Created using
<a href="http://www.sphinx-doc.org/">Sphinx</a> 4.0.3.
and
<a href="https://github.com/bashtage/sphinx-material/">Material for
Sphinx</a>
</div>
</div>
</div>
</footer>
<script src="../_static/javascripts/application.js"></script>
<script>app.initialize({version: "1.0.4", url: {base: ".."}})</script>
</body>
</html> | {
"content_hash": "72469a5ad2dc8fe9d269449712f3bd11",
"timestamp": "",
"source": "github",
"line_count": 447,
"max_line_length": 999,
"avg_line_length": 40.42058165548099,
"alnum_prop": 0.6080363072835953,
"repo_name": "statsmodels/statsmodels.github.io",
"id": "b3aca3bce0ca264d4f627aecda2732ea68009e86",
"size": "18072",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "v0.13.0/generated/statsmodels.tsa.statespace.kalman_filter.KalmanFilter.memory_no_filtered_mean.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
using namespace std;
class Triangle : public Object
{
public:
Triangle();
~Triangle();
// object maths
pair<bool, double> intersectionCheck(Ray& ray);
Vector3 surfaceNormal(Vector3& intersection);
private:
Vector3 v0, v1, v2;
};
#endif | {
"content_hash": "3f9fc573bbbb8ed735f8eadfaeef8a59",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 61,
"avg_line_length": 16.470588235294116,
"alnum_prop": 0.6285714285714286,
"repo_name": "wridgers/john",
"id": "3fbedd236dc7788222d00e87ac6fa071bc13e5f3",
"size": "407",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "inc/objects/triangle.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1356"
},
{
"name": "C++",
"bytes": "43339"
},
{
"name": "Lua",
"bytes": "1033"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_43) on Tue Aug 06 14:46:45 EDT 2013 -->
<TITLE>
HtmlUtils (caCORE SDK 4.5 API Documentation)
</TITLE>
<META NAME="date" CONTENT="2013-08-06">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="HtmlUtils (caCORE SDK 4.5 API Documentation)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/HtmlUtils.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV CLASS
<A HREF="../../../../../../gov/nih/nci/system/web/util/HTTPUtils.html" title="class in gov.nih.nci.system.web.util"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?gov/nih/nci/system/web/util/HtmlUtils.html" target="_top"><B>FRAMES</B></A>
<A HREF="HtmlUtils.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | <A HREF="#field_summary">FIELD</A> | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: <A HREF="#field_detail">FIELD</A> | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<!-- ======== START OF CLASS DATA ======== -->
<H2>
<FONT SIZE="-1">
gov.nih.nci.system.web.util</FONT>
<BR>
Class HtmlUtils</H2>
<PRE>
java.lang.Object
<IMG SRC="../../../../../../resources/inherit.gif" ALT="extended by "><B>gov.nih.nci.system.web.util.HtmlUtils</B>
</PRE>
<HR>
<DL>
<DT><PRE>public class <B>HtmlUtils</B><DT>extends java.lang.Object</DL>
</PRE>
<P>
<HR>
<P>
<!-- =========== FIELD SUMMARY =========== -->
<A NAME="field_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Field Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.util.Map<java.lang.String,java.lang.String></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#addressPartTypeOptionMap">addressPartTypeOptionMap</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.util.List<java.lang.String></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#addressPartTypeOptions">addressPartTypeOptions</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#addressPartTypeSelect">addressPartTypeSelect</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.util.List<java.lang.String></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#addressPartTypeValues">addressPartTypeValues</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.util.List<java.lang.String></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#booleanOptions">booleanOptions</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#booleanSelect">booleanSelect</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.util.List<java.lang.String></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#booleanValues">booleanValues</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.util.List<java.lang.String></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#compressionOptions">compressionOptions</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#compressionSelect">compressionSelect</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.util.List<java.lang.String></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#compressionValues">compressionValues</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.util.List<java.lang.String></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#entityNamePartQualifierOptions">entityNamePartQualifierOptions</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#entityNamePartQualifierSelect">entityNamePartQualifierSelect</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.util.List<java.lang.String></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#entityNamePartQualifierValues">entityNamePartQualifierValues</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.util.Map<java.lang.String,java.lang.String></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#entityNamePartTypeOptionMap">entityNamePartTypeOptionMap</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.util.List<java.lang.String></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#entityNamePartTypeOptions">entityNamePartTypeOptions</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#entityNamePartTypeSelect">entityNamePartTypeSelect</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.util.List<java.lang.String></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#entityNamePartTypeValues">entityNamePartTypeValues</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#HTML_SCREEN_BEGIN">HTML_SCREEN_BEGIN</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#HTML_SCREEN_END">HTML_SCREEN_END</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.util.List<java.lang.String></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#identifierReliabilityOptions">identifierReliabilityOptions</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#identifierReliabilitySelect">identifierReliabilitySelect</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.util.List<java.lang.String></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#identifierReliabilityValues">identifierReliabilityValues</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.util.List<java.lang.String></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#identifierScopeOptions">identifierScopeOptions</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#identifierScopeSelect">identifierScopeSelect</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.util.List<java.lang.String></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#identifierScopeValues">identifierScopeValues</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static org.apache.log4j.Logger</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#log">log</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.util.List<java.lang.String></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#nullFlavorOptions">nullFlavorOptions</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#nullFlavorSelect">nullFlavorSelect</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.util.List<java.lang.String></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#nullFlavorValues">nullFlavorValues</A></B></CODE>
<BR>
</TD>
</TR>
</TABLE>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<A NAME="constructor_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Constructor Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#HtmlUtils()">HtmlUtils</A></B>()</CODE>
<BR>
</TD>
</TR>
</TABLE>
<!-- ========== METHOD SUMMARY =========== -->
<A NAME="method_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getAttributeValue(org.jdom.Element, java.lang.String)">getAttributeValue</A></B>(org.jdom.Element root,
java.lang.String attName)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.util.List<java.lang.Object></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getComplexSearchFields(java.lang.String, java.util.List)">getComplexSearchFields</A></B>(java.lang.String complexType,
java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getHTML_AD(java.util.List)">getHTML_AD</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getHTML_ADXP(java.util.List)">getHTML_ADXP</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getHTML_ANY(java.util.List)">getHTML_ANY</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getHTML_BL(java.util.List)">getHTML_BL</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getHTML_Boolean(java.lang.String)">getHTML_Boolean</A></B>(java.lang.String attrName)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getHTML_Boolean(java.lang.String, java.lang.String)">getHTML_Boolean</A></B>(java.lang.String attrName,
java.lang.String value)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getHTML_CD(java.util.List)">getHTML_CD</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getHTML_DSET(java.lang.String, java.util.List)">getHTML_DSET</A></B>(java.lang.String genericType,
java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getHTML_ED_TEXT(java.util.List)">getHTML_ED_TEXT</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getHTML_ED(java.util.List)">getHTML_ED</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getHTML_EN(java.util.List)">getHTML_EN</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getHTML_ENON(java.util.List)">getHTML_ENON</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getHTML_ENPN(java.util.List)">getHTML_ENPN</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getHTML_ENXP(java.util.List)">getHTML_ENXP</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getHTML_II(java.util.List, java.lang.String)">getHTML_II</A></B>(java.util.List<java.lang.Object> searchableFields,
java.lang.String attrName)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getHTML_INT(java.util.List)">getHTML_INT</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getHTML_IVL(java.lang.String, java.util.List)">getHTML_IVL</A></B>(java.lang.String genericType,
java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getHTML_PQ(java.util.List)">getHTML_PQ</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getHTML_PQV(java.util.List)">getHTML_PQV</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getHTML_QTY(java.util.List)">getHTML_QTY</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getHTML_REAL(java.util.List)">getHTML_REAL</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getHTML_SC(java.util.List)">getHTML_SC</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getHTML_ST_NT(java.util.List)">getHTML_ST_NT</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getHTML_ST(java.util.List)">getHTML_ST</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getHTML_TEL_EMAIL(java.util.List)">getHTML_TEL_EMAIL</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getHTML_TEL_PERSON(java.util.List)">getHTML_TEL_PERSON</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getHTML_TEL_PHONE(java.util.List)">getHTML_TEL_PHONE</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getHTML_TEL_URL(java.util.List)">getHTML_TEL_URL</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getHTML_TEL(java.util.List)">getHTML_TEL</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getHTML_TS(java.util.List)">getHTML_TS</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getHTML(java.lang.String, java.lang.String)">getHTML</A></B>(java.lang.String attrName,
java.lang.String validationClass)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getHTML(java.lang.String, java.lang.String, java.lang.String)">getHTML</A></B>(java.lang.String attrName,
java.lang.String validationClass,
java.lang.String value)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getHtmlFor(java.lang.String, java.lang.String)">getHtmlFor</A></B>(java.lang.String attrName,
java.lang.String attrType)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getHtmlFor(java.lang.String, java.lang.String, java.util.List)">getHtmlFor</A></B>(java.lang.String attrName,
java.lang.String attrType,
java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getHtmlFor(java.lang.String, java.lang.String, java.lang.String)">getHtmlFor</A></B>(java.lang.String attrName,
java.lang.String attrType,
java.lang.String value)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getScreen_AD(java.util.List)">getScreen_AD</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getScreen_ADXP(java.util.List)">getScreen_ADXP</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getScreen_BL_NONNULL(java.util.List)">getScreen_BL_NONNULL</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getScreen_BL(java.util.List)">getScreen_BL</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getScreen_CD(java.util.List)">getScreen_CD</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getScreen_DSET(java.lang.String, java.util.List)">getScreen_DSET</A></B>(java.lang.String genericType,
java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getScreen_ED_TEXT(java.util.List)">getScreen_ED_TEXT</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getScreen_ED(java.util.List)">getScreen_ED</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getScreen_EN(java.util.List)">getScreen_EN</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getScreen_ENON(java.util.List)">getScreen_ENON</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getScreen_ENPN(java.util.List)">getScreen_ENPN</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getScreen_ENXP(java.util.List)">getScreen_ENXP</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getScreen_II(java.util.List, java.lang.String)">getScreen_II</A></B>(java.util.List<java.lang.Object> searchableFields,
java.lang.String attrName)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getScreen_INT(java.util.List)">getScreen_INT</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getScreen_IVL(java.lang.String, java.util.List)">getScreen_IVL</A></B>(java.lang.String genericType,
java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getScreen_PQ(java.util.List)">getScreen_PQ</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getScreen_QTY(java.util.List)">getScreen_QTY</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getScreen_REAL(java.util.List)">getScreen_REAL</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getScreen_SC(java.util.List)">getScreen_SC</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getScreen_ST_NT(java.util.List)">getScreen_ST_NT</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getScreen_ST(java.util.List)">getScreen_ST</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getScreen_TEL_EMAIL(java.util.List)">getScreen_TEL_EMAIL</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getScreen_TEL_PERSON(java.util.List)">getScreen_TEL_PERSON</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getScreen_TEL_PHONE(java.util.List)">getScreen_TEL_PHONE</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getScreen_TEL_URL(java.util.List)">getScreen_TEL_URL</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getScreen_TEL(java.util.List)">getScreen_TEL</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getScreen_TS(java.util.List)">getScreen_TS</A></B>(java.util.List<java.lang.Object> searchableFields)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getSelect_AddressPartType()">getSelect_AddressPartType</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getSelect_AddressPartType(java.util.List)">getSelect_AddressPartType</A></B>(java.util.List<java.lang.Object> validAddressPartTypes)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getSelect_Boolean(java.lang.String)">getSelect_Boolean</A></B>(java.lang.String attrName)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getSelect_Boolean(java.lang.String, java.lang.String)">getSelect_Boolean</A></B>(java.lang.String attrName,
java.lang.String value)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getSelect_Compression()">getSelect_Compression</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getSelect_EntityNamePartQualifier()">getSelect_EntityNamePartQualifier</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getSelect_EntityNamePartType()">getSelect_EntityNamePartType</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getSelect_EntityNamePartType(java.util.List)">getSelect_EntityNamePartType</A></B>(java.util.List<java.lang.Object> validEntityNamePartTypes)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getSelect_IdentifierReliability()">getSelect_IdentifierReliability</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getSelect_IdentifierScope()">getSelect_IdentifierScope</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../gov/nih/nci/system/web/util/HtmlUtils.html#getSelect_NullFlavor()">getSelect_NullFlavor</A></B>()</CODE>
<BR>
</TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD>
</TR>
</TABLE>
<P>
<!-- ============ FIELD DETAIL =========== -->
<A NAME="field_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Field Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="log"><!-- --></A><H3>
log</H3>
<PRE>
private static org.apache.log4j.Logger <B>log</B></PRE>
<DL>
<DL>
</DL>
</DL>
<HR>
<A NAME="HTML_SCREEN_BEGIN"><!-- --></A><H3>
HTML_SCREEN_BEGIN</H3>
<PRE>
private static java.lang.String <B>HTML_SCREEN_BEGIN</B></PRE>
<DL>
<DL>
</DL>
</DL>
<HR>
<A NAME="HTML_SCREEN_END"><!-- --></A><H3>
HTML_SCREEN_END</H3>
<PRE>
private static java.lang.String <B>HTML_SCREEN_END</B></PRE>
<DL>
<DL>
</DL>
</DL>
<HR>
<A NAME="booleanSelect"><!-- --></A><H3>
booleanSelect</H3>
<PRE>
private static java.lang.String <B>booleanSelect</B></PRE>
<DL>
<DL>
</DL>
</DL>
<HR>
<A NAME="booleanOptions"><!-- --></A><H3>
booleanOptions</H3>
<PRE>
private static java.util.List<java.lang.String> <B>booleanOptions</B></PRE>
<DL>
<DL>
</DL>
</DL>
<HR>
<A NAME="booleanValues"><!-- --></A><H3>
booleanValues</H3>
<PRE>
private static java.util.List<java.lang.String> <B>booleanValues</B></PRE>
<DL>
<DL>
</DL>
</DL>
<HR>
<A NAME="compressionSelect"><!-- --></A><H3>
compressionSelect</H3>
<PRE>
private static java.lang.String <B>compressionSelect</B></PRE>
<DL>
<DL>
</DL>
</DL>
<HR>
<A NAME="compressionOptions"><!-- --></A><H3>
compressionOptions</H3>
<PRE>
private static java.util.List<java.lang.String> <B>compressionOptions</B></PRE>
<DL>
<DL>
</DL>
</DL>
<HR>
<A NAME="compressionValues"><!-- --></A><H3>
compressionValues</H3>
<PRE>
private static java.util.List<java.lang.String> <B>compressionValues</B></PRE>
<DL>
<DL>
</DL>
</DL>
<HR>
<A NAME="identifierReliabilitySelect"><!-- --></A><H3>
identifierReliabilitySelect</H3>
<PRE>
private static java.lang.String <B>identifierReliabilitySelect</B></PRE>
<DL>
<DL>
</DL>
</DL>
<HR>
<A NAME="identifierReliabilityOptions"><!-- --></A><H3>
identifierReliabilityOptions</H3>
<PRE>
private static java.util.List<java.lang.String> <B>identifierReliabilityOptions</B></PRE>
<DL>
<DL>
</DL>
</DL>
<HR>
<A NAME="identifierReliabilityValues"><!-- --></A><H3>
identifierReliabilityValues</H3>
<PRE>
private static java.util.List<java.lang.String> <B>identifierReliabilityValues</B></PRE>
<DL>
<DL>
</DL>
</DL>
<HR>
<A NAME="identifierScopeSelect"><!-- --></A><H3>
identifierScopeSelect</H3>
<PRE>
private static java.lang.String <B>identifierScopeSelect</B></PRE>
<DL>
<DL>
</DL>
</DL>
<HR>
<A NAME="identifierScopeOptions"><!-- --></A><H3>
identifierScopeOptions</H3>
<PRE>
private static java.util.List<java.lang.String> <B>identifierScopeOptions</B></PRE>
<DL>
<DL>
</DL>
</DL>
<HR>
<A NAME="identifierScopeValues"><!-- --></A><H3>
identifierScopeValues</H3>
<PRE>
private static java.util.List<java.lang.String> <B>identifierScopeValues</B></PRE>
<DL>
<DL>
</DL>
</DL>
<HR>
<A NAME="nullFlavorSelect"><!-- --></A><H3>
nullFlavorSelect</H3>
<PRE>
private static java.lang.String <B>nullFlavorSelect</B></PRE>
<DL>
<DL>
</DL>
</DL>
<HR>
<A NAME="nullFlavorOptions"><!-- --></A><H3>
nullFlavorOptions</H3>
<PRE>
private static java.util.List<java.lang.String> <B>nullFlavorOptions</B></PRE>
<DL>
<DL>
</DL>
</DL>
<HR>
<A NAME="nullFlavorValues"><!-- --></A><H3>
nullFlavorValues</H3>
<PRE>
private static java.util.List<java.lang.String> <B>nullFlavorValues</B></PRE>
<DL>
<DL>
</DL>
</DL>
<HR>
<A NAME="addressPartTypeOptionMap"><!-- --></A><H3>
addressPartTypeOptionMap</H3>
<PRE>
private static java.util.Map<java.lang.String,java.lang.String> <B>addressPartTypeOptionMap</B></PRE>
<DL>
<DL>
</DL>
</DL>
<HR>
<A NAME="addressPartTypeSelect"><!-- --></A><H3>
addressPartTypeSelect</H3>
<PRE>
private static java.lang.String <B>addressPartTypeSelect</B></PRE>
<DL>
<DL>
</DL>
</DL>
<HR>
<A NAME="addressPartTypeOptions"><!-- --></A><H3>
addressPartTypeOptions</H3>
<PRE>
private static java.util.List<java.lang.String> <B>addressPartTypeOptions</B></PRE>
<DL>
<DL>
</DL>
</DL>
<HR>
<A NAME="addressPartTypeValues"><!-- --></A><H3>
addressPartTypeValues</H3>
<PRE>
private static java.util.List<java.lang.String> <B>addressPartTypeValues</B></PRE>
<DL>
<DL>
</DL>
</DL>
<HR>
<A NAME="entityNamePartTypeOptionMap"><!-- --></A><H3>
entityNamePartTypeOptionMap</H3>
<PRE>
private static java.util.Map<java.lang.String,java.lang.String> <B>entityNamePartTypeOptionMap</B></PRE>
<DL>
<DL>
</DL>
</DL>
<HR>
<A NAME="entityNamePartTypeSelect"><!-- --></A><H3>
entityNamePartTypeSelect</H3>
<PRE>
private static java.lang.String <B>entityNamePartTypeSelect</B></PRE>
<DL>
<DL>
</DL>
</DL>
<HR>
<A NAME="entityNamePartTypeOptions"><!-- --></A><H3>
entityNamePartTypeOptions</H3>
<PRE>
private static java.util.List<java.lang.String> <B>entityNamePartTypeOptions</B></PRE>
<DL>
<DL>
</DL>
</DL>
<HR>
<A NAME="entityNamePartTypeValues"><!-- --></A><H3>
entityNamePartTypeValues</H3>
<PRE>
private static java.util.List<java.lang.String> <B>entityNamePartTypeValues</B></PRE>
<DL>
<DL>
</DL>
</DL>
<HR>
<A NAME="entityNamePartQualifierSelect"><!-- --></A><H3>
entityNamePartQualifierSelect</H3>
<PRE>
private static java.lang.String <B>entityNamePartQualifierSelect</B></PRE>
<DL>
<DL>
</DL>
</DL>
<HR>
<A NAME="entityNamePartQualifierOptions"><!-- --></A><H3>
entityNamePartQualifierOptions</H3>
<PRE>
private static java.util.List<java.lang.String> <B>entityNamePartQualifierOptions</B></PRE>
<DL>
<DL>
</DL>
</DL>
<HR>
<A NAME="entityNamePartQualifierValues"><!-- --></A><H3>
entityNamePartQualifierValues</H3>
<PRE>
private static java.util.List<java.lang.String> <B>entityNamePartQualifierValues</B></PRE>
<DL>
<DL>
</DL>
</DL>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<A NAME="constructor_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Constructor Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="HtmlUtils()"><!-- --></A><H3>
HtmlUtils</H3>
<PRE>
public <B>HtmlUtils</B>()</PRE>
<DL>
</DL>
<!-- ============ METHOD DETAIL ========== -->
<A NAME="method_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Method Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="getSelect_AddressPartType()"><!-- --></A><H3>
getSelect_AddressPartType</H3>
<PRE>
private static java.lang.String <B>getSelect_AddressPartType</B>()</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getSelect_AddressPartType(java.util.List)"><!-- --></A><H3>
getSelect_AddressPartType</H3>
<PRE>
private static java.lang.String <B>getSelect_AddressPartType</B>(java.util.List<java.lang.Object> validAddressPartTypes)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getSelect_Boolean(java.lang.String)"><!-- --></A><H3>
getSelect_Boolean</H3>
<PRE>
private static java.lang.String <B>getSelect_Boolean</B>(java.lang.String attrName)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getSelect_Boolean(java.lang.String, java.lang.String)"><!-- --></A><H3>
getSelect_Boolean</H3>
<PRE>
private static java.lang.String <B>getSelect_Boolean</B>(java.lang.String attrName,
java.lang.String value)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getSelect_EntityNamePartType()"><!-- --></A><H3>
getSelect_EntityNamePartType</H3>
<PRE>
private static java.lang.String <B>getSelect_EntityNamePartType</B>()</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getSelect_EntityNamePartType(java.util.List)"><!-- --></A><H3>
getSelect_EntityNamePartType</H3>
<PRE>
private static java.lang.String <B>getSelect_EntityNamePartType</B>(java.util.List<java.lang.Object> validEntityNamePartTypes)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getSelect_EntityNamePartQualifier()"><!-- --></A><H3>
getSelect_EntityNamePartQualifier</H3>
<PRE>
private static java.lang.String <B>getSelect_EntityNamePartQualifier</B>()</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getSelect_Compression()"><!-- --></A><H3>
getSelect_Compression</H3>
<PRE>
private static java.lang.String <B>getSelect_Compression</B>()</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getSelect_IdentifierReliability()"><!-- --></A><H3>
getSelect_IdentifierReliability</H3>
<PRE>
private static java.lang.String <B>getSelect_IdentifierReliability</B>()</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getSelect_IdentifierScope()"><!-- --></A><H3>
getSelect_IdentifierScope</H3>
<PRE>
private static java.lang.String <B>getSelect_IdentifierScope</B>()</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getSelect_NullFlavor()"><!-- --></A><H3>
getSelect_NullFlavor</H3>
<PRE>
private static java.lang.String <B>getSelect_NullFlavor</B>()</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getHTML_AD(java.util.List)"><!-- --></A><H3>
getHTML_AD</H3>
<PRE>
private static java.lang.String <B>getHTML_AD</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getHTML_ADXP(java.util.List)"><!-- --></A><H3>
getHTML_ADXP</H3>
<PRE>
private static java.lang.String <B>getHTML_ADXP</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getHTML_ANY(java.util.List)"><!-- --></A><H3>
getHTML_ANY</H3>
<PRE>
private static java.lang.String <B>getHTML_ANY</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getHTML_BL(java.util.List)"><!-- --></A><H3>
getHTML_BL</H3>
<PRE>
private static java.lang.String <B>getHTML_BL</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getHTML_Boolean(java.lang.String)"><!-- --></A><H3>
getHTML_Boolean</H3>
<PRE>
private static java.lang.String <B>getHTML_Boolean</B>(java.lang.String attrName)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getHTML_Boolean(java.lang.String, java.lang.String)"><!-- --></A><H3>
getHTML_Boolean</H3>
<PRE>
private static java.lang.String <B>getHTML_Boolean</B>(java.lang.String attrName,
java.lang.String value)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getHTML(java.lang.String, java.lang.String)"><!-- --></A><H3>
getHTML</H3>
<PRE>
private static java.lang.String <B>getHTML</B>(java.lang.String attrName,
java.lang.String validationClass)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getHTML(java.lang.String, java.lang.String, java.lang.String)"><!-- --></A><H3>
getHTML</H3>
<PRE>
private static java.lang.String <B>getHTML</B>(java.lang.String attrName,
java.lang.String validationClass,
java.lang.String value)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getHTML_CD(java.util.List)"><!-- --></A><H3>
getHTML_CD</H3>
<PRE>
private static java.lang.String <B>getHTML_CD</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getHTML_DSET(java.lang.String, java.util.List)"><!-- --></A><H3>
getHTML_DSET</H3>
<PRE>
private static java.lang.String <B>getHTML_DSET</B>(java.lang.String genericType,
java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getHTML_ED(java.util.List)"><!-- --></A><H3>
getHTML_ED</H3>
<PRE>
private static java.lang.String <B>getHTML_ED</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getHTML_ED_TEXT(java.util.List)"><!-- --></A><H3>
getHTML_ED_TEXT</H3>
<PRE>
private static java.lang.String <B>getHTML_ED_TEXT</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getHTML_EN(java.util.List)"><!-- --></A><H3>
getHTML_EN</H3>
<PRE>
private static java.lang.String <B>getHTML_EN</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getHTML_ENON(java.util.List)"><!-- --></A><H3>
getHTML_ENON</H3>
<PRE>
private static java.lang.String <B>getHTML_ENON</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getHTML_ENPN(java.util.List)"><!-- --></A><H3>
getHTML_ENPN</H3>
<PRE>
private static java.lang.String <B>getHTML_ENPN</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getHTML_ENXP(java.util.List)"><!-- --></A><H3>
getHTML_ENXP</H3>
<PRE>
private static java.lang.String <B>getHTML_ENXP</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getHTML_II(java.util.List, java.lang.String)"><!-- --></A><H3>
getHTML_II</H3>
<PRE>
private static java.lang.String <B>getHTML_II</B>(java.util.List<java.lang.Object> searchableFields,
java.lang.String attrName)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getHTML_INT(java.util.List)"><!-- --></A><H3>
getHTML_INT</H3>
<PRE>
private static java.lang.String <B>getHTML_INT</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getHTML_IVL(java.lang.String, java.util.List)"><!-- --></A><H3>
getHTML_IVL</H3>
<PRE>
private static java.lang.String <B>getHTML_IVL</B>(java.lang.String genericType,
java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getHTML_PQV(java.util.List)"><!-- --></A><H3>
getHTML_PQV</H3>
<PRE>
private static java.lang.String <B>getHTML_PQV</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getHTML_PQ(java.util.List)"><!-- --></A><H3>
getHTML_PQ</H3>
<PRE>
private static java.lang.String <B>getHTML_PQ</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getHTML_QTY(java.util.List)"><!-- --></A><H3>
getHTML_QTY</H3>
<PRE>
private static java.lang.String <B>getHTML_QTY</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getHTML_REAL(java.util.List)"><!-- --></A><H3>
getHTML_REAL</H3>
<PRE>
private static java.lang.String <B>getHTML_REAL</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getHTML_SC(java.util.List)"><!-- --></A><H3>
getHTML_SC</H3>
<PRE>
private static java.lang.String <B>getHTML_SC</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getHTML_ST(java.util.List)"><!-- --></A><H3>
getHTML_ST</H3>
<PRE>
private static java.lang.String <B>getHTML_ST</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getHTML_ST_NT(java.util.List)"><!-- --></A><H3>
getHTML_ST_NT</H3>
<PRE>
private static java.lang.String <B>getHTML_ST_NT</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getHTML_TEL(java.util.List)"><!-- --></A><H3>
getHTML_TEL</H3>
<PRE>
private static java.lang.String <B>getHTML_TEL</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getHTML_TEL_EMAIL(java.util.List)"><!-- --></A><H3>
getHTML_TEL_EMAIL</H3>
<PRE>
private static java.lang.String <B>getHTML_TEL_EMAIL</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getHTML_TEL_PERSON(java.util.List)"><!-- --></A><H3>
getHTML_TEL_PERSON</H3>
<PRE>
private static java.lang.String <B>getHTML_TEL_PERSON</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getHTML_TEL_PHONE(java.util.List)"><!-- --></A><H3>
getHTML_TEL_PHONE</H3>
<PRE>
private static java.lang.String <B>getHTML_TEL_PHONE</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getHTML_TEL_URL(java.util.List)"><!-- --></A><H3>
getHTML_TEL_URL</H3>
<PRE>
private static java.lang.String <B>getHTML_TEL_URL</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getHTML_TS(java.util.List)"><!-- --></A><H3>
getHTML_TS</H3>
<PRE>
private static java.lang.String <B>getHTML_TS</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getScreen_AD(java.util.List)"><!-- --></A><H3>
getScreen_AD</H3>
<PRE>
private static java.lang.String <B>getScreen_AD</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getScreen_ADXP(java.util.List)"><!-- --></A><H3>
getScreen_ADXP</H3>
<PRE>
private static java.lang.String <B>getScreen_ADXP</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getScreen_BL(java.util.List)"><!-- --></A><H3>
getScreen_BL</H3>
<PRE>
private static java.lang.String <B>getScreen_BL</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getScreen_BL_NONNULL(java.util.List)"><!-- --></A><H3>
getScreen_BL_NONNULL</H3>
<PRE>
private static java.lang.String <B>getScreen_BL_NONNULL</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getScreen_CD(java.util.List)"><!-- --></A><H3>
getScreen_CD</H3>
<PRE>
private static java.lang.String <B>getScreen_CD</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getScreen_DSET(java.lang.String, java.util.List)"><!-- --></A><H3>
getScreen_DSET</H3>
<PRE>
private static java.lang.String <B>getScreen_DSET</B>(java.lang.String genericType,
java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getScreen_ED(java.util.List)"><!-- --></A><H3>
getScreen_ED</H3>
<PRE>
private static java.lang.String <B>getScreen_ED</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getScreen_ED_TEXT(java.util.List)"><!-- --></A><H3>
getScreen_ED_TEXT</H3>
<PRE>
private static java.lang.String <B>getScreen_ED_TEXT</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getScreen_EN(java.util.List)"><!-- --></A><H3>
getScreen_EN</H3>
<PRE>
private static java.lang.String <B>getScreen_EN</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getScreen_ENON(java.util.List)"><!-- --></A><H3>
getScreen_ENON</H3>
<PRE>
private static java.lang.String <B>getScreen_ENON</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getScreen_ENPN(java.util.List)"><!-- --></A><H3>
getScreen_ENPN</H3>
<PRE>
private static java.lang.String <B>getScreen_ENPN</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getScreen_ENXP(java.util.List)"><!-- --></A><H3>
getScreen_ENXP</H3>
<PRE>
private static java.lang.String <B>getScreen_ENXP</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getScreen_II(java.util.List, java.lang.String)"><!-- --></A><H3>
getScreen_II</H3>
<PRE>
private static java.lang.String <B>getScreen_II</B>(java.util.List<java.lang.Object> searchableFields,
java.lang.String attrName)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getScreen_INT(java.util.List)"><!-- --></A><H3>
getScreen_INT</H3>
<PRE>
private static java.lang.String <B>getScreen_INT</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getScreen_IVL(java.lang.String, java.util.List)"><!-- --></A><H3>
getScreen_IVL</H3>
<PRE>
private static java.lang.String <B>getScreen_IVL</B>(java.lang.String genericType,
java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getScreen_PQ(java.util.List)"><!-- --></A><H3>
getScreen_PQ</H3>
<PRE>
private static java.lang.String <B>getScreen_PQ</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getScreen_QTY(java.util.List)"><!-- --></A><H3>
getScreen_QTY</H3>
<PRE>
private static java.lang.String <B>getScreen_QTY</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getScreen_REAL(java.util.List)"><!-- --></A><H3>
getScreen_REAL</H3>
<PRE>
private static java.lang.String <B>getScreen_REAL</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getScreen_SC(java.util.List)"><!-- --></A><H3>
getScreen_SC</H3>
<PRE>
private static java.lang.String <B>getScreen_SC</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getScreen_ST(java.util.List)"><!-- --></A><H3>
getScreen_ST</H3>
<PRE>
private static java.lang.String <B>getScreen_ST</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getScreen_ST_NT(java.util.List)"><!-- --></A><H3>
getScreen_ST_NT</H3>
<PRE>
private static java.lang.String <B>getScreen_ST_NT</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getScreen_TEL(java.util.List)"><!-- --></A><H3>
getScreen_TEL</H3>
<PRE>
private static java.lang.String <B>getScreen_TEL</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getScreen_TEL_EMAIL(java.util.List)"><!-- --></A><H3>
getScreen_TEL_EMAIL</H3>
<PRE>
private static java.lang.String <B>getScreen_TEL_EMAIL</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getScreen_TEL_PERSON(java.util.List)"><!-- --></A><H3>
getScreen_TEL_PERSON</H3>
<PRE>
private static java.lang.String <B>getScreen_TEL_PERSON</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getScreen_TEL_PHONE(java.util.List)"><!-- --></A><H3>
getScreen_TEL_PHONE</H3>
<PRE>
private static java.lang.String <B>getScreen_TEL_PHONE</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getScreen_TEL_URL(java.util.List)"><!-- --></A><H3>
getScreen_TEL_URL</H3>
<PRE>
private static java.lang.String <B>getScreen_TEL_URL</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getScreen_TS(java.util.List)"><!-- --></A><H3>
getScreen_TS</H3>
<PRE>
private static java.lang.String <B>getScreen_TS</B>(java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getHtmlFor(java.lang.String, java.lang.String)"><!-- --></A><H3>
getHtmlFor</H3>
<PRE>
public static java.lang.String <B>getHtmlFor</B>(java.lang.String attrName,
java.lang.String attrType)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getHtmlFor(java.lang.String, java.lang.String, java.lang.String)"><!-- --></A><H3>
getHtmlFor</H3>
<PRE>
public static java.lang.String <B>getHtmlFor</B>(java.lang.String attrName,
java.lang.String attrType,
java.lang.String value)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getAttributeValue(org.jdom.Element, java.lang.String)"><!-- --></A><H3>
getAttributeValue</H3>
<PRE>
public static java.lang.String <B>getAttributeValue</B>(org.jdom.Element root,
java.lang.String attName)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getHtmlFor(java.lang.String, java.lang.String, java.util.List)"><!-- --></A><H3>
getHtmlFor</H3>
<PRE>
public static java.lang.String <B>getHtmlFor</B>(java.lang.String attrName,
java.lang.String attrType,
java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getComplexSearchFields(java.lang.String, java.util.List)"><!-- --></A><H3>
getComplexSearchFields</H3>
<PRE>
private static java.util.List<java.lang.Object> <B>getComplexSearchFields</B>(java.lang.String complexType,
java.util.List<java.lang.Object> searchableFields)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<!-- ========= END OF CLASS DATA ========= -->
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/HtmlUtils.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV CLASS
<A HREF="../../../../../../gov/nih/nci/system/web/util/HTTPUtils.html" title="class in gov.nih.nci.system.web.util"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?gov/nih/nci/system/web/util/HtmlUtils.html" target="_top"><B>FRAMES</B></A>
<A HREF="HtmlUtils.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | <A HREF="#field_summary">FIELD</A> | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: <A HREF="#field_detail">FIELD</A> | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
This API was generated by the caCORE Software Development Kit (SDK)
</BODY>
</HTML>
| {
"content_hash": "26001ace9f9ba5eaa0d2a339358cde58",
"timestamp": "",
"source": "github",
"line_count": 2234,
"max_line_length": 242,
"avg_line_length": 37.384959713518356,
"alnum_prop": 0.6318278694413181,
"repo_name": "NCIP/cadsr-objectcart",
"id": "56aa48d64ba9ca3ed4fd80d03f13937c17b00e25",
"size": "83518",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "objectCart/software/src/web/docs/system/gov/nih/nci/system/web/util/HtmlUtils.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "749890"
},
{
"name": "Java",
"bytes": "116781"
},
{
"name": "JavaScript",
"bytes": "4923606"
},
{
"name": "PHP",
"bytes": "14325"
},
{
"name": "XSLT",
"bytes": "17240"
}
],
"symlink_target": ""
} |
using namespace seqan;
SEQAN_DEFINE_TEST(test_rsbs_iterator_get_value)
{
unsigned length_ = 1000;
String<unsigned> controlString;
resize(controlString, length_);
Rng<MersenneTwister> rng(SEED);
controlString[0] = pickRandomNumber(rng) % 2;
for (unsigned i = 1; i < length_; ++i)
{
controlString[i] = pickRandomNumber(rng) % 2;
}
typedef RankSupportBitString<void> TRankSupportBitString;
TRankSupportBitString bitString(controlString);
Iterator<RankSupportBitString<void> >::Type defaultIt = begin(bitString);
for (unsigned i = 0; i < length(bitString); ++i)
{
SEQAN_ASSERT(getBit(bitString, i) == getValue(defaultIt));
SEQAN_ASSERT(getBit(bitString, i) == getValue(defaultIt, Bit()));
SEQAN_ASSERT(getRank(bitString, i) == getValue(defaultIt, Rank()));
++defaultIt;
}
}
#endif // TEST_INDEX_FM_RANK_SUPPORT_BIT_STRING_H_
| {
"content_hash": "78af478a0e12114e8f16d22ee6128d79",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 77,
"avg_line_length": 30.8,
"alnum_prop": 0.6623376623376623,
"repo_name": "cmccoy/codon-sw",
"id": "db36c675b2d853c9a613075f5182acff14c6c19c",
"size": "3059",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "deps/seqan/core/tests/index/test_index_fm_rank_support_bit_string_iterator.h",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "C++",
"bytes": "35724"
}
],
"symlink_target": ""
} |
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html#License
package com.ibm.icu.impl.data;
import java.util.ListResourceBundle;
public class HolidayBundle_en extends ListResourceBundle {
// Normally, each HolidayBundle uses the holiday's US English name
// as the string key for looking up the localized name. This means
// that the key itself can be used if no name is found for the requested
// locale.
//
// For holidays where the key is _not_ the English name, e.g. in the
// case of conflicts, the English name must be given here.
//
static private final Object[][] fContents = {
{ "", "" }, // Can't be empty!
};
@Override
public synchronized Object[][] getContents() { return fContents; }
}
| {
"content_hash": "915857643cc39d5879e446cc3a8764f4",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 76,
"avg_line_length": 31.923076923076923,
"alnum_prop": 0.6638554216867469,
"repo_name": "sabi0/fitnotifications",
"id": "004ec2b531c070351d16d8f97e8026612076b105",
"size": "1161",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "icu4j/src/main/java/com/ibm/icu/impl/data/HolidayBundle_en.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "9711995"
}
],
"symlink_target": ""
} |
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Stashcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef STASHCOIN_ALLOCATORS_H
#define STASHCOIN_ALLOCATORS_H
#include <string.h>
#include <string>
#include <boost/thread/mutex.hpp>
#include <map>
#include <openssl/crypto.h> // for OPENSSL_cleanse()
#ifdef WIN32
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
// This is used to attempt to keep keying material out of swap
// Note that VirtualLock does not provide this as a guarantee on Windows,
// but, in practice, memory that has been VirtualLock'd almost never gets written to
// the pagefile except in rare circumstances where memory is extremely low.
#else
#include <sys/mman.h>
#include <limits.h> // for PAGESIZE
#include <unistd.h> // for sysconf
#endif
/**
* Thread-safe class to keep track of locked (ie, non-swappable) memory pages.
*
* Memory locks do not stack, that is, pages which have been locked several times by calls to mlock()
* will be unlocked by a single call to munlock(). This can result in keying material ending up in swap when
* those functions are used naively. This class simulates stacking memory locks by keeping a counter per page.
*
* @note By using a map from each page base address to lock count, this class is optimized for
* small objects that span up to a few pages, mostly smaller than a page. To support large allocations,
* something like an interval tree would be the preferred data structure.
*/
template <class Locker> class LockedPageManagerBase
{
public:
LockedPageManagerBase(size_t page_size):
page_size(page_size)
{
// Determine bitmask for extracting page from address
assert(!(page_size & (page_size-1))); // size must be power of two
page_mask = ~(page_size - 1);
}
// For all pages in affected range, increase lock count
void LockRange(void *p, size_t size)
{
boost::mutex::scoped_lock lock(mutex);
if(!size) return;
const size_t base_addr = reinterpret_cast<size_t>(p);
const size_t start_page = base_addr & page_mask;
const size_t end_page = (base_addr + size - 1) & page_mask;
for(size_t page = start_page; page <= end_page; page += page_size)
{
Histogram::iterator it = histogram.find(page);
if(it == histogram.end()) // Newly locked page
{
locker.Lock(reinterpret_cast<void*>(page), page_size);
histogram.insert(std::make_pair(page, 1));
}
else // Page was already locked; increase counter
{
it->second += 1;
}
}
}
// For all pages in affected range, decrease lock count
void UnlockRange(void *p, size_t size)
{
boost::mutex::scoped_lock lock(mutex);
if(!size) return;
const size_t base_addr = reinterpret_cast<size_t>(p);
const size_t start_page = base_addr & page_mask;
const size_t end_page = (base_addr + size - 1) & page_mask;
for(size_t page = start_page; page <= end_page; page += page_size)
{
Histogram::iterator it = histogram.find(page);
assert(it != histogram.end()); // Cannot unlock an area that was not locked
// Decrease counter for page, when it is zero, the page will be unlocked
it->second -= 1;
if(it->second == 0) // Nothing on the page anymore that keeps it locked
{
// Unlock page and remove the count from histogram
locker.Unlock(reinterpret_cast<void*>(page), page_size);
histogram.erase(it);
}
}
}
// Get number of locked pages for diagnostics
int GetLockedPageCount()
{
boost::mutex::scoped_lock lock(mutex);
return histogram.size();
}
private:
Locker locker;
boost::mutex mutex;
size_t page_size, page_mask;
// map of page base address to lock count
typedef std::map<size_t,int> Histogram;
Histogram histogram;
};
/** Determine system page size in bytes */
static inline size_t GetSystemPageSize()
{
size_t page_size;
#if defined(WIN32)
SYSTEM_INFO sSysInfo;
GetSystemInfo(&sSysInfo);
page_size = sSysInfo.dwPageSize;
#elif defined(PAGESIZE) // defined in limits.h
page_size = PAGESIZE;
#else // assume some POSIX OS
page_size = sysconf(_SC_PAGESIZE);
#endif
return page_size;
}
/**
* OS-dependent memory page locking/unlocking.
* Defined as policy class to make stubbing for test possible.
*/
class MemoryPageLocker
{
public:
/** Lock memory pages.
* addr and len must be a multiple of the system page size
*/
bool Lock(const void *addr, size_t len)
{
#ifdef WIN32
return VirtualLock(const_cast<void*>(addr), len);
#else
return mlock(addr, len) == 0;
#endif
}
/** Unlock memory pages.
* addr and len must be a multiple of the system page size
*/
bool Unlock(const void *addr, size_t len)
{
#ifdef WIN32
return VirtualUnlock(const_cast<void*>(addr), len);
#else
return munlock(addr, len) == 0;
#endif
}
};
/**
* Singleton class to keep track of locked (ie, non-swappable) memory pages, for use in
* std::allocator templates.
*/
class LockedPageManager: public LockedPageManagerBase<MemoryPageLocker>
{
public:
static LockedPageManager instance; // instantiated in util.cpp
private:
LockedPageManager():
LockedPageManagerBase<MemoryPageLocker>(GetSystemPageSize())
{}
};
//
// Allocator that locks its contents from being paged
// out of memory and clears its contents before deletion.
//
template<typename T>
struct secure_allocator : public std::allocator<T>
{
// MSVC8 default copy constructor is broken
typedef std::allocator<T> base;
typedef typename base::size_type size_type;
typedef typename base::difference_type difference_type;
typedef typename base::pointer pointer;
typedef typename base::const_pointer const_pointer;
typedef typename base::reference reference;
typedef typename base::const_reference const_reference;
typedef typename base::value_type value_type;
secure_allocator() throw() {}
secure_allocator(const secure_allocator& a) throw() : base(a) {}
template <typename U>
secure_allocator(const secure_allocator<U>& a) throw() : base(a) {}
~secure_allocator() throw() {}
template<typename _Other> struct rebind
{ typedef secure_allocator<_Other> other; };
T* allocate(std::size_t n, const void *hint = 0)
{
T *p;
p = std::allocator<T>::allocate(n, hint);
if (p != NULL)
LockedPageManager::instance.LockRange(p, sizeof(T) * n);
return p;
}
void deallocate(T* p, std::size_t n)
{
if (p != NULL)
{
OPENSSL_cleanse(p, sizeof(T) * n);
LockedPageManager::instance.UnlockRange(p, sizeof(T) * n);
}
std::allocator<T>::deallocate(p, n);
}
};
//
// Allocator that clears its contents before deletion.
//
template<typename T>
struct zero_after_free_allocator : public std::allocator<T>
{
// MSVC8 default copy constructor is broken
typedef std::allocator<T> base;
typedef typename base::size_type size_type;
typedef typename base::difference_type difference_type;
typedef typename base::pointer pointer;
typedef typename base::const_pointer const_pointer;
typedef typename base::reference reference;
typedef typename base::const_reference const_reference;
typedef typename base::value_type value_type;
zero_after_free_allocator() throw() {}
zero_after_free_allocator(const zero_after_free_allocator& a) throw() : base(a) {}
template <typename U>
zero_after_free_allocator(const zero_after_free_allocator<U>& a) throw() : base(a) {}
~zero_after_free_allocator() throw() {}
template<typename _Other> struct rebind
{ typedef zero_after_free_allocator<_Other> other; };
void deallocate(T* p, std::size_t n)
{
if (p != NULL)
OPENSSL_cleanse(p, sizeof(T) * n);
std::allocator<T>::deallocate(p, n);
}
};
// This is exactly like std::string, but with a custom allocator.
typedef std::basic_string<char, std::char_traits<char>, secure_allocator<char> > SecureString;
#endif
| {
"content_hash": "3fab15671466d222e85b2d8d6c623f52",
"timestamp": "",
"source": "github",
"line_count": 258,
"max_line_length": 110,
"avg_line_length": 33.36434108527132,
"alnum_prop": 0.6548559479553904,
"repo_name": "stashdev/stashcoin",
"id": "1826573916228c779a0e3bdbdf042424a3c81beb",
"size": "8608",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/allocators.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "101975"
},
{
"name": "C++",
"bytes": "13269646"
},
{
"name": "CSS",
"bytes": "1127"
},
{
"name": "IDL",
"bytes": "13788"
},
{
"name": "Objective-C",
"bytes": "2656"
},
{
"name": "Python",
"bytes": "3773"
},
{
"name": "Shell",
"bytes": "8319"
},
{
"name": "TypeScript",
"bytes": "5240693"
}
],
"symlink_target": ""
} |
<?php
declare(strict_types=1);
/*
* This file is part of SolidInvoice project.
*
* (c) Pierre du Plessis <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace SolidInvoice\DashboardBundle\Action;
use SolidInvoice\CoreBundle\Templating\Template;
use Symfony\Component\HttpFoundation\Request;
final class Index
{
public function __invoke(Request $request): Template
{
return new Template('@SolidInvoiceDashboard/Default/index.html.twig');
}
}
| {
"content_hash": "484822c4ea6f3b68602c94272f59c744",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 78,
"avg_line_length": 22.84,
"alnum_prop": 0.7338003502626971,
"repo_name": "pierredup/CSBill",
"id": "61349280cd643de7043c23804a1daa39925c7cf4",
"size": "571",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "src/DashboardBundle/Action/Index.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "3754"
},
{
"name": "CSS",
"bytes": "24685"
},
{
"name": "Gherkin",
"bytes": "33358"
},
{
"name": "HTML",
"bytes": "203058"
},
{
"name": "JavaScript",
"bytes": "197931"
},
{
"name": "PHP",
"bytes": "1114416"
},
{
"name": "Shell",
"bytes": "1035"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
namespace Langben.DAL
{
[MetadataType(typeof(SysPersonMetadata))]//使用SysPersonMetadata对SysPerson进行数据验证
public partial class SysPerson
{
#region 自定义属性,即由数据实体扩展的实体
[Display(Name = "部门")]
public string SysDepartmentIdOld { get; set; }
[Display(Name = "角色")]
public string SysRoleId { get; set; }
[Display(Name = "角色")]
public string SysRoleIdOld { get; set; }
[Display(Name = "文档管理")]
public string SysDocumentId { get; set; }
[Display(Name = "文档管理")]
public string SysDocumentIdOld { get; set; }
#endregion
}
public class SysPersonMetadata
{
[ScaffoldColumn(false)]
[Display(Name = "主键", Order = 1)]
public object Id { get; set; }
[ScaffoldColumn(true)]
[Display(Name = "用户名", Order = 2)]
[Required(ErrorMessage = "请填写")]
[StringLength(200, ErrorMessage = "长度不可超过200")]
public object Name { get; set; }
[ScaffoldColumn(true)]
[Display(Name = "姓名", Order = 3)]
[Required(ErrorMessage = "请填写")]
[StringLength(200, ErrorMessage = "长度不可超过200")]
public object MyName { get; set; }
[StringLength(100, ErrorMessage = "{0} 必须至少包含 {2} 个字符。", MinimumLength = 6)]
[ScaffoldColumn(true)]
[Display(Name = "密码", Order = 4)]
[Required(ErrorMessage = "请填写")]
[DataType(System.ComponentModel.DataAnnotations.DataType.Password)]
public object Password { get; set; }
[ScaffoldColumn(true)]
[Display(Name = "确认密码", Order = 5)]
[Required(ErrorMessage = "请填写")]
[StringLength(200, ErrorMessage = "长度不可超过200")]
[DataType(System.ComponentModel.DataAnnotations.DataType.Password)]
[System.ComponentModel.DataAnnotations.Compare("Password", ErrorMessage = "两次密码不一致")]
public object SurePassword { get; set; }
[ScaffoldColumn(true)]
[Display(Name = "性别", Order = 6)]
[StringLength(200, ErrorMessage = "长度不可超过200")]
public object Sex { get; set; }
[ScaffoldColumn(true)]
[Display(Name = "部门", Order = 7)]
[StringLength(36, ErrorMessage = "长度不可超过36")]
public object SysDepartmentId { get; set; }
[ScaffoldColumn(true)]
[Display(Name = "职位", Order = 8)]
[StringLength(200, ErrorMessage = "长度不可超过200")]
public object Position { get; set; }
[ScaffoldColumn(true)]
[Display(Name = "手机号码", Order = 9)]
[StringLength(200, ErrorMessage = "长度不可超过200")]
public object MobilePhoneNumber { get; set; }
[ScaffoldColumn(true)]
[Display(Name = "办公电话", Order = 10)]
[StringLength(200, ErrorMessage = "长度不可超过200")]
[DataType(System.ComponentModel.DataAnnotations.DataType.PhoneNumber, ErrorMessage = "号码格式不正确")]
public object PhoneNumber { get; set; }
[ScaffoldColumn(true)]
[Display(Name = "省", Order = 11)]
[StringLength(200, ErrorMessage = "长度不可超过200")]
public object Province { get; set; }
[ScaffoldColumn(true)]
[Display(Name = "市", Order = 12)]
[StringLength(200, ErrorMessage = "长度不可超过200")]
public object City { get; set; }
[ScaffoldColumn(true)]
[Display(Name = "县", Order = 13)]
[StringLength(200, ErrorMessage = "长度不可超过200")]
public object Village { get; set; }
[ScaffoldColumn(true)]
[Display(Name = "联系地址", Order = 14)]
[StringLength(200, ErrorMessage = "长度不可超过200")]
public object Address { get; set; }
[ScaffoldColumn(true)]
[Display(Name = "邮箱", Order = 15)]
[StringLength(200, ErrorMessage = "长度不可超过200")]
public object EmailAddress { get; set; }
[ScaffoldColumn(true)]
[Display(Name = "备注", Order = 16)]
[StringLength(4000, ErrorMessage = "长度不可超过4000")]
public object Remark { get; set; }
[ScaffoldColumn(true)]
[Display(Name = "状态", Order = 17)]
[StringLength(200, ErrorMessage = "长度不可超过200")]
public object State { get; set; }
[ScaffoldColumn(true)]
[Display(Name = "创建时间", Order = 18)]
[DataType(System.ComponentModel.DataAnnotations.DataType.DateTime, ErrorMessage = "时间格式不正确")]
public DateTime? CreateTime { get; set; }
[ScaffoldColumn(true)]
[Display(Name = "创建人", Order = 19)]
[StringLength(200, ErrorMessage = "长度不可超过200")]
public object CreatePerson { get; set; }
[ScaffoldColumn(true)]
[Display(Name = "编辑时间", Order = 20)]
[DataType(System.ComponentModel.DataAnnotations.DataType.DateTime, ErrorMessage = "时间格式不正确")]
public DateTime? UpdateTime { get; set; }
[ScaffoldColumn(true)]
[Display(Name = "登录次数", Order = 21)]
[Range(0, 2147483646, ErrorMessage = "数值超出范围")]
public int? LogonNum { get; set; }
[ScaffoldColumn(true)]
[Display(Name = "本次登录时间", Order = 22)]
[DataType(System.ComponentModel.DataAnnotations.DataType.DateTime, ErrorMessage = "时间格式不正确")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
public DateTime? LogonTime { get; set; }
[ScaffoldColumn(true)]
[Display(Name = "登录IP", Order = 23)]
[StringLength(200, ErrorMessage = "长度不可超过200")]
public object LogonIP { get; set; }
[ScaffoldColumn(true)]
[Display(Name = "上次登录时间", Order = 24)]
[DataType(System.ComponentModel.DataAnnotations.DataType.DateTime, ErrorMessage = "时间格式不正确")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
public DateTime? LastLogonTime { get; set; }
[ScaffoldColumn(true)]
[Display(Name = "上次登录IP", Order = 25)]
[StringLength(200, ErrorMessage = "长度不可超过200")]
public object LastLogonIP { get; set; }
[ScaffoldColumn(true)]
[Display(Name = "页面皮肤", Order = 26)]
[StringLength(200, ErrorMessage = "长度不可超过200")]
public object PageStyle { get; set; }
[ScaffoldColumn(true)]
[Display(Name = "编辑人", Order = 27)]
[StringLength(200, ErrorMessage = "长度不可超过200")]
public object UpdatePerson { get; set; }
[ScaffoldColumn(true)]
[Display(Name = "时间戳", Order = 28)]
public object Version { get; set; }
[ScaffoldColumn(true)]
[Display(Name = "高清头像", Order = 29)]
public object HDpic { get; set; }
}
}
| {
"content_hash": "eafa678e8e21929e05352058aad70099",
"timestamp": "",
"source": "github",
"line_count": 188,
"max_line_length": 104,
"avg_line_length": 35.569148936170215,
"alnum_prop": 0.5987737400927172,
"repo_name": "Langbencom/rights",
"id": "61b0cb7f2d2e1f1eb06cdcbd4c4dce2d6a1358b2",
"size": "7323",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Rights/DAL/SysPersonMeta.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "240"
},
{
"name": "ActionScript",
"bytes": "323602"
},
{
"name": "C#",
"bytes": "1373621"
},
{
"name": "CSS",
"bytes": "1776432"
},
{
"name": "HTML",
"bytes": "6800"
},
{
"name": "JavaScript",
"bytes": "1168331"
},
{
"name": "PHP",
"bytes": "3388"
},
{
"name": "PLpgSQL",
"bytes": "43604"
}
],
"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.11"/>
<title>V8 API Reference Guide for node.js v7.9.0: v8::DefaultGlobalMapTraits< K, V > Class Template 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/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</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 id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">V8 API Reference Guide for node.js v7.9.0
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.11 -->
<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="namespaces.html"><span>Namespaces</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li><a href="examples.html"><span>Examples</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>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="inherits.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</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)">
</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 id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="namespacev8.html">v8</a></li><li class="navelem"><a class="el" href="classv8_1_1DefaultGlobalMapTraits.html">DefaultGlobalMapTraits</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="summary">
<a href="#nested-classes">Classes</a> |
<a href="#pub-types">Public Types</a> |
<a href="#pub-static-methods">Static Public Member Functions</a> |
<a href="#pub-static-attribs">Static Public Attributes</a> |
<a href="classv8_1_1DefaultGlobalMapTraits-members.html">List of all members</a> </div>
<div class="headertitle">
<div class="title">v8::DefaultGlobalMapTraits< K, V > Class Template Reference</div> </div>
</div><!--header-->
<div class="contents">
<div class="dynheader">
Inheritance diagram for v8::DefaultGlobalMapTraits< K, V >:</div>
<div class="dyncontent">
<div class="center"><img src="classv8_1_1DefaultGlobalMapTraits__inherit__graph.png" border="0" usemap="#v8_1_1DefaultGlobalMapTraits_3_01K_00_01V_01_4_inherit__map" alt="Inheritance graph"/></div>
<map name="v8_1_1DefaultGlobalMapTraits_3_01K_00_01V_01_4_inherit__map" id="v8_1_1DefaultGlobalMapTraits_3_01K_00_01V_01_4_inherit__map">
</map>
<center><span class="legend">[<a href="graph_legend.html">legend</a>]</span></center></div>
<div class="dynheader">
Collaboration diagram for v8::DefaultGlobalMapTraits< K, V >:</div>
<div class="dyncontent">
<div class="center"><img src="classv8_1_1DefaultGlobalMapTraits__coll__graph.png" border="0" usemap="#v8_1_1DefaultGlobalMapTraits_3_01K_00_01V_01_4_coll__map" alt="Collaboration graph"/></div>
<map name="v8_1_1DefaultGlobalMapTraits_3_01K_00_01V_01_4_coll__map" id="v8_1_1DefaultGlobalMapTraits_3_01K_00_01V_01_4_coll__map">
</map>
<center><span class="legend">[<a href="graph_legend.html">legend</a>]</span></center></div>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-types"></a>
Public Types</h2></td></tr>
<tr class="memitem:a6626b089621a436fde5ac1a1132cc83c"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a6626b089621a436fde5ac1a1132cc83c"></a>
typedef <a class="el" href="classv8_1_1GlobalValueMap.html">GlobalValueMap</a>< K, V, <a class="el" href="classv8_1_1DefaultGlobalMapTraits.html">DefaultGlobalMapTraits</a>< K, V > > </td><td class="memItemRight" valign="bottom"><b>MapType</b></td></tr>
<tr class="separator:a6626b089621a436fde5ac1a1132cc83c"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:af5285197aae83dcb00d0381fbc90869e"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="af5285197aae83dcb00d0381fbc90869e"></a>
typedef void </td><td class="memItemRight" valign="bottom"><b>WeakCallbackDataType</b></td></tr>
<tr class="separator:af5285197aae83dcb00d0381fbc90869e"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="inherit_header pub_types_classv8_1_1StdMapTraits"><td colspan="2" onclick="javascript:toggleInherit('pub_types_classv8_1_1StdMapTraits')"><img src="closed.png" alt="-"/> Public Types inherited from <a class="el" href="classv8_1_1StdMapTraits.html">v8::StdMapTraits< K, V ></a></td></tr>
<tr class="memitem:ac64cb78b3ef5cfbc35cf03837552e4ea inherit pub_types_classv8_1_1StdMapTraits"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ac64cb78b3ef5cfbc35cf03837552e4ea"></a>
typedef std::map< K, PersistentContainerValue > </td><td class="memItemRight" valign="bottom"><b>Impl</b></td></tr>
<tr class="separator:ac64cb78b3ef5cfbc35cf03837552e4ea inherit pub_types_classv8_1_1StdMapTraits"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ad20ef2022e83bfba6dcee23a2a34098e inherit pub_types_classv8_1_1StdMapTraits"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ad20ef2022e83bfba6dcee23a2a34098e"></a>
typedef Impl::iterator </td><td class="memItemRight" valign="bottom"><b>Iterator</b></td></tr>
<tr class="separator:ad20ef2022e83bfba6dcee23a2a34098e inherit pub_types_classv8_1_1StdMapTraits"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-static-methods"></a>
Static Public Member Functions</h2></td></tr>
<tr class="memitem:a3d4b483a077d6e5665cc62a23c719ee8"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a3d4b483a077d6e5665cc62a23c719ee8"></a>
static WeakCallbackDataType * </td><td class="memItemRight" valign="bottom"><b>WeakCallbackParameter</b> (<a class="el" href="classv8_1_1GlobalValueMap.html">MapType</a> *map, const K &key, <a class="el" href="classv8_1_1Local.html">Local</a>< V > value)</td></tr>
<tr class="separator:a3d4b483a077d6e5665cc62a23c719ee8"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ae65c4d78f93d033712aa328654c00250"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ae65c4d78f93d033712aa328654c00250"></a>
static <a class="el" href="classv8_1_1GlobalValueMap.html">MapType</a> * </td><td class="memItemRight" valign="bottom"><b>MapFromWeakCallbackInfo</b> (const <a class="el" href="classv8_1_1WeakCallbackInfo.html">WeakCallbackInfo</a>< WeakCallbackDataType > &data)</td></tr>
<tr class="separator:ae65c4d78f93d033712aa328654c00250"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a2ebc8d3bbfbe32598863ab44caa36207"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a2ebc8d3bbfbe32598863ab44caa36207"></a>
static K </td><td class="memItemRight" valign="bottom"><b>KeyFromWeakCallbackInfo</b> (const <a class="el" href="classv8_1_1WeakCallbackInfo.html">WeakCallbackInfo</a>< WeakCallbackDataType > &data)</td></tr>
<tr class="separator:a2ebc8d3bbfbe32598863ab44caa36207"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a106883e8168f48826fcfb71aa88e7994"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a106883e8168f48826fcfb71aa88e7994"></a>
static void </td><td class="memItemRight" valign="bottom"><b>DisposeCallbackData</b> (WeakCallbackDataType *data)</td></tr>
<tr class="separator:a106883e8168f48826fcfb71aa88e7994"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a2e50fabc65cf498e981015c1e92ece3e"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a2e50fabc65cf498e981015c1e92ece3e"></a>
static void </td><td class="memItemRight" valign="bottom"><b>OnWeakCallback</b> (const <a class="el" href="classv8_1_1WeakCallbackInfo.html">WeakCallbackInfo</a>< WeakCallbackDataType > &data)</td></tr>
<tr class="separator:a2e50fabc65cf498e981015c1e92ece3e"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:af2a539ddbe5db2b6e1e944590e1dd7e6"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="af2a539ddbe5db2b6e1e944590e1dd7e6"></a>
static void </td><td class="memItemRight" valign="bottom"><b>Dispose</b> (<a class="el" href="classv8_1_1Isolate.html">Isolate</a> *isolate, <a class="el" href="classv8_1_1Global.html">Global</a>< V > value, K key)</td></tr>
<tr class="separator:af2a539ddbe5db2b6e1e944590e1dd7e6"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ad3478535925c0f42664c97c4d35d1c91"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ad3478535925c0f42664c97c4d35d1c91"></a>
static void </td><td class="memItemRight" valign="bottom"><b>DisposeWeak</b> (const <a class="el" href="classv8_1_1WeakCallbackInfo.html">WeakCallbackInfo</a>< WeakCallbackDataType > &data)</td></tr>
<tr class="separator:ad3478535925c0f42664c97c4d35d1c91"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="inherit_header pub_static_methods_classv8_1_1StdMapTraits"><td colspan="2" onclick="javascript:toggleInherit('pub_static_methods_classv8_1_1StdMapTraits')"><img src="closed.png" alt="-"/> Static Public Member Functions inherited from <a class="el" href="classv8_1_1StdMapTraits.html">v8::StdMapTraits< K, V ></a></td></tr>
<tr class="memitem:a63765723a9d6457ef47a42f79b13eaf7 inherit pub_static_methods_classv8_1_1StdMapTraits"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a63765723a9d6457ef47a42f79b13eaf7"></a>
static bool </td><td class="memItemRight" valign="bottom"><b>Empty</b> (Impl *impl)</td></tr>
<tr class="separator:a63765723a9d6457ef47a42f79b13eaf7 inherit pub_static_methods_classv8_1_1StdMapTraits"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a60bd7720bbc6e662d948cf05283a009d inherit pub_static_methods_classv8_1_1StdMapTraits"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a60bd7720bbc6e662d948cf05283a009d"></a>
static size_t </td><td class="memItemRight" valign="bottom"><b>Size</b> (Impl *impl)</td></tr>
<tr class="separator:a60bd7720bbc6e662d948cf05283a009d inherit pub_static_methods_classv8_1_1StdMapTraits"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ae018f70b3284ffda2566c36156db8baa inherit pub_static_methods_classv8_1_1StdMapTraits"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ae018f70b3284ffda2566c36156db8baa"></a>
static void </td><td class="memItemRight" valign="bottom"><b>Swap</b> (Impl &a, Impl &b)</td></tr>
<tr class="separator:ae018f70b3284ffda2566c36156db8baa inherit pub_static_methods_classv8_1_1StdMapTraits"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:abc24bdbd2e7b054a7bd905759fad7987 inherit pub_static_methods_classv8_1_1StdMapTraits"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="abc24bdbd2e7b054a7bd905759fad7987"></a>
static Iterator </td><td class="memItemRight" valign="bottom"><b>Begin</b> (Impl *impl)</td></tr>
<tr class="separator:abc24bdbd2e7b054a7bd905759fad7987 inherit pub_static_methods_classv8_1_1StdMapTraits"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a3ac36ae9e3b5585faeb66bb744c24183 inherit pub_static_methods_classv8_1_1StdMapTraits"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a3ac36ae9e3b5585faeb66bb744c24183"></a>
static Iterator </td><td class="memItemRight" valign="bottom"><b>End</b> (Impl *impl)</td></tr>
<tr class="separator:a3ac36ae9e3b5585faeb66bb744c24183 inherit pub_static_methods_classv8_1_1StdMapTraits"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:aa90a541b794946054fbc1e76e3976c4f inherit pub_static_methods_classv8_1_1StdMapTraits"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="aa90a541b794946054fbc1e76e3976c4f"></a>
static K </td><td class="memItemRight" valign="bottom"><b>Key</b> (Iterator it)</td></tr>
<tr class="separator:aa90a541b794946054fbc1e76e3976c4f inherit pub_static_methods_classv8_1_1StdMapTraits"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ad85f9d7e2ac639208fbce6b04d2436ad inherit pub_static_methods_classv8_1_1StdMapTraits"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ad85f9d7e2ac639208fbce6b04d2436ad"></a>
static PersistentContainerValue </td><td class="memItemRight" valign="bottom"><b>Value</b> (Iterator it)</td></tr>
<tr class="separator:ad85f9d7e2ac639208fbce6b04d2436ad inherit pub_static_methods_classv8_1_1StdMapTraits"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a2f41e206a3b1c9806253cca40d2891b1 inherit pub_static_methods_classv8_1_1StdMapTraits"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a2f41e206a3b1c9806253cca40d2891b1"></a>
static PersistentContainerValue </td><td class="memItemRight" valign="bottom"><b>Set</b> (Impl *impl, K key, PersistentContainerValue value)</td></tr>
<tr class="separator:a2f41e206a3b1c9806253cca40d2891b1 inherit pub_static_methods_classv8_1_1StdMapTraits"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a96c6fa384a4f7b7a64b464457ff347c2 inherit pub_static_methods_classv8_1_1StdMapTraits"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a96c6fa384a4f7b7a64b464457ff347c2"></a>
static PersistentContainerValue </td><td class="memItemRight" valign="bottom"><b>Get</b> (Impl *impl, K key)</td></tr>
<tr class="separator:a96c6fa384a4f7b7a64b464457ff347c2 inherit pub_static_methods_classv8_1_1StdMapTraits"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ad35e42652392e70dd23fa4b69b9800ea inherit pub_static_methods_classv8_1_1StdMapTraits"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ad35e42652392e70dd23fa4b69b9800ea"></a>
static PersistentContainerValue </td><td class="memItemRight" valign="bottom"><b>Remove</b> (Impl *impl, K key)</td></tr>
<tr class="separator:ad35e42652392e70dd23fa4b69b9800ea inherit pub_static_methods_classv8_1_1StdMapTraits"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-static-attribs"></a>
Static Public Attributes</h2></td></tr>
<tr class="memitem:aca4a466a95927f10ea3fa0bff1e041d2"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="aca4a466a95927f10ea3fa0bff1e041d2"></a>
static const PersistentContainerCallbackType </td><td class="memItemRight" valign="bottom"><b>kCallbackType</b> = kNotWeak</td></tr>
<tr class="separator:aca4a466a95927f10ea3fa0bff1e041d2"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<hr/>The documentation for this class was generated from the following file:<ul>
<li>deps/v8/include/<a class="el" href="v8-util_8h_source.html">v8-util.h</a></li>
</ul>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.11
</small></address>
</body>
</html>
| {
"content_hash": "194a1c39e969e75cb71dd7f148a4567c",
"timestamp": "",
"source": "github",
"line_count": 204,
"max_line_length": 344,
"avg_line_length": 87.41176470588235,
"alnum_prop": 0.7278488111260655,
"repo_name": "v8-dox/v8-dox.github.io",
"id": "50700bd5c9102239880378351aeb31681ffc5882",
"size": "17832",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "9f73df5/html/classv8_1_1DefaultGlobalMapTraits.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
This example design targets the Alpha Data ADM-PCIE-9V3 FPGA board.
The design by default listens to UDP port 1234 at IP address 192.168.1.128 and
will echo back any packets received. The design will also respond correctly
to ARP requests.
* FPGA: xcvu3p-ffvc1517-2-i
* PHY: 10G BASE-R PHY IP core and internal GTY transceiver
## How to build
Run make to build. Ensure that the Xilinx Vivado toolchain components are
in PATH.
## How to test
Run make program to program the ADM-PCIE-9V3 board with Vivado. Then run
netcat -u 192.168.1.128 1234
to open a UDP connection to port 1234. Any text entered into netcat will be
echoed back after pressing enter.
It is also possible to use hping to test the design by running
hping 192.168.1.128 -2 -p 1234 -d 1024
| {
"content_hash": "fec55e951bacfa1f2bcb913dcacdf65a",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 78,
"avg_line_length": 30.115384615384617,
"alnum_prop": 0.7496807151979565,
"repo_name": "alexforencich/verilog-ethernet",
"id": "10a48174c298bb9e71dfb458897e7b8bc31494c3",
"size": "848",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "example/ADM_PCIE_9V3/fpga_10g/README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Makefile",
"bytes": "655682"
},
{
"name": "Python",
"bytes": "3186932"
},
{
"name": "Shell",
"bytes": "4505"
},
{
"name": "Tcl",
"bytes": "189025"
},
{
"name": "Verilog",
"bytes": "4219830"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.