text stringlengths 2 1.04M | meta dict |
|---|---|
import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';;
function rootClick(e) {
if (this.props.disableScrim || ReactDOM.findDOMNode(this).contains(e.target)) return;
this.scrimClick(e);
}
const privates = new WeakMap();
export default ParentClass => {
return class Scrim extends ParentClass {
static propTypes = {
disableScrim: PropTypes.bool
};
constructor(props, context) {
super(props, context);
privates.set(this, rootClick.bind(this));
}
scrimClick() {
}
componentDidMount(...args) {
if (super.componentDidMount) super.componentDidMount(...args);
const document = this.props.getDocument ? this.props.getDocument() : global.document;
if (typeof document === 'object') document.documentElement.addEventListener('click', privates.get(this));
}
componentWillUnmount(...args) {
if (super.componentWillUnmount) super.componentWillUnmount(...args);
const document = this.props.getDocument ? this.props.getDocument() : global.document;
if (typeof document === 'object') document.documentElement.removeEventListener('click', privates.get(this));
}
};
}; | {
"content_hash": "f26ed730d4b806ec5965257a9d25cea2",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 114,
"avg_line_length": 31.57894736842105,
"alnum_prop": 0.6891666666666667,
"repo_name": "sjolicoeur/pivotal-ui",
"id": "962e39a835c4f25fec00160da2abf43c4b82ce44",
"size": "1200",
"binary": false,
"copies": "1",
"ref": "refs/heads/development",
"path": "library/src/pivotal-ui-react/mixins/mixins/scrim_mixin.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "14441668"
},
{
"name": "HTML",
"bytes": "44301978"
},
{
"name": "JavaScript",
"bytes": "108876094"
},
{
"name": "Nginx",
"bytes": "23894"
},
{
"name": "Ruby",
"bytes": "17360"
},
{
"name": "Shell",
"bytes": "4676"
}
],
"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 (1.8.0_92) on Wed Jul 27 21:23:59 CEST 2016 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Package net.sourceforge.pmd.lang.java.rule.comments (PMD Java 5.5.1 Test API)</title>
<meta name="date" content="2016-07-27">
<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="Uses of Package net.sourceforge.pmd.lang.java.rule.comments (PMD Java 5.5.1 Test API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Use</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</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?net/sourceforge/pmd/lang/java/rule/comments/package-use.html" target="_top">Frames</a></li>
<li><a href="package-use.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>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 title="Uses of Package net.sourceforge.pmd.lang.java.rule.comments" class="title">Uses of Package<br>net.sourceforge.pmd.lang.java.rule.comments</h1>
</div>
<div class="contentContainer">No usage of net.sourceforge.pmd.lang.java.rule.comments</div>
<!-- ======= 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</li>
<li class="navBarCell1Rev">Use</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</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?net/sourceforge/pmd/lang/java/rule/comments/package-use.html" target="_top">Frames</a></li>
<li><a href="package-use.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>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2002–2016 <a href="http://pmd.sourceforge.net/">InfoEther</a>. All rights reserved.</small></p>
</body>
</html>
| {
"content_hash": "9e8145a4978221e30164ba350096f202",
"timestamp": "",
"source": "github",
"line_count": 126,
"max_line_length": 153,
"avg_line_length": 35.96031746031746,
"alnum_prop": 0.6036195100419334,
"repo_name": "jasonwee/videoOnCloud",
"id": "18f48c7c1c27b6d3018eb1891867caf11a659a4f",
"size": "4531",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pmd/pmd-doc-5.5.1/pmd-java/testapidocs/net/sourceforge/pmd/lang/java/rule/comments/package-use.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "116270"
},
{
"name": "C",
"bytes": "2209717"
},
{
"name": "C++",
"bytes": "375267"
},
{
"name": "CSS",
"bytes": "1134648"
},
{
"name": "Dockerfile",
"bytes": "1656"
},
{
"name": "HTML",
"bytes": "306558398"
},
{
"name": "Java",
"bytes": "1465506"
},
{
"name": "JavaScript",
"bytes": "9028509"
},
{
"name": "Jupyter Notebook",
"bytes": "30907"
},
{
"name": "Less",
"bytes": "107003"
},
{
"name": "PHP",
"bytes": "856"
},
{
"name": "PowerShell",
"bytes": "77807"
},
{
"name": "Pug",
"bytes": "2968"
},
{
"name": "Python",
"bytes": "1001861"
},
{
"name": "R",
"bytes": "7390"
},
{
"name": "Roff",
"bytes": "3553"
},
{
"name": "Shell",
"bytes": "206191"
},
{
"name": "Thrift",
"bytes": "80564"
},
{
"name": "XSLT",
"bytes": "4740"
}
],
"symlink_target": ""
} |
require 'spec_helper'
describe Datagrid::Ordering do
let!(:third) { Entry.create!(:name => "cc")}
let!(:second) { Entry.create!(:name => "bb")}
let!(:first) { Entry.create!(:name => "aa")}
it "should support order" do
expect(test_report(:order => "name") do
scope do
Entry
end
column :name
end.assets).to eq([first, second, third])
end
it "should support desc order" do
expect(test_report(:order => "name", :descending => true) do
scope do
Entry
end
column :name
end.assets).to eq([third, second, first])
end
it "should raise error if ordered by not existing column" do
expect {
test_report(:order => :hello).assets
}.to raise_error(Datagrid::OrderUnsupported)
end
it "should raise error if ordered by column without order" do
expect do
test_report(:order => :category) do
filter(:category, :default, :order => false) do |value|
self
end
end.assets
end.to raise_error(Datagrid::OrderUnsupported)
end
it "should override default order" do
expect(test_report(:order => :name) do
scope { Entry.order("name desc")}
column(:name, :order => "name asc")
end.assets).to eq([first, second, third])
end
it "should support order given as block" do
expect(test_report(:order => :name) do
scope { Entry }
column(:name, :order => proc { order("name desc") })
end.assets).to eq([third, second, first])
end
it "should support reversing order given as block" do
expect(test_report(:order => :name, :descending => true) do
scope { Entry }
column(:name, :order => proc { order("name desc") })
end.assets).to eq([first, second, third])
end
it "should support order desc given as block" do
expect(test_report(:order => :name, :descending => true) do
scope { Entry }
column(:name, :order_desc => proc { order("name desc")})
end.assets).to eq([third, second, first])
end
it "should treat true order as default" do
expect(test_report(:order => :name) do
scope { Entry }
column(:name, :order => true)
end.assets).to eq([first, second, third])
end
it "should support order_by_value" do
report = test_report(:order => :the_name) do
scope {Entry}
column(:the_name, :order_by_value => true) do
name
end
end
expect(report.assets).to eq([first, second, third])
report.descending = true
expect(report.assets).to eq([third, second, first])
end
it "should support order_by_value as block" do
order = { :aa => 2, :bb => 3, :cc => 1}
report = test_report(:order => :the_name) do
scope {Entry}
column(:the_name, :order_by_value => proc{|model| order[model.name.to_sym]}) do
name
end
end
expect(report.assets).to eq([third, first, second])
report.descending = true
expect(report.assets).to eq([second, first, third])
end
it "should work correctly with inherited classes" do
class OrderInheritenceBase
include Datagrid
scope { Entry }
end
class OrderInheritenceChild < OrderInheritenceBase
column(:name)
end
grid = OrderInheritenceChild.new(order: 'name')
expect(grid.assets).to eq([first, second, third])
grid.descending = true
expect(grid.assets).to eq([third, second, first])
end
it "should support ordering by dynamic columns" do
report = test_report(:order => "name") do
scope {Entry}
dynamic do
column(:name)
end
end
expect(report.assets).to eq([first, second, third])
end
it "should support #ordered_by? method" do
report = test_report(:order => "name") do
scope {Entry}
column(:id)
column(:name)
end
expect(report).to be_ordered_by(:name)
expect(report).to be_ordered_by("name")
expect(report).to be_ordered_by(report.column_by_name(:name))
expect(report).to_not be_ordered_by(:id)
expect(report).to_not be_ordered_by("id")
expect(report).to_not be_ordered_by(report.column_by_name(:id))
end
end
| {
"content_hash": "9571483534ab73756f8e8fddc9fa19b8",
"timestamp": "",
"source": "github",
"line_count": 150,
"max_line_length": 85,
"avg_line_length": 27.493333333333332,
"alnum_prop": 0.6188166828322017,
"repo_name": "bogdan/datagrid",
"id": "8dea7969d7f1dc58bd07a54c0f05ead12dc43238",
"size": "4124",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "spec/datagrid/ordering_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2115"
},
{
"name": "HTML",
"bytes": "5967"
},
{
"name": "Ruby",
"bytes": "250262"
}
],
"symlink_target": ""
} |
"""Statistical metrics for Calibrator routines
"""
import numpy as np
from sklearn.metrics import r2_score
def filter_nan(s, o):
"""
this functions removed the data from simulated and observed data
wherever the observed data contains nan
this is used by all other functions, otherwise they will produce nan as
output
"""
data = np.array([s.flatten(), o.flatten()])
data = np.transpose(data)
data = data[~np.isnan(data).any(1)]
return data[:, 0], data[:, 1]
def percentage_deviation(s, o):
"""
Percent deviation
input:
s: simulated
o: observed
output:
percent deviation
"""
s, o = filter_nan(s, o)
return sum(sum(abs(s - o) / abs(o)))
def pc_bias(s, o):
"""
Percent Bias
input:
s: simulated
o: observed
output:
pc_bias: percent bias
"""
s, o = filter_nan(s, o)
return 100.0 * sum(s - o) / sum(o)
def apb(s, o):
"""
Absolute Percent Bias
input:
s: simulated
o: observed
output:
apb_bias: absolute percent bias
"""
s, o = filter_nan(s, o)
return 100.0 * sum(abs(s - o)) / sum(o)
def rmse(s, o):
"""
Root Mean Squared Error
input:
s: simulated
o: observed
output:
rmse: root mean squared error
"""
s, o = filter_nan(s, o)
return np.sqrt(np.mean((s - o)**2))
def norm_rmse(s, o):
"""
Normalized to stanard deviation Root Mean Squared Error
input:
s: simulated
o: observed
output:
nrmse: normalized root mean squared error: RMSE / mean or SD
"""
s, o = filter_nan(s, o)
return rmse(s, o) / np.std(o)
def mae(s, o):
"""
Mean Absolute Error
input:
s: simulated
o: observed
output:
maes: mean absolute error
"""
s, o = filter_nan(s, o)
return np.mean(abs(s - o))
def bias(s, o):
"""
Bias
input:
s: simulated
o: observed
output:
bias: bias
"""
s, o = filter_nan(s, o)
return np.mean(s - o)
def NS(s, o):
"""
Nash Sutcliffe efficiency coefficient (the same as r^2)
input:
s: simulated
o: observed
output:
ns: Nash Sutcliffe efficient coefficient
"""
s, o = filter_nan(s, o)
return 1 - sum((s - o)**2) / sum((o - np.mean(o))**2)
def likelihood(s, o, N=5):
"""
Likelihood
input:
s: simulated
o: observed
output:
L: likelihood
"""
s, o = filter_nan(s, o)
return np.exp(-N * sum((s - o)**2) / sum((o - np.mean(o))**2))
def correlation(s, o):
"""
correlation coefficient
input:
s: simulated
o: observed
output:
corr: correlation coefficient
"""
s, o = filter_nan(s, o)
if s.size == 0:
corr = np.NaN
else:
corr = np.corrcoef(o, s)[0, 1]
return corr
def index_agreement(s, o):
"""
index of agreement
input:
s: simulated
o: observed
output:
ia: index of agreement
"""
s, o = filter_nan(s, o)
ia = 1 - (np.sum((o - s)**2)) / (
np.sum((np.abs(s - np.mean(o)) + np.abs(o - np.mean(o)))**2))
return ia
def squared_error(s, o):
"""
squared error
input:
s: simulated
o: observed
output:
se: squared error
"""
s, o = filter_nan(s, o)
return sum((s - o)**2)
def coefficient_of_determination(s, o):
"""
coefficient of determination (r-squared)
input:
s: simulated
o: observed
output:
r2: coefficient of determination
"""
s, o = filter_nan(s, o)
o_mean = np.mean(o)
se = squared_error(s, o)
se_mean = squared_error(o, o_mean)
r2 = 1 - (se / se_mean)
return r2
def rsquared(s, o):
"""
coefficient of determination (r-squared)
using python sklern module
input:
s: simulated
o: observed
output:
r2: coefficient of determination
"""
s, o = filter_nan(s, o)
return r2_score(o, s)
| {
"content_hash": "21b6d0d03b8cfa8c26f043570b14593c",
"timestamp": "",
"source": "github",
"line_count": 212,
"max_line_length": 75,
"avg_line_length": 19.35377358490566,
"alnum_prop": 0.5303436509870826,
"repo_name": "biogeochemistry/PorousMediaLab",
"id": "10932ff3509f35456a50b8503dd54fdbe0777bd4",
"size": "4103",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "porousmedialab/metrics.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "101253"
},
{
"name": "Shell",
"bytes": "366"
}
],
"symlink_target": ""
} |
<?php
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/ads/googleads/v11/errors/change_status_error.proto
namespace Google\Ads\GoogleAds\V11\Errors\ChangeStatusErrorEnum;
use UnexpectedValueException;
/**
* Enum describing possible change status errors.
*
* Protobuf type <code>google.ads.googleads.v11.errors.ChangeStatusErrorEnum.ChangeStatusError</code>
*/
class ChangeStatusError
{
/**
* Enum unspecified.
*
* Generated from protobuf enum <code>UNSPECIFIED = 0;</code>
*/
const UNSPECIFIED = 0;
/**
* The received error code is not known in this version.
*
* Generated from protobuf enum <code>UNKNOWN = 1;</code>
*/
const UNKNOWN = 1;
/**
* The requested start date is too old.
*
* Generated from protobuf enum <code>START_DATE_TOO_OLD = 3;</code>
*/
const START_DATE_TOO_OLD = 3;
/**
* The change_status search request must specify a finite range filter
* on last_change_date_time.
*
* Generated from protobuf enum <code>CHANGE_DATE_RANGE_INFINITE = 4;</code>
*/
const CHANGE_DATE_RANGE_INFINITE = 4;
/**
* The change status search request has specified invalid date time filters
* that can never logically produce any valid results (for example, start
* time after end time).
*
* Generated from protobuf enum <code>CHANGE_DATE_RANGE_NEGATIVE = 5;</code>
*/
const CHANGE_DATE_RANGE_NEGATIVE = 5;
/**
* The change_status search request must specify a LIMIT.
*
* Generated from protobuf enum <code>LIMIT_NOT_SPECIFIED = 6;</code>
*/
const LIMIT_NOT_SPECIFIED = 6;
/**
* The LIMIT specified by change_status request should be less than or equal
* to 10K.
*
* Generated from protobuf enum <code>INVALID_LIMIT_CLAUSE = 7;</code>
*/
const INVALID_LIMIT_CLAUSE = 7;
private static $valueToName = [
self::UNSPECIFIED => 'UNSPECIFIED',
self::UNKNOWN => 'UNKNOWN',
self::START_DATE_TOO_OLD => 'START_DATE_TOO_OLD',
self::CHANGE_DATE_RANGE_INFINITE => 'CHANGE_DATE_RANGE_INFINITE',
self::CHANGE_DATE_RANGE_NEGATIVE => 'CHANGE_DATE_RANGE_NEGATIVE',
self::LIMIT_NOT_SPECIFIED => 'LIMIT_NOT_SPECIFIED',
self::INVALID_LIMIT_CLAUSE => 'INVALID_LIMIT_CLAUSE',
];
public static function name($value)
{
if (!isset(self::$valueToName[$value])) {
throw new UnexpectedValueException(sprintf(
'Enum %s has no name defined for value %s', __CLASS__, $value));
}
return self::$valueToName[$value];
}
public static function value($name)
{
$const = __CLASS__ . '::' . strtoupper($name);
if (!defined($const)) {
throw new UnexpectedValueException(sprintf(
'Enum %s has no value defined for name %s', __CLASS__, $name));
}
return constant($const);
}
}
// Adding a class alias for backwards compatibility with the previous class name.
class_alias(ChangeStatusError::class, \Google\Ads\GoogleAds\V11\Errors\ChangeStatusErrorEnum_ChangeStatusError::class);
| {
"content_hash": "907f46db60c52d106808439dfce50893",
"timestamp": "",
"source": "github",
"line_count": 96,
"max_line_length": 119,
"avg_line_length": 33.270833333333336,
"alnum_prop": 0.6343143393863494,
"repo_name": "googleads/google-ads-php",
"id": "30d2fb58ca5eea4b81cd57dab1638542fb315d3c",
"size": "3194",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "src/Google/Ads/GoogleAds/V11/Errors/ChangeStatusErrorEnum/ChangeStatusError.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "899"
},
{
"name": "PHP",
"bytes": "9952711"
},
{
"name": "Shell",
"bytes": "338"
}
],
"symlink_target": ""
} |
using namespace arangodb;
using namespace arangodb::aql;
using namespace arangodb::tests;
using namespace arangodb::tests::aql;
WaitingExecutionBlockMock::WaitingExecutionBlockMock(ExecutionEngine* engine,
ExecutionNode const* node,
std::deque<SharedAqlItemBlockPtr>&& data)
: ExecutionBlock(engine, node),
_data(std::move(data)),
_resourceMonitor(),
_inflight(0),
_hasWaited(false) {}
std::pair<arangodb::aql::ExecutionState, arangodb::Result> WaitingExecutionBlockMock::initializeCursor(
arangodb::aql::InputAqlItemRow const& input) {
if (!_hasWaited) {
_hasWaited = true;
return {ExecutionState::WAITING, TRI_ERROR_NO_ERROR};
}
_hasWaited = false;
_inflight = 0;
return {ExecutionState::DONE, TRI_ERROR_NO_ERROR};
}
std::pair<arangodb::aql::ExecutionState, Result> WaitingExecutionBlockMock::shutdown(int errorCode) {
ExecutionState state;
Result res;
return std::make_pair(state, res);
}
std::pair<arangodb::aql::ExecutionState, SharedAqlItemBlockPtr> WaitingExecutionBlockMock::getSome(size_t atMost) {
if (!_hasWaited) {
_hasWaited = true;
if (_returnedDone) {
return {ExecutionState::DONE, nullptr};
}
return {ExecutionState::WAITING, nullptr};
}
_hasWaited = false;
if (_data.empty()) {
_returnedDone = true;
return {ExecutionState::DONE, nullptr};
}
auto result = std::move(_data.front());
_data.pop_front();
if (_data.empty()) {
_returnedDone = true;
return {ExecutionState::DONE, std::move(result)};
} else {
return {ExecutionState::HASMORE, std::move(result)};
}
}
std::pair<arangodb::aql::ExecutionState, size_t> WaitingExecutionBlockMock::skipSome(size_t atMost) {
traceSkipSomeBegin(atMost);
if (!_hasWaited) {
_hasWaited = true;
traceSkipSomeEnd(ExecutionState::WAITING, 0);
return {ExecutionState::WAITING, 0};
}
_hasWaited = false;
if (_data.empty()) {
traceSkipSomeEnd(ExecutionState::DONE, 0);
return {ExecutionState::DONE, 0};
}
size_t skipped = _data.front()->size();
_data.pop_front();
if (_data.empty()) {
traceSkipSomeEnd(ExecutionState::DONE, skipped);
return {ExecutionState::DONE, skipped};
} else {
traceSkipSomeEnd(ExecutionState::HASMORE, skipped);
return {ExecutionState::HASMORE, skipped};
}
}
| {
"content_hash": "712d19e468f4700a157952fa2f4fdf35",
"timestamp": "",
"source": "github",
"line_count": 82,
"max_line_length": 115,
"avg_line_length": 29.51219512195122,
"alnum_prop": 0.6582644628099174,
"repo_name": "fceller/arangodb",
"id": "4706dd4f4d4825ecdaec897b83e27f873da63ef7",
"size": "3590",
"binary": false,
"copies": "1",
"ref": "refs/heads/devel",
"path": "tests/Aql/WaitingExecutionBlockMock.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Ada",
"bytes": "89080"
},
{
"name": "AppleScript",
"bytes": "1429"
},
{
"name": "Assembly",
"bytes": "142084"
},
{
"name": "Batchfile",
"bytes": "9073"
},
{
"name": "C",
"bytes": "1938354"
},
{
"name": "C#",
"bytes": "55625"
},
{
"name": "C++",
"bytes": "79379178"
},
{
"name": "CLIPS",
"bytes": "5291"
},
{
"name": "CMake",
"bytes": "109718"
},
{
"name": "CSS",
"bytes": "1341035"
},
{
"name": "CoffeeScript",
"bytes": "94"
},
{
"name": "DIGITAL Command Language",
"bytes": "27303"
},
{
"name": "Emacs Lisp",
"bytes": "15477"
},
{
"name": "Go",
"bytes": "1018005"
},
{
"name": "Groff",
"bytes": "263567"
},
{
"name": "HTML",
"bytes": "459886"
},
{
"name": "JavaScript",
"bytes": "55446690"
},
{
"name": "LLVM",
"bytes": "39361"
},
{
"name": "Lua",
"bytes": "16189"
},
{
"name": "Makefile",
"bytes": "178253"
},
{
"name": "Module Management System",
"bytes": "1545"
},
{
"name": "NSIS",
"bytes": "26909"
},
{
"name": "Objective-C",
"bytes": "4430"
},
{
"name": "Objective-C++",
"bytes": "1857"
},
{
"name": "Pascal",
"bytes": "145262"
},
{
"name": "Perl",
"bytes": "227308"
},
{
"name": "Protocol Buffer",
"bytes": "5837"
},
{
"name": "Python",
"bytes": "3563935"
},
{
"name": "Ruby",
"bytes": "1000962"
},
{
"name": "SAS",
"bytes": "1847"
},
{
"name": "Scheme",
"bytes": "19885"
},
{
"name": "Shell",
"bytes": "488846"
},
{
"name": "VimL",
"bytes": "4075"
},
{
"name": "Yacc",
"bytes": "36950"
}
],
"symlink_target": ""
} |
import * as vscode from 'vscode';
export function name(filename: string): Promise<string | undefined> {
return vscode.window.showInputBox({
placeHolder: 'Enter the new path for the duplicate.',
value: filename.split('.').map((el, i) => i === 0 ? `${el}-copy` : el).join('.')
}) as Promise<string | undefined>;
}
export function overwrite(filepath: string): Promise<vscode.MessageItem | undefined> {
const message = `The path **${filepath}** alredy exists. Do you want to overwrite the existing path?`;
const action = {
title: 'OK',
isCloseAffordance: false
};
return vscode.window.showWarningMessage(message, action) as Promise<vscode.MessageItem | undefined>;
}
| {
"content_hash": "76eb287a2e51d9da2b806cbdf3e7675e",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 103,
"avg_line_length": 37.77777777777778,
"alnum_prop": 0.7044117647058824,
"repo_name": "mrmlnc/vscode-duplicate",
"id": "2ec98ba4ed091dd6cd6e382ba23d8a6bddc9b6d2",
"size": "680",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/utils/prompt.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "TypeScript",
"bytes": "6487"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using Mono.Cecil;
using Mono.Cecil.Cil;
using ModClient.Attributes;
using ModClient.Methods;
namespace ModdingFramework.Patcher
{
class MainClass
{
private static readonly String DEFAULT_MODS_DIR = "Mods";
private static readonly BindingFlags ALL_INCLUSIVE_BINDING_FLAGS =
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.DeclaredOnly;
static void Main(string[] args)
{
IPatcher patcher;
// TODO: Check which mods have already been installed, only install new ones
// TODO: If this is the first time patching, backup the assembly in a "pristine" folder.
// TODO: Corollary to first: maintain list of mods and patches, add this to the assembly for later reading.
String targetAssembly = args.Length > 0 ? args[0] : @"Managed\Assembly-CSharp.dll";
String pristineLocation = targetAssembly.Replace(".dll", "-pristine.dll");
String outputLocation = targetAssembly;
if (File.Exists(pristineLocation))
{
Console.WriteLine("Found pristine DLL at {0}, using this as patching base.", pristineLocation);
targetAssembly = pristineLocation;
}
else
{
Console.WriteLine("Making backup of current {0} at {1}....", targetAssembly, pristineLocation);
File.Copy(targetAssembly, pristineLocation);
}
try
{
patcher = CecilPatcher.Create(targetAssembly);
}
catch (Exception e)
{
Console.WriteLine("Failed to read input assembly {0}: {1}", targetAssembly, e);
return;
}
IEnumerable<string> modDlls =
Directory.EnumerateFileSystemEntries(DEFAULT_MODS_DIR, "*.dll", SearchOption.AllDirectories);
foreach (String modDll in modDlls)
{
Assembly assembly;
try
{
// TODO: use reflection only context to avoid overhead of loading assembly transitive deps.
// Requires converting all GetCustomAttribute to CustomAttributeData.GetCustomAttributes.
assembly = Assembly.LoadFrom(modDll);
assembly.GetTypes();
}
catch (Exception exception)
{
Console.WriteLine("Exception while attempting to load assembly [{0}]", modDll);
Console.WriteLine(exception);
continue;
}
ModAttribute modAttr = Attribute.GetCustomAttribute(assembly, typeof(ModAttribute)) as ModAttribute;
if (modAttr == null)
{
Console.WriteLine("Assembly {0} had no Mod attribute", assembly);
return;
}
Console.WriteLine("Processing data for mod {0}:", modAttr.ToString());
ICollection<PatchDescriptor> patchesForMod = ProcessAssembly(assembly);
// TODO: Verify PatchDescriptors locally (make sure method signatures match)
// and globally (no conflicting patches).
// TODO: Populate dictionary of <String, Patches> or make a list of "ModDescriptor" objects.
foreach (var patch in patchesForMod)
{
Console.WriteLine(
"Adding patch for method {0} in type {1}.",
patch.patchAttribute.method,
patch.patchAttribute.type);
try
{
patcher.AddPatch(patch);
}
catch (Exception e)
{
Console.WriteLine("Failed to add patch! Exception: {0}", e);
}
}
}
using (var outputStream = new FileStream(outputLocation, FileMode.OpenOrCreate, FileAccess.Write))
{
patcher.WritePatchedAssembly(outputStream);
}
}
static ICollection<PatchDescriptor> ProcessAssembly(Assembly assembly)
{
var descriptors = new List<PatchDescriptor>();
foreach (Type type in assembly.GetTypes())
{
ProcessType(type, descriptors);
}
return descriptors;
}
static void ProcessModule(Module module, ICollection<PatchDescriptor> descriptors)
{
var allTypes = module.GetTypes();
foreach (var type in allTypes) { ProcessType(type, descriptors); }
}
static void ProcessType(Type type, ICollection<PatchDescriptor> descriptors)
{
var allMethods = type.GetMethods(ALL_INCLUSIVE_BINDING_FLAGS);
foreach (var method in allMethods)
{
PatchAttribute attr = Attribute.GetCustomAttribute(method, typeof(PatchAttribute)) as PatchAttribute;
if (attr != null)
{
descriptors.Add(new PatchDescriptor(method, attr));
}
}
}
}
}
| {
"content_hash": "d1019b750f48713aef5f3cbf6565025c",
"timestamp": "",
"source": "github",
"line_count": 136,
"max_line_length": 119,
"avg_line_length": 40.720588235294116,
"alnum_prop": 0.5455037919826652,
"repo_name": "msmith57/7dtd-mods",
"id": "8f4aad35b87a95c6b923932101c79beed1bf7de1",
"size": "5540",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ModdingFramework/ModdingFramework/Patcher/Main.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "33590"
}
],
"symlink_target": ""
} |
using VideoList.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
namespace VideoList.Controllers
{
public class VideosController : ApiController
{
// I know this isn't the best way to do this, but the local database is only
// temporary and will be replaced with a connection to a Firebase database
// In order to minimize the number of new things to learn at one time,
// I've temporarily added this class to pull data from SQLEXPRESS.
private const string _cStr = @"Data Source=localhost\SQLEXPRESS;Initial Catalog=OurMedia;Integrated Security=True";
[Route("api/getAllVideos")]
public string GetAllVideos()
{
using (var cnxn = new SqlConnection(_cStr))
{
cnxn.Open();
var cmd = new SqlCommand();
cmd.Connection = cnxn;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "spGetVideoList";
var reader = cmd.ExecuteReader();
var videos = new List<Video>();
while(reader.Read())
{
var newVideo = new Video();
newVideo.VideoId = reader.GetInt32(0);
newVideo.Title = reader.GetString(1);
newVideo.Format = reader.GetString(3);
newVideo.FormatId = reader.GetInt32(2);
newVideo.Genre = reader.GetString(5);
newVideo.GenreId = reader.GetInt32(4);
newVideo.Owner = reader.GetString(7);
newVideo.OwnerId = reader.GetInt32(6);
newVideo.YearReleased = reader.GetString(8);
videos.Add(newVideo);
}
var jss = new JavaScriptSerializer();
string output = jss.Serialize(videos);
return output;
}
}
[Route("api/getAllGenres")]
public string GetAllGenres()
{
using (var cnxn = new SqlConnection(_cStr))
{
cnxn.Open();
var cmd = new SqlCommand();
cmd.Connection = cnxn;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "spGetAllGenres";
var reader = cmd.ExecuteReader();
var genres = new List<Genre>();
while (reader.Read())
{
var newGenre = new Genre();
newGenre.Id = reader.GetInt32(0);
newGenre.Name = reader.GetString(1);
genres.Add(newGenre);
}
var jss = new JavaScriptSerializer();
string output = jss.Serialize(genres);
return output;
}
}
}
}
| {
"content_hash": "1bedfb986a7a9ce60dea1693b4b069eb",
"timestamp": "",
"source": "github",
"line_count": 87,
"max_line_length": 123,
"avg_line_length": 35.18390804597701,
"alnum_prop": 0.5311989545900032,
"repo_name": "irenesmith/psychic-palm-tree",
"id": "682f87e344691b3ec0dcc3bdd17792afe3b4aaa9",
"size": "3063",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "VideoList/Controllers/VideosController.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "103"
},
{
"name": "C#",
"bytes": "6188"
},
{
"name": "CSS",
"bytes": "55394"
},
{
"name": "HTML",
"bytes": "9781"
},
{
"name": "JavaScript",
"bytes": "1547584"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<TITLE>
com.google.template.soy.sharedpasses.render (Soy Complete)
</TITLE>
<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="com.google.template.soy.sharedpasses.render (Soy Complete)";
}
}
</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="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../com/google/template/soy/sharedpasses/opti/package-summary.html"><B>PREV PACKAGE</B></A>
<A HREF="../../../../../../com/google/template/soy/soyparse/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?com/google/template/soy/sharedpasses/render/package-summary.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-summary.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>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<H2>
Package com.google.template.soy.sharedpasses.render
</H2>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Interface Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../../com/google/template/soy/sharedpasses/render/EvalVisitor.EvalVisitorFactory.html" title="interface in com.google.template.soy.sharedpasses.render">EvalVisitor.EvalVisitorFactory</A></B></TD>
<TD>Interface for a factory that creates an EvalVisitor.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../../com/google/template/soy/sharedpasses/render/RenderVisitor.RenderVisitorFactory.html" title="interface in com.google.template.soy.sharedpasses.render">RenderVisitor.RenderVisitorFactory</A></B></TD>
<TD>Interface for a factory that creates an RenderVisitor.</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Class Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../../com/google/template/soy/sharedpasses/render/EvalVisitor.html" title="class in com.google.template.soy.sharedpasses.render">EvalVisitor</A></B></TD>
<TD>Visitor for evaluating the expression rooted at a given ExprNode.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../../com/google/template/soy/sharedpasses/render/EvalVisitorFactoryImpl.html" title="class in com.google.template.soy.sharedpasses.render">EvalVisitorFactoryImpl</A></B></TD>
<TD>Default implementation of EvalVisitorFactory.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../../com/google/template/soy/sharedpasses/render/RenderVisitor.html" title="class in com.google.template.soy.sharedpasses.render">RenderVisitor</A></B></TD>
<TD>Visitor for rendering the template subtree rooted at a given SoyNode.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../../com/google/template/soy/sharedpasses/render/RenderVisitorFactoryImpl.html" title="class in com.google.template.soy.sharedpasses.render">RenderVisitorFactoryImpl</A></B></TD>
<TD>Default implementation of RenderVisitorFactory.</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Exception Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../../com/google/template/soy/sharedpasses/render/RenderException.html" title="class in com.google.template.soy.sharedpasses.render">RenderException</A></B></TD>
<TD>Exception thrown when a rendering or evaluation attempt fails.</TD>
</TR>
</TABLE>
<P>
<DL>
</DL>
<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="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../com/google/template/soy/sharedpasses/opti/package-summary.html"><B>PREV PACKAGE</B></A>
<A HREF="../../../../../../com/google/template/soy/soyparse/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?com/google/template/soy/sharedpasses/render/package-summary.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-summary.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>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
<div id="footer">
<div id="footerlogo" style="float:left">
<img src="http://www.google.com/images/art.gif"
alt="Google colored balls">
</div>
<div id="copyright" style="float:left">
<p>
© 2009 Google -
<a href="http://www.google.com/privacy.html">Privacy Policy</a> -
<a href="http://www.google.com/terms_of_service.html">Terms and Conditions</a> -
<a href="http://www.google.com/about.html">About Google</a>
</p>
</div>
</div>
</BODY>
</HTML>
| {
"content_hash": "daa30d008b91859b1cde97a42dbbc86c",
"timestamp": "",
"source": "github",
"line_count": 214,
"max_line_length": 243,
"avg_line_length": 43.71028037383178,
"alnum_prop": 0.6281804575582638,
"repo_name": "lightbody/closure-templates",
"id": "4c2115810c3dd611803002ec6d36a35b8c97df60",
"size": "9354",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "javadoc-complete/com/google/template/soy/sharedpasses/render/package-summary.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "2502953"
},
{
"name": "JavaScript",
"bytes": "1015991"
}
],
"symlink_target": ""
} |
using System;
using DotNetNuke.Common;
using DotNetNuke.Entities.Tabs;
using DotNetNuke.Services.Localization;
using DotNetNuke.Common.Utilities;
using System.Globalization;
#endregion
namespace DotNetNuke.UI.Skins.Controls
{
/// -----------------------------------------------------------------------------
/// <summary></summary>
/// <returns></returns>
/// <remarks></remarks>
/// <history>
/// [cniknet] 10/15/2004 Replaced public members with properties and removed
/// brackets from property names
/// </history>
/// -----------------------------------------------------------------------------
public partial class BreadCrumb : SkinObjectBase
{
private const string MyFileName = "Breadcrumb.ascx";
public string Separator { get; set; }
public string CssClass { get; set; }
public string RootLevel { get; set; }
public bool UseTitle { get; set; }
public int ProfileUserId {
get {
var userId = Null.NullInteger;
if (!string.IsNullOrEmpty(Request.Params["UserId"])) {
if (!Int32.TryParse(Request.Params["UserId"], out userId)) userId = Null.NullInteger;
}
return userId;
}
}
public int GroupId {
get {
var groupId = Null.NullInteger;
if (!string.IsNullOrEmpty(Request.Params["GroupId"])) {
groupId = Int32.Parse(Request.Params["GroupId"]);
}
return groupId;
}
}
//do not show when there is no breadcrumb(only has current tab)
public bool HideWithNoBreadCrumb { get; set; }
private void InitializeComponent()
{
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
InitializeComponent();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (HideWithNoBreadCrumb && PortalSettings.ActiveTab.BreadCrumbs.Count == 1)
{
return;
}
//public attributes
string strSeparator;
if (!String.IsNullOrEmpty(Separator))
{
if (Separator.IndexOf("src=") != -1)
{
Separator = Separator.Replace("src=\"", "src=\"" + PortalSettings.ActiveTab.SkinPath);
}
strSeparator = Separator;
}
else
{
strSeparator = " <img alt=\"*\" src=\"" + Globals.ApplicationPath + "/images/breadcrumb.gif\"> ";
}
string strCssClass;
if (!String.IsNullOrEmpty(CssClass))
{
strCssClass = CssClass;
}
else
{
strCssClass = "SkinObject";
}
int intRootLevel;
if (!String.IsNullOrEmpty(RootLevel))
{
intRootLevel = int.Parse(RootLevel);
}
else
{
intRootLevel = 1;
}
string strBreadCrumbs = "";
if (intRootLevel == -1)
{
strBreadCrumbs += string.Format(Localization.GetString("Root", Localization.GetResourceFile(this, MyFileName)),
Globals.GetPortalDomainName(PortalSettings.PortalAlias.HTTPAlias, Request, true),
strCssClass);
strBreadCrumbs += strSeparator;
intRootLevel = 0;
}
//process bread crumbs
int intTab;
for (intTab = intRootLevel; intTab <= PortalSettings.ActiveTab.BreadCrumbs.Count - 1; intTab++)
{
if (intTab != intRootLevel)
{
strBreadCrumbs += strSeparator;
}
var objTab = (TabInfo) PortalSettings.ActiveTab.BreadCrumbs[intTab];
string strLabel = objTab.LocalizedTabName;
if (UseTitle && !String.IsNullOrEmpty(objTab.Title))
{
strLabel = objTab.Title;
}
var tabUrl = objTab.FullUrl;
if (ProfileUserId > -1) {
tabUrl = Globals.NavigateURL(objTab.TabID, "", "UserId=" + ProfileUserId.ToString(CultureInfo.InvariantCulture));
}
if (GroupId > -1) {
tabUrl = Globals.NavigateURL(objTab.TabID, "", "GroupId=" + GroupId.ToString(CultureInfo.InvariantCulture));
}
if (objTab.DisableLink)
{
strBreadCrumbs += "<span class=\"" + strCssClass + "\">" + strLabel + "</span>";
}
else
{
strBreadCrumbs += "<a href=\"" + tabUrl + "\" class=\"" + strCssClass + "\">" + strLabel + "</a>";
}
}
lblBreadCrumb.Text = strBreadCrumbs;
}
}
} | {
"content_hash": "3327d46a0d1e9f3a7f9fe5b10fe23611",
"timestamp": "",
"source": "github",
"line_count": 152,
"max_line_length": 133,
"avg_line_length": 34.203947368421055,
"alnum_prop": 0.4727832275437584,
"repo_name": "raphael-m/Dnn.Platform",
"id": "12ee54275af046eba47eeb758565dcd68bcb3f73",
"size": "6421",
"binary": false,
"copies": "2",
"ref": "refs/heads/development",
"path": "Website/admin/Skins/BreadCrumb.ascx.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "1325033"
},
{
"name": "Batchfile",
"bytes": "374"
},
{
"name": "C#",
"bytes": "20858229"
},
{
"name": "CSS",
"bytes": "1026642"
},
{
"name": "Erlang",
"bytes": "2168"
},
{
"name": "HTML",
"bytes": "628764"
},
{
"name": "JavaScript",
"bytes": "3820356"
},
{
"name": "PHP",
"bytes": "2199"
},
{
"name": "Smalltalk",
"bytes": "66184"
},
{
"name": "Visual Basic",
"bytes": "139461"
},
{
"name": "XSLT",
"bytes": "16560"
}
],
"symlink_target": ""
} |
//
// Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003
//
// Arjuna Technologies Ltd.,
// Newcastle upon Tyne,
// Tyne and Wear,
// UK.
//
package org.jboss.jbossts.qa.RawResources02Clients3;
/*
* Copyright (C) 1999-2001 by HP Bluestone Software, Inc. All rights Reserved.
*
* HP Arjuna Labs,
* Newcastle upon Tyne,
* Tyne and Wear,
* UK.
*
* $Id: Client013.java,v 1.3 2003/07/07 13:43:42 jcoleman Exp $
*/
/*
* Try to get around the differences between Ansi CPP and
* K&R cpp with concatenation.
*/
/*
* Copyright (C) 1999-2001 by HP Bluestone Software, Inc. All rights Reserved.
*
* HP Arjuna Labs,
* Newcastle upon Tyne,
* Tyne and Wear,
* UK.
*
* $Id: Client013.java,v 1.3 2003/07/07 13:43:42 jcoleman Exp $
*/
import org.jboss.jbossts.qa.RawResources02.*;
import org.jboss.jbossts.qa.Utils.OAInterface;
import org.jboss.jbossts.qa.Utils.ORBInterface;
import org.jboss.jbossts.qa.Utils.OTS;
import org.jboss.jbossts.qa.Utils.ServerIORStore;
import org.omg.CORBA.TRANSACTION_ROLLEDBACK;
public class Client013
{
public static void main(String[] args)
{
try
{
ORBInterface.initORB(args, null);
OAInterface.initOA();
String serviceIOR1 = ServerIORStore.loadIOR(args[args.length - 3]);
Service service1 = ServiceHelper.narrow(ORBInterface.orb().string_to_object(serviceIOR1));
String serviceIOR2 = ServerIORStore.loadIOR(args[args.length - 2]);
Service service2 = ServiceHelper.narrow(ORBInterface.orb().string_to_object(serviceIOR2));
String serviceIOR3 = ServerIORStore.loadIOR(args[args.length - 1]);
Service service3 = ServiceHelper.narrow(ORBInterface.orb().string_to_object(serviceIOR3));
ResourceBehavior[] resourceBehaviors1 = new ResourceBehavior[1];
resourceBehaviors1[0] = new ResourceBehavior();
resourceBehaviors1[0].prepare_behavior = PrepareBehavior.PrepareBehaviorReturnVoteCommit;
resourceBehaviors1[0].rollback_behavior = RollbackBehavior.RollbackBehaviorReturn;
resourceBehaviors1[0].commit_behavior = CommitBehavior.CommitBehaviorReturn;
resourceBehaviors1[0].commitonephase_behavior = CommitOnePhaseBehavior.CommitOnePhaseBehaviorReturn;
ResourceBehavior[] resourceBehaviors2 = new ResourceBehavior[1];
resourceBehaviors2[0] = new ResourceBehavior();
resourceBehaviors2[0].prepare_behavior = PrepareBehavior.PrepareBehaviorReturnVoteRollback;
resourceBehaviors2[0].rollback_behavior = RollbackBehavior.RollbackBehaviorReturn;
resourceBehaviors2[0].commit_behavior = CommitBehavior.CommitBehaviorReturn;
resourceBehaviors2[0].commitonephase_behavior = CommitOnePhaseBehavior.CommitOnePhaseBehaviorReturn;
ResourceBehavior[] resourceBehaviors3 = new ResourceBehavior[1];
resourceBehaviors3[0] = new ResourceBehavior();
resourceBehaviors3[0].prepare_behavior = PrepareBehavior.PrepareBehaviorReturnVoteRollback;
resourceBehaviors3[0].rollback_behavior = RollbackBehavior.RollbackBehaviorReturn;
resourceBehaviors3[0].commit_behavior = CommitBehavior.CommitBehaviorReturn;
resourceBehaviors3[0].commitonephase_behavior = CommitOnePhaseBehavior.CommitOnePhaseBehaviorReturn;
boolean correct = true;
OTS.current().begin();
service1.oper(resourceBehaviors1, OTS.current().get_control());
service2.oper(resourceBehaviors2, OTS.current().get_control());
service3.oper(resourceBehaviors3, OTS.current().get_control());
try
{
OTS.current().commit(true);
System.err.println("Commit succeeded when it shouldn't");
correct = false;
}
catch (TRANSACTION_ROLLEDBACK transactionRolledback)
{
}
correct = correct && service1.is_correct() && service2.is_correct() && service3.is_correct();
ResourceTrace resourceTrace1 = service1.get_resource_trace(0);
ResourceTrace resourceTrace2 = service2.get_resource_trace(0);
ResourceTrace resourceTrace3 = service3.get_resource_trace(0);
correct = correct && ((resourceTrace1 == ResourceTrace.ResourceTracePrepareRollback) || (resourceTrace1 == ResourceTrace.ResourceTraceRollback));
correct = correct && ((resourceTrace2 == ResourceTrace.ResourceTracePrepareRollback) || (resourceTrace2 == ResourceTrace.ResourceTraceRollback));
correct = correct && ((resourceTrace3 == ResourceTrace.ResourceTracePrepareRollback) || (resourceTrace3 == ResourceTrace.ResourceTraceRollback));
if (correct)
{
System.out.println("Passed");
}
else
{
System.out.println("Failed");
}
}
catch (Exception exception)
{
System.out.println("Failed");
System.err.println("Client013.main: " + exception);
exception.printStackTrace(System.err);
}
try
{
OAInterface.shutdownOA();
ORBInterface.shutdownORB();
}
catch (Exception exception)
{
System.err.println("Client013.main: " + exception);
exception.printStackTrace(System.err);
}
}
}
| {
"content_hash": "c3f3f23038d64e8f543b1ad86535c881",
"timestamp": "",
"source": "github",
"line_count": 144,
"max_line_length": 148,
"avg_line_length": 33.423611111111114,
"alnum_prop": 0.747974236442967,
"repo_name": "nmcl/wfswarm-example-arjuna-old",
"id": "35bbbe9c465ff49fc6105ffcf69a4c6a66a576e5",
"size": "5791",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "graalvm/transactions/fork/narayana/qa/tests/src/org/jboss/jbossts/qa/RawResources02Clients3/Client013.java",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "6903"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?><!--
Copyright 2015 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:propertyName="trimPathEnd"
android:duration="@integer/searchback_show_hide_circle_duration"
android:interpolator="@android:interpolator/fast_out_slow_in"
android:valueFrom="@fraction/searchback_circle_search_trim_end"
android:valueTo="@fraction/searchback_circle_back_trim_end"
tools:targetApi="lollipop" />
| {
"content_hash": "74ac36698802d90f32d2521d9e9786ff",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 74,
"avg_line_length": 45.333333333333336,
"alnum_prop": 0.7509191176470589,
"repo_name": "ykrank/S1-Next",
"id": "5110913770eb88c80cbeb03ffecb31e6e6340e10",
"size": "1088",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/res/animator/searchback_hide_circle.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "20430"
},
{
"name": "Java",
"bytes": "727072"
},
{
"name": "Kotlin",
"bytes": "850530"
}
],
"symlink_target": ""
} |
from test import *
MONGO_HOST = 'localhost'
| {
"content_hash": "0319dbb2b354c0ac3cbeae679d7d559d",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 24,
"avg_line_length": 15,
"alnum_prop": 0.7111111111111111,
"repo_name": "raccoongang/socraticqs2",
"id": "3d7ca2efd5a056c4596c4bee1a07be682669af7a",
"size": "61",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "mysite/mysite/settings/test_localhost.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "189600"
},
{
"name": "Dockerfile",
"bytes": "580"
},
{
"name": "Gherkin",
"bytes": "289"
},
{
"name": "HTML",
"bytes": "342788"
},
{
"name": "JavaScript",
"bytes": "133425"
},
{
"name": "Makefile",
"bytes": "2991"
},
{
"name": "Python",
"bytes": "1504025"
},
{
"name": "Shell",
"bytes": "1521"
}
],
"symlink_target": ""
} |
import { Component, Input, OnChanges } from '@angular/core';
import { TrackInfo } from './model/trackinfo';
import * as myGlobals from '../globals';
@Component({
selector: 'tnt-event-data',
templateUrl: './tnt-event-data.component.html',
styleUrls: ['./tnt-event-data.component.css']
})
export class TnTEventDataComponent implements OnChanges {
@Input('incomingTrackingInfo') incomingTrackingInfo: TrackInfo[];
@Input('bcEventVerified') bcEventVerified: boolean;
collectionSize = 0;
page = 1;
pageSize = 5;
selectedEvent = {};
eventsToDescribe: TrackInfo[] = [];
debug = myGlobals.debug;
constructor() { }
ngOnChanges() {
if (!this.incomingTrackingInfo.length) {
return;
}
this.selectedEvent = {};
this.eventsToDescribe = [];
}
get events(): TrackInfo[] {
const everyEvent = this.incomingTrackingInfo;
this.collectionSize = everyEvent.length;
return everyEvent.slice((this.page - 1) * this.pageSize, (this.page - 1) * this.pageSize + this.pageSize);
}
eventSelection(event: TrackInfo) {
this.eventsToDescribe = []; // reset on every button press
this.selectedEvent = event; // highlight the event
let selectedEventIndex = this.incomingTrackingInfo.findIndex(el => el.eventTime === event.eventTime);
if (this.debug) {
console.log('selectedEventIndex ', selectedEventIndex);
}
if (selectedEventIndex === (this.incomingTrackingInfo.length - 1)) {
if (this.debug) {
console.log('First ever event in the Tracking Chain! No previous Event happened!');
}
this.eventsToDescribe.push(event);
} else {
this.eventsToDescribe.push(this.incomingTrackingInfo[selectedEventIndex]); // push the selected Event
this.eventsToDescribe.push(this.incomingTrackingInfo[selectedEventIndex + 1]); // push the previously occured event
if (this.debug) {
console.log(this.eventsToDescribe);
}
}
}
}
| {
"content_hash": "6e8dad117d9b0548a1db98df76176e20",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 127,
"avg_line_length": 36.79661016949152,
"alnum_prop": 0.6126209120221097,
"repo_name": "nimble-platform/frontend-service",
"id": "97069606e38f3a434e7ec472958f45c076d71468",
"size": "2969",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/tnt/tnt-event-data.component.ts",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "135821"
},
{
"name": "Dockerfile",
"bytes": "369"
},
{
"name": "HTML",
"bytes": "1305632"
},
{
"name": "JavaScript",
"bytes": "8243"
},
{
"name": "Shell",
"bytes": "1721"
},
{
"name": "TypeScript",
"bytes": "2729038"
}
],
"symlink_target": ""
} |
var fs = require('fs-extra');
var http = require('http'); // http protocol
var https = require('https'); // https protocol
var Mongo = require('mongodb').MongoClient;
var express = require('express'); // web server
var expressValidator = require('express-validator');
var cookieParser = require('cookie-parser'); // parse cookies
var socketio = require('socket.io'); // websocket
var request = require('request'); // http trafficer
var bodyParser = require('body-parser'); // middleware
var Uber = require('node-uber'); // import uber api
var OAuth = require('oauth'); // oauth api
var Promise = require('bluebird');
var util = require('util');
var geocoder = require('geocoder');
var qs = require('qs'); // querystring parsing
var assert = require('assert');
var chai = require('chai'); // Node assertion library
var nock = require('nock'); // http isolated requests
var should = chai.should();
// web server
var app = express();
var route = express.Router(); // add support for express routing
app.use(cookieParser());
var server = http.Server(app);
var io = socketio(server);
// static file serving
app.use('/', express.static('../Client/'));
var credentials = {
key: fs.readFileSync('bin/key.pem'),
cert: fs.readFileSync('bin/cert.pem')
};
// body parsing ensures req.body property
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// error handling middleware
var errorHandler = function(err, req, res, next) {
if(err.status) {
res.status(err.status);
} else {
res.status(500);
}
res.render('error', { error : err });
next(err);
};
app.use(errorHandler);
io.on('connection', function(socket){
socket.on('chat message', function(msg){
console.log('message: ' + msg);
});
});
// logger that prevents circular object reference in javascript
var log = function(msg, obj) {
console.log('\n');
if(obj) {
try {
console.log(msg + JSON.stringify(obj));
} catch(err) {
var simpleObject = {};
for (var prop in obj ){
if (!obj.hasOwnProperty(prop)){
continue;
}
if (typeof(obj[prop]) == 'object'){
continue;
}
if (typeof(obj[prop]) == 'function'){
continue;
}
simpleObject[prop] = obj[prop];
}
console.log('circular-' + msg + JSON.stringify(simpleObject)); // returns cleaned up JSON
}
} else {
console.log(msg);
}
};
// secure web server
https.createServer(credentials, app).listen(3000);
// only redirect the home page. 403 forbid all others
http.createServer(function(req, res) {
log('catch a redirect from ' + req.headers.host + ' (is HSTS working?)');
log('redirect req = ', req);
log('redirect res = ', res);
if (req.headers.host + req.url === DOMAIN + '/') {
res.writeHead(301, { 'Location' : 'https://' + req.headers.host + req.url });
res.end();
} else {
res.writeHead(403);
res.end();
}
}).listen(8080);
log('TRNZT running on local.info');
var key = {
"client_id": "LJGpana69PX47lPLFP5PpIdySYT5CT-G",
"client_secret": "mgtzL4Ok7Ibyfb4ecvO-PpQhQJbgTLF3SC_vS8RN",
"server_token": "Drp9ApEpmWdRKUIsf3CS3RGCmvo-tTDRGzYV6BDv",
"redirect_uri": "https://local.info:3000/v1.2/callback",
"name": "TRNZT",
"language": "en_US", // optional, defaults to en_US
};
var uber = new Uber(key);
// uber instance for Sandbox mode
key.sandbox = true;
var uber_sandbox = new Uber(key);
// JSON path for reply files
jsonReplyPath = function(filename) {
return path.join(__dirname, '/replies/' + filename + '.json');
}
// Load JSON file from replies folder for assertions
jsonReply = function(path) {
return JSON.parse(fs.readFileSync(this.jsonReplyPath(path), 'utf8'));
}
/************************************
*****
***** Uber API Requests
*****
************************************/
// Authenticate uber login with scopes
app.get('/v1.2/login', function(request, response) {
var url = uber.getAuthorizeUrl(['profile', 'places', 'ride_widgets', 'request']);
response.redirect(url);
log(url);
// User can manually go to authorization @ https://login.uber.com/oauth/v2/authorize?client_id=LJGpana69PX47lPLFP5PpIdySYT5CT-G&response_type=code
});
// Redirect script to authorize uber profile with oAuth 2.0
app.get('/v1.2/callback', function(request, response) {
uber.authorizationAsync( {
authorization_code: request.query.code
})
.spread(function(access_token, refresh_token, authorizedScopes, tokenExpiration) {
// store the user id and associated access_token, refresh_token, scopes and token expiration date
request.access = access_token;
log('New access_token retrieved: ' + access_token);
log('... token allows access to scopes: ' + authorizedScopes);
log('... token is valid until: ' + tokenExpiration);
log('... after token expiration, re-authorize using refresh_token: ' + refresh_token);
var query = request.query;
return uber.products.getAllForLocationAsync(39.010969, -94.61509899999999);
})
.then(function(res) {
var namezString = getProdNamez(res);
var descriptionzString = getProdDescs(res);
log(res.products);
// redirect the user back to your actual app
response.redirect('../?access_token=' + request.access + '&product_names=' + namezString + '&product_descriptions=' + descriptionzString);
})
.error(function(err) {
console.error(err);
});
});
function getProdNamez(res) {
var arr = res.products;
var namez = '';
for(var i = 0; i < arr.length; i++) {
namez += arr[i].display_name + ',';
}
return namez;
}
function getProdDescs(res) {
var arr = res.products;
var descriptionz = '';
for(var i = 0; i < arr.length; i++) {
descriptionz += arr[i].description + ',';
}
return descriptionz;
}
// Request a ride on behalf of an uber user
app.get('/v1.2/requests', function(req, res) {
var options = {
url: 'https://sandbox-api.uber.com/v1.2/requests',
headers: {
"Content-Type": "application/json",
"Accept-Language": "en_US",
"Authorization": "Bearer KA.eyJ2ZXJzaW9uIjoyLCJpZCI6IlpXREJ3OVBWU2dpUTZyTThvU1dya3c9PSIsImV4cGlyZXNfYXQiOjE0OTYzMzQ0NzUsInBpcGVsaW5lX2tleV9pZCI6Ik1RPT0iLCJwaXBlbGluZV9pZCI6MX0.a9PV89iqwudoAdZRdFsc5oVKVBujLf9S1-xiI5sRUUI"
}
};
function createtherequest(err, res, body) {
uber.requests.createAsync({
"product_id": '33de8094-3dc4-4ca9-8f67-243275f57623',
"start_latitude": '38.9597897',
"start_longitude": '-94.60699369999999',
"end_latitude": '39.010969',
"end_longitude": '-94.61509899999999'
})
.then(function(res) {
log(res);
res.redirect('https://sandbox-api.uber.com/v1.2/requests');
})
.error(function(err) {
console.error(err);
});
};
//var query = url.parse(request.url, true).query;
request(options, createtherequest);
});
// Get an upfront fare before requesting a ride
app.get('/v1.2/estimates/price', function(request, response) {
//extract the query from the request URL
var query = request.query;
/*
res.set({
'Content-Type': 'application/json',
'Authorization': 'Token ' + uber.access_token,
'Accept-Language': 'en_US'
});
*/
//if no query params sent, respond with Bad Request
if (!query || !query.lat || !query.lng) {
response.sendStatus(400);
} else {
uber.estimates.getPriceForRouteAsync(38.9597897, -94.606994, 39.010969, -94.615098)
.then(function(res) {
log(res);
})
.error(function(err) {
console.error(err);
});
}
});
app.get('/v1.2/estimates/time', function(request, response) {
// extract the query from the request URL
var query = url.parse(request.url, true).query;
// if no query params sent, respond with Bad Request
if (!query || !query.lat || !query.lng) {
response.sendStatus(400);
} else {
uber.estimates.getETAForLocationAsync(end_latitude, end_longitude)
.then(function(res) {
response.json(res);
})
.error(function(err) {
console.error(err);
});
}
});
// Get profile information on user that authorized app
app.get('/v1.2/me', function(request, response) {
uber.user.getProfileAsync()
.then(function(res) {
log(res);
})
.error(function(err) {
console.error(err);
});
});
// Retrieve home and work address from user profile
app.get('/v1.2/places/{place_id}', function(request, response) {
uber.places.getHomeAsync()
.then(function(res) {
log(res);
})
.error(function(err) {
console.error(err);
});
uber.places.getWorkAsync()
.then(function(res) {
log(res);
})
.error(function(err) {
console.error(err);
});
});
/********** Posts ****************/
// Login token Create
app.post('https://local.info/:oauth/v2/:token', function(data) {
});
// Ride Request Create
app.post('https://local.info/v1.2/:requests', function(data) {
});
/************************************
*****
***** Exports for uber
*****
************************************/
exports.chai = chai;
exports.nock = nock;
exports.request = request;
exports.should = should;
exports.qs = qs;
exports.uber = uber;
exports.uber_sandbox = uber_sandbox;
exports.key = key;
exports.jsonReplyPath = jsonReplyPath;
exports.jsonReply = jsonReply;
| {
"content_hash": "adb23ed2afd1c6af0e5cf71daf6232aa",
"timestamp": "",
"source": "github",
"line_count": 337,
"max_line_length": 223,
"avg_line_length": 27.958456973293767,
"alnum_prop": 0.6308639354701762,
"repo_name": "4ked/TRNZT",
"id": "af5ab79d081c4a69c4041995778d148d4763105a",
"size": "9422",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Server/server.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "4757"
},
{
"name": "HTML",
"bytes": "6768"
},
{
"name": "JavaScript",
"bytes": "19198"
},
{
"name": "Shell",
"bytes": "4641"
}
],
"symlink_target": ""
} |
<?php
/**
* Subclass for representing a row from the 'author' table.
*
*
*
* @package lib.model
*/
class Author extends BaseAuthor
{
/**
* Initializes internal state of Author object.
* @see parent::__construct()
*/
public function __construct()
{
// Make sure that parent constructor is always invoked, since that
// is where any default values for this object are set.
parent::__construct();
}
public function __toString()
{
return $this->getName();
}
}
| {
"content_hash": "fb94a1b35a4b25a8437f826f6ed72e1c",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 68,
"avg_line_length": 18.75,
"alnum_prop": 0.6076190476190476,
"repo_name": "hybmg57/jobeet",
"id": "ac96be3d311b87731b73c612e35b84af471da02d",
"size": "525",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "lib/plugins/sfPropelPlugin/test/functional/fixtures/lib/model/Author.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "25098"
},
{
"name": "JavaScript",
"bytes": "4841"
},
{
"name": "PHP",
"bytes": "3609090"
},
{
"name": "Shell",
"bytes": "1960"
}
],
"symlink_target": ""
} |
#include "EqualityConditionNSL.hpp"
EqualityConditionNSL::EqualityConditionNSL(unsigned int size): NonSmoothLaw(size)
{}
EqualityConditionNSL::~EqualityConditionNSL()
{}
| {
"content_hash": "8423c0eb4207428559b9da01fd8f0bdb",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 81,
"avg_line_length": 17.5,
"alnum_prop": 0.8057142857142857,
"repo_name": "siconos/siconos",
"id": "b3634acb40b42a7ffd48a9d31ade8ebd31711546",
"size": "865",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "kernel/src/modelingTools/EqualityConditionNSL.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "34"
},
{
"name": "C",
"bytes": "4141675"
},
{
"name": "C++",
"bytes": "4400059"
},
{
"name": "CMake",
"bytes": "424764"
},
{
"name": "Dockerfile",
"bytes": "12024"
},
{
"name": "GAMS",
"bytes": "5614"
},
{
"name": "Nix",
"bytes": "3368"
},
{
"name": "Python",
"bytes": "890857"
},
{
"name": "SWIG",
"bytes": "149591"
},
{
"name": "Shell",
"bytes": "10735"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8" ?>
<class xmlns="http://xml.phpdox.net/src#" full="V8JsException" namespace="" name="V8JsException">
<extends name="Exception" full="Exception"/>
<member name="JsFileName" static="false" visibility="protected">
<default>null</default>
<docblock>
<description compact=""/>
</docblock>
</member>
<member name="JsLineNumber" static="false" visibility="protected">
<default>null</default>
<docblock>
<description compact=""/>
</docblock>
</member>
<member name="JsSourceLine" static="false" visibility="protected">
<default>null</default>
<docblock>
<description compact=""/>
</docblock>
</member>
<member name="JsTrace" static="false" visibility="protected">
<default>null</default>
<docblock>
<description compact=""/>
</docblock>
</member>
<member name="message" static="false" visibility="protected">
<default>null</default>
<docblock>
<description compact="The exception message"/>
<var type="string"/>
</docblock>
</member>
<member name="code" static="false" visibility="protected">
<default>null</default>
<docblock>
<description compact="The exception code"/>
<var type="int"/>
</docblock>
</member>
<member name="file" static="false" visibility="protected">
<default>null</default>
<docblock>
<description compact="The filename where the exception was created"/>
<var type="string"/>
</docblock>
</member>
<member name="line" static="false" visibility="protected">
<default>null</default>
<docblock>
<description compact="The line where the exception was created"/>
<var type="int"/>
</docblock>
</member>
<method name="getJsFileName" abstract="false" static="false" visibility="public" final="true">
<docblock>
<description compact="The getJsFileName purpose"/>
<return type="string"/>
</docblock>
</method>
<method name="getJsLineNumber" abstract="false" static="false" visibility="public" final="true">
<docblock>
<description compact="The getJsLineNumber purpose"/>
<return type="int"/>
</docblock>
</method>
<method name="getJsSourceLine" abstract="false" static="false" visibility="public" final="true">
<docblock>
<description compact="The getJsSourceLine purpose"/>
<return type="int"/>
</docblock>
</method>
<method name="getJsTrace" abstract="false" static="false" visibility="public" final="true">
<docblock>
<description compact="The getJsTrace purpose"/>
<return type="string"/>
</docblock>
</method>
<method name="getMessage" abstract="false" static="false" visibility="public" final="true">
<docblock>
<description compact=""/>
<return type="string"/>
</docblock>
</method>
<method name="getPrevious" abstract="false" static="false" visibility="public" final="true">
<docblock>
<description compact=""/>
<return type="Exception"/>
</docblock>
</method>
<method name="getCode" abstract="false" static="false" visibility="public" final="true">
<docblock>
<description compact=""/>
<return type="mixed"/>
</docblock>
</method>
<method name="getFile" abstract="false" static="false" visibility="public" final="true">
<docblock>
<description compact=""/>
<return type="string"/>
</docblock>
</method>
<method name="getLine" abstract="false" static="false" visibility="public" final="true">
<docblock>
<description compact=""/>
<return type="int"/>
</docblock>
</method>
<method name="getTrace" abstract="false" static="false" visibility="public" final="true">
<docblock>
<description compact=""/>
<return type="array"/>
</docblock>
</method>
<method name="getTraceAsString" abstract="false" static="false" visibility="public" final="true">
<docblock>
<description compact=""/>
<return type="string"/>
</docblock>
</method>
<method name="__toString" abstract="false" static="false" visibility="public" final="false">
<docblock>
<description compact=""/>
<return type="string"/>
</docblock>
</method>
<method name="__clone" abstract="false" static="false" final="true">
<docblock>
<description compact=""/>
<return type="void"/>
</docblock>
</method>
</class> | {
"content_hash": "fa71f2bad889d33cb49a5a04bc497577",
"timestamp": "",
"source": "github",
"line_count": 134,
"max_line_length": 99,
"avg_line_length": 33.007462686567166,
"alnum_prop": 0.6389328510061044,
"repo_name": "rxz135cc/yii2webApp",
"id": "2e4264df35d4313fa518a6f562bde377013dbf44",
"size": "4423",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "vendor/theseer/phpdox/dependencies/php/classes/V8JsException.xml",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "1026"
},
{
"name": "CSS",
"bytes": "375021"
},
{
"name": "HTML",
"bytes": "23331"
},
{
"name": "JavaScript",
"bytes": "137958"
},
{
"name": "PHP",
"bytes": "269507"
}
],
"symlink_target": ""
} |
FROM balenalib/artik520-debian:buster-run
ENV Logging__Console__FormatterName=Json
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
ca-certificates \
curl \
\
# .NET Core dependencies
libc6 \
libgcc1 \
libgssapi-krb5-2 \
libicu63 \
libssl1.1 \
libstdc++6 \
zlib1g \
&& rm -rf /var/lib/apt/lists/*
# Configure web servers to bind to port 80 when present
ENV ASPNETCORE_URLS=http://+:80 \
# Enable detection of running in a container
DOTNET_RUNNING_IN_CONTAINER=true
# Install .NET Core
ENV DOTNET_VERSION 6.0.0
RUN curl -SL --output dotnet.tar.gz "https://dotnetcli.blob.core.windows.net/dotnet/Runtime/$DOTNET_VERSION/dotnet-runtime-$DOTNET_VERSION-linux-arm.tar.gz" \
&& dotnet_sha512='575037f2e164deaf3bcdd82f7b3f2b5a5784547c5bad4070375c00373722265401b88a81695b919f92ca176f21c1bdf1716f8fce16ab3d301ae666daa8cae750' \
&& echo "$dotnet_sha512 dotnet.tar.gz" | sha512sum -c - \
&& mkdir -p /usr/share/dotnet \
&& tar -zxf dotnet.tar.gz -C /usr/share/dotnet \
&& rm dotnet.tar.gz \
&& ln -s /usr/share/dotnet/dotnet /usr/bin/dotnet
ENV ASPNETCORE_VERSION 6.0.0
RUN curl -SL --output aspnetcore.tar.gz "https://dotnetcli.blob.core.windows.net/dotnet/aspnetcore/Runtime/$ASPNETCORE_VERSION/aspnetcore-runtime-$ASPNETCORE_VERSION-linux-arm.tar.gz" \
&& aspnetcore_sha512='36be738bb40a0cadacd4531c3597a25fd45deb7c48090ffb61c79a5db7742a5b8e13051b06556e15e7e162e4a044795c0ca5e6da4db26b63b05c37b39e74e301' \
&& echo "$aspnetcore_sha512 aspnetcore.tar.gz" | sha512sum -c - \
&& mkdir -p /usr/share/dotnet \
&& tar -zxf aspnetcore.tar.gz -C /usr/share/dotnet ./shared/Microsoft.AspNetCore.App \
&& rm aspnetcore.tar.gz
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/44e597e40f2010cdde15b3ba1e397aea3a5c5271/scripts/assets/tests/test-stack@dotnet.sh" \
&& echo "Running test-stack@dotnet" \
&& chmod +x test-stack@dotnet.sh \
&& bash test-stack@dotnet.sh \
&& rm -rf test-stack@dotnet.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Debian Buster \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \ndotnet 6.0-aspnet \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh | {
"content_hash": "cd7255e16d54f5814bfeab5f21824262",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 679,
"avg_line_length": 54.172413793103445,
"alnum_prop": 0.7154678548695098,
"repo_name": "resin-io-library/base-images",
"id": "a9e18a00f8fa02a940f5c1da99a2327ed12ef00a",
"size": "3163",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "balena-base-images/dotnet/artik520/debian/buster/6.0-aspnet/run/Dockerfile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "71234697"
},
{
"name": "JavaScript",
"bytes": "13096"
},
{
"name": "Shell",
"bytes": "12051936"
},
{
"name": "Smarty",
"bytes": "59789"
}
],
"symlink_target": ""
} |
@extends('spark::layouts.app')
@section('scripts')
<script src="https://js.braintreegateway.com/v2/braintree.js"></script>
@endsection
@section('content')
<spark-register-braintree inline-template>
<div>
<div class="spark-screen container">
<!-- Common Register Form Contents -->
@include('spark::auth.register-common')
<!-- Billing Information -->
<div class="row" v-show="selectedPlan && selectedPlan.price > 0">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading"><i class="fa fa-btn fa-credit-card"></i>Billing</div>
<div class="panel-body">
<!-- Generic 500 Level Error Message / Stripe Threw Exception -->
<div class="alert alert-danger" v-if="registerForm.errors.has('form')">
We had trouble validating your card. It's possible your card provider is preventing
us from charging the card. Please contact your card provider or customer support.
</div>
<form class="form-horizontal" role="form">
<!-- Braintree Container -->
<div id="braintree-container" class="m-b-sm"></div>
<!-- Coupon Code -->
<div class="form-group" :class="{'has-error': registerForm.errors.has('coupon')}" v-if="query.coupon">
<label for="number" class="col-md-4 control-label">Coupon Code</label>
<div class="col-sm-6">
<input type="text" class="form-control" name="coupon" v-model="registerForm.coupon">
<span class="help-block" v-show="registerForm.errors.has('coupon')">
@{{ registerForm.errors.get('coupon') }}
</span>
</div>
</div>
<!-- Terms And Conditions -->
<div class="form-group" :class="{'has-error': registerForm.errors.has('terms')}">
<div class="col-sm-6 col-sm-offset-4">
<div class="checkbox">
<label>
<input type="checkbox" v-model="registerForm.terms">
I Accept The <a href="/terms" target="_blank">Terms Of Service</a>
<span class="help-block" v-show="registerForm.errors.has('terms')">
<strong>@{{ registerForm.errors.get('terms') }}</strong>
</span>
</label>
</div>
</div>
</div>
<!-- Register Button -->
<div class="form-group">
<div class="col-sm-6 col-sm-offset-4">
<button type="submit" class="btn btn-primary" :disabled="registerForm.busy">
<span v-if="registerForm.busy">
<i class="fa fa-btn fa-spinner fa-spin"></i>Registering
</span>
<span v-else>
<i class="fa fa-btn fa-check-circle"></i>Register
</span>
</button>
</div>
</div>
<hr>
</form>
</div>
</div>
</div>
</div>
</div>
<!-- Plan Features Modal -->
@include('spark::modals.plan-details')
</div>
</spark-register-braintree>
@endsection
| {
"content_hash": "18ed39a17053fa349cb4b11f2a250c62",
"timestamp": "",
"source": "github",
"line_count": 86,
"max_line_length": 134,
"avg_line_length": 52.08139534883721,
"alnum_prop": 0.3795490064746595,
"repo_name": "nikolayru011/spark",
"id": "0dcecb320e5024ecdab9b2e0b38767488b6b495f",
"size": "4479",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "project-name/resources/views/vendor/spark/auth/register-braintree.blade.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "553"
},
{
"name": "CSS",
"bytes": "11624"
},
{
"name": "HTML",
"bytes": "229287"
},
{
"name": "PHP",
"bytes": "515039"
},
{
"name": "Vue",
"bytes": "563"
}
],
"symlink_target": ""
} |
package main.java.GarageAssistantApp.RepositoriesPackage;
import main.java.GarageAssistantApp.EntityPackage.Account;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Created by Mati on 2016-11-05.
*/
@Repository
public interface AccountRepository extends CrudRepository<Account, Long> {
Account findByUsername(String username);
List<Account> findByEnabled(boolean enabled);
}
| {
"content_hash": "57b2cb1109b22b41891d8866a5009e8d",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 74,
"avg_line_length": 28.176470588235293,
"alnum_prop": 0.8100208768267223,
"repo_name": "mati29/GarageAssistant",
"id": "2ba2224b44593f8997704a0fdbe9d7070b2c4329",
"size": "479",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/GarageAssistantApp/RepositoriesPackage/AccountRepository.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "41661"
},
{
"name": "HTML",
"bytes": "360348"
},
{
"name": "Java",
"bytes": "151700"
}
],
"symlink_target": ""
} |
// Copyright (c) Dapplo and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Dapplo.Windows.Input.Enums;
using Dapplo.Windows.Input.Structs;
namespace Dapplo.Windows.Input.Keyboard;
/// <summary>
/// This is a utility class to help to generate input for mouse and keyboard
/// </summary>
public static class KeyboardInputGenerator
{
/// <summary>
/// Generate key down
/// </summary>
/// <param name="keycodes">VirtualKeyCodes for the key downs</param>
/// <returns>number of input events generated</returns>
public static uint KeyDown(params VirtualKeyCode[] keycodes)
{
var keyboardInputs = new KeyboardInput[keycodes.Length];
var index = 0;
foreach (var virtualKeyCode in keycodes)
{
keyboardInputs[index++] = KeyboardInput.ForKeyDown(virtualKeyCode);
}
return NativeInput.SendInput(Structs.Input.CreateKeyboardInputs(keyboardInputs));
}
/// <summary>
/// Generate a key combination press(es)
/// </summary>
/// <param name="keycodes">params VirtualKeyCodes</param>
public static uint KeyCombinationPress(params VirtualKeyCode[] keycodes)
{
var keyboardInputs = new KeyboardInput[keycodes.Length * 2];
var index = 0;
// all down
foreach (var virtualKeyCode in keycodes)
{
keyboardInputs[index++] = KeyboardInput.ForKeyDown(virtualKeyCode);
}
// all up
foreach (var virtualKeyCode in keycodes)
{
keyboardInputs[index++] = KeyboardInput.ForKeyUp(virtualKeyCode);
}
return NativeInput.SendInput(Structs.Input.CreateKeyboardInputs(keyboardInputs));
}
/// <summary>
/// Generate key press(es)
/// </summary>
/// <param name="keycodes">params VirtualKeyCodes</param>
public static uint KeyPresses(params VirtualKeyCode[] keycodes)
{
var keyboardInputs = new KeyboardInput[keycodes.Length * 2];
var index = 0;
foreach (var virtualKeyCode in keycodes)
{
keyboardInputs[index++] = KeyboardInput.ForKeyDown(virtualKeyCode);
keyboardInputs[index++] = KeyboardInput.ForKeyUp(virtualKeyCode);
}
return NativeInput.SendInput(Structs.Input.CreateKeyboardInputs(keyboardInputs));
}
/// <summary>
/// Generate key(s) up
/// </summary>
/// <param name="keycodes">VirtualKeyCodes for the keys to release</param>
/// <returns>number of input events generated</returns>
public static uint KeyUp(params VirtualKeyCode[] keycodes)
{
var keyboardInputs = new KeyboardInput[keycodes.Length];
var index = 0;
foreach (var virtualKeyCode in keycodes)
{
keyboardInputs[index++] = KeyboardInput.ForKeyUp(virtualKeyCode);
}
return NativeInput.SendInput(Structs.Input.CreateKeyboardInputs(keyboardInputs));
}
} | {
"content_hash": "fb7de08d74012db27e6a65a93ac8a170",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 101,
"avg_line_length": 36.46987951807229,
"alnum_prop": 0.6564255037991411,
"repo_name": "dapplo/Dapplo.Windows",
"id": "b8d994bae2d14a69efd1c32c64c16b260092cf7f",
"size": "3029",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Dapplo.Windows.Input/Keyboard/KeyboardInputGenerator.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "1458616"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace PollSystem.Web
{
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
} | {
"content_hash": "bfc3d860f67b7318308f45280c6e790c",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 60,
"avg_line_length": 18.529411764705884,
"alnum_prop": 0.6825396825396826,
"repo_name": "YaneYosifov/TelerikAcademy",
"id": "b7e08e96609a2a9b75f7c622c0a92d53717a4222",
"size": "317",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Quality Assurance/Part III/Practical Exam/PollSystem/PollSystem.Web/Login.aspx.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "104820"
},
{
"name": "Batchfile",
"bytes": "524"
},
{
"name": "C#",
"bytes": "1470931"
},
{
"name": "CSS",
"bytes": "83613"
},
{
"name": "CoffeeScript",
"bytes": "3700"
},
{
"name": "HTML",
"bytes": "271804"
},
{
"name": "JavaScript",
"bytes": "412546"
},
{
"name": "Python",
"bytes": "111725"
},
{
"name": "Smalltalk",
"bytes": "219384"
},
{
"name": "XSLT",
"bytes": "3327"
}
],
"symlink_target": ""
} |
package org.apache.ignite.internal.processors.query.h2.sql;
import java.util.*;
/**
* Query parameter.
*/
public class GridSqlParameter extends GridSqlElement implements GridSqlValue {
/** Index. */
private int idx;
/**
* @param idx Index.
*/
public GridSqlParameter(int idx) {
super(Collections.<GridSqlElement>emptyList());
this.idx = idx;
}
/** {@inheritDoc} */
@Override public String getSQL() {
return "?" + (idx + 1);
}
/**
* @return Index.
*/
public int index() {
return idx;
}
/**
* @param idx New index.
*/
public void index(int idx) {
this.idx = idx;
}
}
| {
"content_hash": "eb33f45f2746b3daa212d9921604c82a",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 78,
"avg_line_length": 17.121951219512194,
"alnum_prop": 0.5455840455840456,
"repo_name": "louishust/incubator-ignite",
"id": "fc716592cc4517fffea4ab9b8924f143fa9d7cdc",
"size": "1504",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sql/GridSqlParameter.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "34170"
},
{
"name": "C++",
"bytes": "28098"
},
{
"name": "CSS",
"bytes": "17517"
},
{
"name": "Groovy",
"bytes": "15102"
},
{
"name": "HTML",
"bytes": "4669"
},
{
"name": "Java",
"bytes": "18653931"
},
{
"name": "JavaScript",
"bytes": "1085"
},
{
"name": "PHP",
"bytes": "18527"
},
{
"name": "Scala",
"bytes": "728073"
},
{
"name": "Shell",
"bytes": "398112"
}
],
"symlink_target": ""
} |
package org.springframework.boot.actuate.autoconfigure.cloudfoundry;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;
import org.springframework.boot.actuate.autoconfigure.endpoint.EndpointWebMvcAutoConfiguration;
import org.springframework.boot.actuate.cloudfoundry.CloudFoundryEndpointHandlerMapping;
import org.springframework.boot.actuate.cloudfoundry.CloudFoundrySecurityInterceptor;
import org.springframework.boot.actuate.cloudfoundry.CloudFoundrySecurityService;
import org.springframework.boot.actuate.cloudfoundry.TokenValidator;
import org.springframework.boot.actuate.endpoint.mvc.MvcEndpoints;
import org.springframework.boot.actuate.endpoint.mvc.NamedMvcEndpoint;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnCloudPlatform;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.security.IgnoredRequestCustomizer;
import org.springframework.boot.cloud.CloudPlatform;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.servlet.HandlerInterceptor;
/**
* {@link EnableAutoConfiguration Auto-configuration} to expose actuator endpoints for
* cloud foundry to use.
*
* @author Madhura Bhave
* @since 2.0.0
*/
@Configuration
@ConditionalOnProperty(prefix = "management.cloudfoundry", name = "enabled", matchIfMissing = true)
@ConditionalOnBean(MvcEndpoints.class)
@AutoConfigureAfter(EndpointWebMvcAutoConfiguration.class)
@ConditionalOnCloudPlatform(CloudPlatform.CLOUD_FOUNDRY)
public class CloudFoundryActuatorAutoConfiguration {
@Bean
public CloudFoundryEndpointHandlerMapping cloudFoundryEndpointHandlerMapping(
MvcEndpoints mvcEndpoints, RestTemplateBuilder restTemplateBuilder,
Environment environment) {
Set<NamedMvcEndpoint> endpoints = new LinkedHashSet<>(
mvcEndpoints.getEndpoints(NamedMvcEndpoint.class));
HandlerInterceptor securityInterceptor = getSecurityInterceptor(
restTemplateBuilder, environment);
CorsConfiguration corsConfiguration = getCorsConfiguration();
CloudFoundryEndpointHandlerMapping mapping = new CloudFoundryEndpointHandlerMapping(
endpoints, corsConfiguration, securityInterceptor);
mapping.setPrefix("/cloudfoundryapplication");
return mapping;
}
private HandlerInterceptor getSecurityInterceptor(
RestTemplateBuilder restTemplateBuilder, Environment environment) {
CloudFoundrySecurityService cloudfoundrySecurityService = getCloudFoundrySecurityService(
restTemplateBuilder, environment);
TokenValidator tokenValidator = new TokenValidator(cloudfoundrySecurityService);
HandlerInterceptor securityInterceptor = new CloudFoundrySecurityInterceptor(
tokenValidator, cloudfoundrySecurityService,
environment.getProperty("vcap.application.application_id"));
return securityInterceptor;
}
private CloudFoundrySecurityService getCloudFoundrySecurityService(
RestTemplateBuilder restTemplateBuilder, Environment environment) {
String cloudControllerUrl = environment.getProperty("vcap.application.cf_api");
boolean skipSslValidation = environment.getProperty(
"management.cloudfoundry.skip-ssl-validation", Boolean.class, false);
return cloudControllerUrl == null ? null
: new CloudFoundrySecurityService(restTemplateBuilder, cloudControllerUrl,
skipSslValidation);
}
private CorsConfiguration getCorsConfiguration() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin(CorsConfiguration.ALL);
corsConfiguration.setAllowedMethods(
Arrays.asList(HttpMethod.GET.name(), HttpMethod.POST.name()));
corsConfiguration.setAllowedHeaders(
Arrays.asList("Authorization", "X-Cf-App-Instance", "Content-Type"));
return corsConfiguration;
}
/**
* Nested configuration for ignored requests if Spring Security is present.
*/
@ConditionalOnClass(WebSecurity.class)
static class CloudFoundryIgnoredRequestConfiguration {
@Bean
public IgnoredRequestCustomizer cloudFoundryIgnoredRequestCustomizer() {
return new CloudFoundryIgnoredRequestCustomizer();
}
private static class CloudFoundryIgnoredRequestCustomizer
implements IgnoredRequestCustomizer {
@Override
public void customize(WebSecurity.IgnoredRequestConfigurer configurer) {
configurer.requestMatchers(
new AntPathRequestMatcher("/cloudfoundryapplication/**"));
}
}
}
}
| {
"content_hash": "4e1f270f9e0df3020a7132398659610c",
"timestamp": "",
"source": "github",
"line_count": 118,
"max_line_length": 99,
"avg_line_length": 43.55084745762712,
"alnum_prop": 0.8375170266588831,
"repo_name": "bjornlindstrom/spring-boot",
"id": "2cc70cdce81ffa713df37d7281c0d14ef8dc1ffd",
"size": "5759",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryActuatorAutoConfiguration.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "6942"
},
{
"name": "CSS",
"bytes": "5769"
},
{
"name": "FreeMarker",
"bytes": "2134"
},
{
"name": "Groovy",
"bytes": "49512"
},
{
"name": "HTML",
"bytes": "69585"
},
{
"name": "Java",
"bytes": "11813740"
},
{
"name": "JavaScript",
"bytes": "37789"
},
{
"name": "Ruby",
"bytes": "1307"
},
{
"name": "Shell",
"bytes": "27326"
},
{
"name": "Smarty",
"bytes": "2885"
},
{
"name": "XSLT",
"bytes": "34105"
}
],
"symlink_target": ""
} |
import * as moment from 'moment';
import * as _ from 'lodash';
import { PickerColumn } from 'ionic-angular';
import { MultiPickerType, IMomentObject } from '../../../src/components/multi-picker/multi-picker-types';
export interface IMomentFakeObject extends IMomentObject {
fakeMinutes?: number,
fakeHours?: number
}
let defaultMomentResult = {
fakeMinutes: 36,
fakeHours: 7
};
class StubMultiPickerType extends MultiPickerType {
setColumns(val) {
this._columns = val
}
protected defaultMoment(pickerValue: string): IMomentFakeObject {
return defaultMomentResult
}
}
let stubType: StubMultiPickerType;
let columns: Array<PickerColumn>;
describe('MultiPickerType', () => {
beforeEach(()=> {
stubType = new StubMultiPickerType()
columns = [
{
name: 'fakeMinutes',
options: [{ text: '34', value: 34 }, { text: '35', value: 35 }, { text: '36', value: 36 }],
selectedIndex: 1
},
{
name: 'fakeHours',
options: [{ text: '05', value: 5 }, { text: '06', value: 6 }, { text: '07', value: 7 }],
selectedIndex: 0
}
]
});
describe('#columns', () => {
it('should return _columns', () => {
stubType.setColumns(columns);
expect(stubType.columns()).toBe(columns)
})
});
describe('#dealDoneVisibleBnt', () => {
beforeEach(()=> {
this.button = {}
});
it('should set empty string', () => {
stubType.dealDoneVisibleBnt(columns, this.button);
expect(this.button.cssRole).toEqual('')
});
it('should set hide if selected option of at least one column is disabled', () => {
columns[0].options[columns[0].selectedIndex].disabled = true;
stubType.dealDoneVisibleBnt(columns, this.button);
expect(this.button.cssRole).toEqual('hide')
})
});
describe('#setDefaultSelectedIndexes', () => {
it('should set indexes from defaultMoment when it is given', () => {
spyOn(stubType, 'defaultMoment').and.callThrough();
stubType.setDefaultSelectedIndexes(columns, '17');
expect(columns[0].selectedIndex).toEqual(2);
expect(columns[1].selectedIndex).toEqual(2);
expect(stubType['defaultMoment']).toHaveBeenCalledWith('17')
});
it('should set zeros when defaultMoment is NOT given', () => {
spyOn(stubType, 'defaultMoment').and.returnValue({});
stubType.setDefaultSelectedIndexes(columns, '17');
expect(columns[0].selectedIndex).toEqual(0);
expect(columns[1].selectedIndex).toEqual(0);
expect(stubType['defaultMoment']).toHaveBeenCalledWith('17')
})
});
describe('#currentMoment', () => {
it('should return defaultMoment when pickerValue is string', () => {
spyOn(stubType, 'defaultMoment').and.callThrough();
expect(stubType['currentMoment'](columns, '17')).toBe(defaultMomentResult);
expect(stubType['defaultMoment']).toHaveBeenCalledWith('17')
});
it('should return defaultMoment when pickerValue is moment', () => {
const _moment = moment();
spyOn(stubType, 'defaultMoment').and.callThrough();
expect(stubType['currentMoment'](columns, _moment)).toBe(defaultMomentResult);
expect(stubType['defaultMoment']).toHaveBeenCalledWith(_moment)
});
it('should be calculated from selected indexes', () => {
spyOn(stubType, 'defaultMoment').and.callThrough();
expect(stubType['currentMoment'](columns, null)).toEqual({fakeMinutes: 35, fakeHours: 5});
expect(stubType['defaultMoment']).toHaveBeenCalledTimes(0)
})
});
describe('#generateOptions', () => {
it('should call generateOptions for each column', () => {
_.each(columns, column => {
column['generateOptions'] = ()=>{};
spyOn(column, 'generateOptions').and.callThrough();
});
stubType.setColumns(columns);
stubType['generateOptions']();
_.each(columns, column => {
expect(column['generateOptions']).toHaveBeenCalledTimes(1)
})
})
});
describe('#disableInvalid', () => {
it('should compare filtered options and all options', () => {
let column = columns[0];
column['filter'] = ()=> {};
spyOn(column, 'filter').and.returnValue(_.map([column.options[0], column.options[2]], 'value'));
stubType.setColumns({fakeMinutes: column});
stubType['disableInvalid'](columns, 'fakeMinutes', 0, [1]);
expect(column.options[1].disabled).toBe(true);
expect(column['filter']).toHaveBeenCalledTimes(1)
})
})
});
| {
"content_hash": "8caba65bca0e7e11712b509d8c4081dd",
"timestamp": "",
"source": "github",
"line_count": 131,
"max_line_length": 105,
"avg_line_length": 34.42748091603053,
"alnum_prop": 0.6341463414634146,
"repo_name": "byzg/ion2-datetime-picker",
"id": "f6eb2193f0dafc7fefc6fadfc326479a2e9849aa",
"size": "4510",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "specs/components/multi-picker/multy-picker-types.spec.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4573"
},
{
"name": "HTML",
"bytes": "5986"
},
{
"name": "JavaScript",
"bytes": "18491"
},
{
"name": "TypeScript",
"bytes": "82076"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "bc12ce4b509aad90b19ba0f69285c1a2",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.23076923076923,
"alnum_prop": 0.6917293233082706,
"repo_name": "mdoering/backbone",
"id": "2b8a4a11f3f6dbed46c09ac2cb5f6050ad3569bf",
"size": "194",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Houlletia/Houlletia conspersa/ Syn. Jennyella conspersa/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
using System;
using NClang.Natives;
using System.Linq;
using System.Runtime.InteropServices;
using SystemLongLong = System.Int64;
using SystemULongLong = System.UInt64;
using CXString = NClang.ClangString;
namespace NClang
{
public class ClangComment
{
CXComment source;
internal ClangComment (CXComment source)
{
this.source = source;
}
// CommentASTIntrospection
public CommentKind Kind {
get { return LibClang.clang_Comment_getKind (source); }
}
public int ChildCount {
get { return (int) LibClang.clang_Comment_getNumChildren (source); }
}
public ClangComment GetChild (int index)
{
return new ClangComment (LibClang.clang_Comment_getChild (source, (uint) index));
}
public bool IsWhitespace {
get { return LibClang.clang_Comment_isWhitespace (source) != 0; }
}
public bool InlineContentCommentHasTrailingNewLine {
get { return LibClang.clang_InlineContentComment_hasTrailingNewline (source) != 0; }
}
public string TextCommentText {
get { return LibClang.clang_TextComment_getText (source).Unwrap (); }
}
public string InlineCommandName {
get { return LibClang.clang_InlineCommandComment_getCommandName (source).Unwrap (); }
}
public CommentInlineCommandRenderKind InlineCommandRenderKind {
get { return LibClang.clang_InlineCommandComment_getRenderKind (source); }
}
public int InlineCommandArgumentCunt {
get { return (int) LibClang.clang_InlineCommandComment_getNumArgs (source); }
}
public string GetInlineCommandArgument (int index)
{
return LibClang.clang_InlineCommandComment_getArgText (source, (uint) index).Unwrap ();
}
public string HtmlTagCommentTagName {
get { return LibClang.clang_HTMLTagComment_getTagName (source).Unwrap (); }
}
public bool HtmlStartTagIsSelfClosing {
get { return LibClang.clang_HTMLStartTagComment_isSelfClosing (source) != 0; }
}
public int HtmlStartTagAttributeCount {
get { return (int) LibClang.clang_HTMLStartTag_getNumAttrs (source); }
}
public string GetHtmlStartTagAttributeName (int index)
{
return LibClang.clang_HTMLStartTag_getAttrName (source, (uint) index).Unwrap ();
}
public string GetHtmlStartTagAttributeValue (int index)
{
return LibClang.clang_HTMLStartTag_getAttrValue (source, (uint) index).Unwrap ();
}
public string BlockCommandName {
get { return LibClang.clang_BlockCommandComment_getCommandName (source).Unwrap (); }
}
public int BlockCommandArgumentCount {
get { return (int) LibClang.clang_BlockCommandComment_getNumArgs (source); }
}
public string GetBlockCommandArgument (int index)
{
return LibClang.clang_BlockCommandComment_getArgText (source, (uint) index).Unwrap ();
}
public ClangComment BlockCommandParagrath {
get { return new ClangComment (LibClang.clang_BlockCommandComment_getParagraph (source)); }
}
public string ParameterCommandParameterName {
get { return LibClang.clang_ParamCommandComment_getParamName (source).Unwrap (); }
}
public bool ParameterCommandIsIndexValid {
get { return LibClang.clang_ParamCommandComment_isParamIndexValid (source) != 0; }
}
public int ParameterCommandParameterIndex {
get { return (int) LibClang.clang_ParamCommandComment_getParamIndex (source); }
}
public bool ParameterCommandIsDirectionExplicit {
get { return LibClang.clang_ParamCommandComment_isDirectionExplicit (source) != 0; }
}
public CommentParamPassDirection ParameterCommandDirection {
get { return LibClang.clang_ParamCommandComment_getDirection (source); }
}
public string TypeParameterCommandParameterName {
get { return LibClang.clang_TParamCommandComment_getParamName (source).Unwrap (); }
}
public bool TypeParameterCommandIsPositionValid {
get { return LibClang.clang_TParamCommandComment_isParamPositionValid (source) != 0; }
}
public int ParameterCommandDepth {
get { return (int) LibClang.clang_TParamCommandComment_getDepth (source); }
}
public int ParameterCommandGetIndex (int depth)
{
return (int) LibClang.clang_TParamCommandComment_getIndex (source, (uint) depth);
}
public string VerbatimBlockLineCommentText {
get { return LibClang.clang_VerbatimBlockLineComment_getText (source).Unwrap (); }
}
public string VerbatimLineCommentText {
get { return LibClang.clang_VerbatimLineComment_getText (source).Unwrap (); }
}
public string HtmlTagAsString {
get { return LibClang.clang_HTMLTagComment_getAsString (source).Unwrap (); }
}
public string FullCommentAsHtml {
get { return LibClang.clang_FullComment_getAsHTML (source).Unwrap (); }
}
public string FullCommentAsXml {
get { return LibClang.clang_FullComment_getAsXML (source).Unwrap (); }
}
}
}
| {
"content_hash": "978e8a4dc6ba9e6b4fe952139c8bbdd4",
"timestamp": "",
"source": "github",
"line_count": 163,
"max_line_length": 94,
"avg_line_length": 29.085889570552148,
"alnum_prop": 0.7466779160514659,
"repo_name": "atsushieno/nclang",
"id": "11e0ef898468c4ef27ab336613836b2027d6b6a0",
"size": "4741",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "NClang/LanguageService/ClangComment.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "286634"
}
],
"symlink_target": ""
} |
namespace LmpCommon.Message.Types
{
public enum LockMessageType
{
ListRequest = 0,
ListReply = 1,
Acquire = 2,
Release = 3
}
} | {
"content_hash": "cc2d57edc34c78e70467f206fc25a6b0",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 34,
"avg_line_length": 17.1,
"alnum_prop": 0.543859649122807,
"repo_name": "gavazquez/LunaMultiPlayer",
"id": "cf4d4dfa868440358bd3c20a81883e161a980f66",
"size": "173",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "LmpCommon/Message/Types/LockMessageType.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "3648"
},
{
"name": "C#",
"bytes": "2055657"
},
{
"name": "CSS",
"bytes": "1100"
},
{
"name": "HTML",
"bytes": "484"
},
{
"name": "JavaScript",
"bytes": "1252"
},
{
"name": "Smalltalk",
"bytes": "15844"
}
],
"symlink_target": ""
} |
id: RHEL-07-030523
status: implemented
tag: auditd
---
The tasks add a rule to auditd that logs each time a user manages the
configuration files for ``sudo``.
Deployers can opt-out of this change by setting an Ansible variable:
.. code-block:: yaml
security_rhel7_audit_sudo_config_changes: no
| {
"content_hash": "0ecde0d54df6df539e0173180ce6a964",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 69,
"avg_line_length": 23.23076923076923,
"alnum_prop": 0.7483443708609272,
"repo_name": "major/openstack-ansible-security",
"id": "1d2c32ffc2b9b11364e1a4a95f00413574200710",
"size": "306",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/metadata/rhel7/RHEL-07-030523.rst",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "13608"
},
{
"name": "Shell",
"bytes": "2134"
}
],
"symlink_target": ""
} |
from src.base.test_cases import TestCases
class SortCharByFreqTestCases(TestCases):
def __init__(self):
super(SortCharByFreqTestCases, self).__init__()
self.__add_test_case__('Test 1', 'tree', ['eetr', 'eert'])
self.__add_test_case__('Test 2', 'cccaaa', ['cccaaa', 'aaaccc'])
self.__add_test_case__('Test 3', 'Aabb', ['bbAa', 'bbaA'])
self.__add_test_case__('Test 4', 'eeeee', ['eeeee'])
| {
"content_hash": "8e15238db396ed95c2bad5496fae3286",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 72,
"avg_line_length": 39.54545454545455,
"alnum_prop": 0.5770114942528736,
"repo_name": "hychrisli/PyAlgorithms",
"id": "a300c5e6eed2eea909643e47a031632441615955",
"size": "435",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/tests/part2/q451_test_sort_char_by_freq.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "201747"
}
],
"symlink_target": ""
} |
<?php
namespace Craft;
class GuestEntriesEmailPlugin extends BasePlugin
{
//private $_customLinks;
public function init()
{
craft()->on('guestEntries.onSuccess', function(GuestEntriesEvent $event) {
// get entry object
$entryModel = $event->params['entry'];
$sectionId = $entryModel['attributes']['sectionId'];
$section = craft()->sections->getSectionById($sectionId);
$sectionHandle = $section['handle'];
// get settings
//$settings = $this->getSettings();
$settings = craft()->plugins->getPlugin('guestentriesemail')->getSettings();
$sendEmail = $settings['attributes']['sendEmail'][$sectionHandle];
$emailSubject = $settings['attributes']['emailSubject'][$sectionHandle] . ': ' . $entryModel['title'];
$emailAddresses = $settings['attributes']['emailAddresses'][$sectionHandle];
if ($sendEmail === '1') {
// setup sendto email addresses
$sendToEmails = array_map('trim', explode(',', $emailAddresses));
// assemble message
$message = "<p><b>$emailSubject</b></p>\n";
foreach ($entryModel->getFieldLayout()->getFields() as $fieldLayoutField) {
$field = $fieldLayoutField->getField();
$fieldValue = $entryModel->getFieldValue($field->handle);
if(gettype($fieldValue) == "string") {
// most fields
$message .= "<p><b>" . $field->name . ":</b> " . $fieldValue . "</p>\n";
}
else if(is_a($fieldValue, 'Craft\SingleOptionFieldData')) {
$message .= "<p><b>" . $field->name . ":</b> " . $fieldValue->label . "</p>\n";
}
else if(is_a($fieldValue, 'Craft\MultiOptionsFieldData')) {
$fieldContent = "";
foreach($fieldValue->getOptions() as $fieldValueItem) {
$fieldContent .= $fieldValueItem->label . ", ";
}
$fieldContent = rtrim($fieldContent, ", ");
$message .= "<p><b>" . $field->name . ":</b> " . $fieldContent . "</p>\n";
}
else if(gettype($fieldValue) == "array") {
// checkboxes, multi-selects
$fieldContent = "";
foreach($fieldValue as $fieldValueItem) {
$fieldContent .= $fieldValueItem . ", ";
}
$fieldContent = rtrim($fieldContent, ", ");
$message .= "<p><b>" . $field->name . ":</b> " . $fieldContent . "</p>\n";
}
else if ($field->type == "Assets") {
// assets
$fieldContent = " <br>";
foreach($fieldValue->find() as $asset) {
$fieldContent .= '<a href="' . $asset->getUrl() . '">' . $asset->getUrl() . '</a>,<br>';
}
$fieldContent = substr($fieldContent, 0, strlen($fieldContent) - 5);
$message .= "<p><b>" . $field->name . ":</b> " . $fieldContent . "</p>\n";
}
}
// debug plugin
/*
print('<pre style="color: white; white-space: pre;">');
var_dump($message);
print('</pre>');
$entryModel->addError('title', $message);
$event->isValid = false;
*/
// send email notification
if ($event->isValid == true) {
foreach ($sendToEmails as $value) {
$email = new EmailModel();
$email->toEmail = $value;
$email->subject = $emailSubject;
$email->htmlBody = $message;
$email->body = strip_tags($message);
craft()->email->sendEmail($email);
}
}
}
});
}
public function getName()
{
return Craft::t('Guest Entries Email Notification');
}
public function getVersion()
{
return '0.2.1';
}
public function getDeveloper()
{
return 'Sprokets Fork';
}
public function getDeveloperUrl()
{
return 'https://github.com/Sprokets/Craft-Guest-Entries-Email-Notification';
}
public function hasCpSection()
{
return false;
}
protected function defineSettings()
{
return array(
'emailAddresses' => AttributeType::Mixed,
'emailSubject' => AttributeType::Mixed,
'sendEmail' => AttributeType::Mixed,
);
}
public function getSettingsHtml()
{
$guestEntiresPlugin = craft()->plugins->getPlugin('guestentries', true);
if ($guestEntiresPlugin !== NULL) {
$guestEntiresPluginInstalled = true;
} else {
$guestEntiresPluginInstalled = false;
}
$editableSections = array();
$allSections = craft()->sections->getAllSections();
foreach ($allSections as $section)
{
// No sense in doing this for singles.
if ($section->type !== 'single')
{
$editableSections[$section->handle] = array('section' => $section);
}
}
// output settings template
return craft()->templates->render('guestentriesemail/settings', array(
'settings' => $this->getSettings(),
'editableSections' => $editableSections,
'guestEntiresPluginInstalled' => $guestEntiresPluginInstalled,
));
}
} | {
"content_hash": "c53a42c421315ae0ebf16ba4cac23c3e",
"timestamp": "",
"source": "github",
"line_count": 161,
"max_line_length": 108,
"avg_line_length": 31.52173913043478,
"alnum_prop": 0.5499507389162561,
"repo_name": "Sprokets/Craft-Guest-Entries-Email-Notification",
"id": "a46251797a6952cc587d981a7ad689834954b8f6",
"size": "5075",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "guestentriesemail/GuestEntriesEmailPlugin.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1590"
},
{
"name": "PHP",
"bytes": "5075"
}
],
"symlink_target": ""
} |
require 'pact_broker/domain/webhook_request'
module PactBroker
module Webhooks
class HttpRequestWithRedactedHeaders < SimpleDelegator
def to_hash
__getobj__().to_hash.each_with_object({}) do | (key, values), new_hash |
new_hash[key] = redact?(key) ? ["**********"] : values
end
end
def method
__getobj__().method
end
def redact? name
PactBroker::Domain::WebhookRequest::HEADERS_TO_REDACT.any?{ | pattern | name =~ pattern }
end
end
end
end
| {
"content_hash": "af99caee1c677348c8ffa9b711e3ffb0",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 97,
"avg_line_length": 25.38095238095238,
"alnum_prop": 0.5928705440900562,
"repo_name": "tancnle/pact_broker",
"id": "a6fd468aed167f4823be4f47bcda90098a930616",
"size": "533",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/pact_broker/webhooks/http_request_with_redacted_headers.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "12964"
},
{
"name": "Dockerfile",
"bytes": "471"
},
{
"name": "HTML",
"bytes": "33366"
},
{
"name": "JavaScript",
"bytes": "417327"
},
{
"name": "Ruby",
"bytes": "1538682"
},
{
"name": "Shell",
"bytes": "9413"
},
{
"name": "TSQL",
"bytes": "6998"
}
],
"symlink_target": ""
} |
// mitk includes
#include <mitkImage.h>
#include <mitkImageDataItem.h>
#include <mitkImageCast.h>
#include "mitkItkImageFileReader.h"
#include <mitkTestingMacros.h>
#include <mitkImageStatisticsHolder.h>
#include "mitkImageGenerator.h"
#include "mitkImageReadAccessor.h"
#include "mitkException.h"
// itk includes
#include <itkImage.h>
#include <itkMersenneTwisterRandomVariateGenerator.h>
// stl includes
#include <fstream>
// vtk includes
#include <vtkImageData.h>
// Checks if reference count is correct after using GetVtkImageData()
bool ImageVtkDataReferenceCheck(const char* fname) {
const std::string filename = std::string(fname);
mitk::ItkImageFileReader::Pointer imageReader = mitk::ItkImageFileReader::New();
try
{
imageReader->SetFileName(filename);
imageReader->Update();
}
catch(...) {
MITK_TEST_FAILED_MSG(<< "Could not read file for testing: " << filename);
return false;
}
{
mitk::Image::Pointer image = imageReader->GetOutput();
vtkImageData* vtk = image->GetVtkImageData();
if(vtk == NULL)
return false;
}
return true;
}
class mitkImageTestClass
{
public:
void SetClonedGeometry_None_ClonedEqualInput()
{
mitk::Image::Pointer image = mitk::ImageGenerator::GenerateRandomImage<float>(100, 100, 100, 1, 0.2, 0.3, 0.4);
//-----------------
// geometry information for image
mitk::Point3D origin;
mitk::Vector3D right, bottom;
mitk::Vector3D spacing;
mitk::FillVector3D(origin, 17.0, 19.92, 7.83);
mitk::FillVector3D(right, 1.0, 2.0, 3.0);
mitk::FillVector3D(bottom, 0.0, -3.0, 2.0);
mitk::FillVector3D(spacing, 0.78, 0.91, 2.23);
//InitializeStandardPlane(rightVector, downVector, spacing)
mitk::PlaneGeometry::Pointer planegeometry = mitk::PlaneGeometry::New();
planegeometry->InitializeStandardPlane(100, 100, right, bottom, &spacing);
planegeometry->SetOrigin(origin);
planegeometry->ChangeImageGeometryConsideringOriginOffset(true);
image->SetClonedGeometry(planegeometry);
mitk::Geometry3D::Pointer imageGeometry = image->GetGeometry();
itk::ScalableAffineTransform<mitk::ScalarType,3>* frameNew = imageGeometry->GetIndexToWorldTransform();
itk::ScalableAffineTransform<mitk::ScalarType,3>* frameOld = planegeometry->GetIndexToWorldTransform();
bool matrixEqual = true;
for (int i = 0; i < 16; ++i)
{
double valueNew = *(frameNew->GetMatrix()[i]);
double valueOld = *(frameOld->GetMatrix()[i]);
//MITK_INFO << "Index: " << i << " Old: " << valueOld << " New: " << valueNew << " Difference:" << valueOld-valueNew<< std::endl;
matrixEqual = matrixEqual && mitk::Equal(valueNew, valueOld, mitk::eps);
}
// Disabled because this test fails on the dashboard. Does not fail on my machine.
// See Bug 6505
// MITK_TEST_CONDITION(matrixEqual, "Matrix elements of cloned matrix equal original matrix");
}
};
int mitkImageTest(int argc, char* argv[])
{
MITK_TEST_BEGIN(mitkImageTest);
mitkImageTestClass tester;
tester.SetClonedGeometry_None_ClonedEqualInput();
//Create Image out of nowhere
mitk::Image::Pointer imgMem = mitk::Image::New();
mitk::PixelType pt = mitk::MakeScalarPixelType<int>();
unsigned int dim[]={100,100,20};
MITK_TEST_CONDITION_REQUIRED( imgMem.IsNotNull(), "An image was created. ");
// Initialize image
imgMem->Initialize( pt, 3, dim);
MITK_TEST_CONDITION_REQUIRED( imgMem->IsInitialized(), "Image::IsInitialized() ?");
MITK_TEST_CONDITION_REQUIRED( imgMem->GetPixelType() == pt, "PixelType was set correctly.");
int *p;
int *p2;
try
{
mitk::ImageReadAccessor imgMemAcc(imgMem);
p = (int*)imgMemAcc.GetData();
}
catch (mitk::Exception& e)
{
MITK_ERROR << e.what();
}
MITK_TEST_CONDITION( p != NULL, "GetData() returned not-NULL pointer.");
// filling image
const unsigned int size = dim[0]*dim[1]*dim[2];
for(unsigned int i=0; i<size; ++i, ++p)
*p = (signed int)i;
// Getting it again and compare with filled values:
try
{
mitk::ImageReadAccessor imgMemAcc(imgMem);
p2 = (int*)imgMemAcc.GetData();
}
catch (mitk::Exception &e)
{
MITK_ERROR << e.what();
}
MITK_TEST_CONDITION( p2 != NULL, "GetData() returned not-NULL pointer.");
bool isEqual = true;
for(unsigned int i=0; i<size; ++i, ++p2)
{
if(*p2 != (signed int) i )
{
isEqual = false;
}
}
MITK_TEST_CONDITION( isEqual, "The values previously set as data are correct [pixelwise comparison].");
// Testing GetSliceData() and compare with filled values:
try
{
mitk::ImageReadAccessor imgMemAcc(imgMem, imgMem->GetSliceData(dim[2]/2));
p2 = (int*)imgMemAcc.GetData();
}
catch (mitk::Exception& e)
{
MITK_ERROR << e.what();
}
MITK_TEST_CONDITION_REQUIRED( p2 != NULL, "Valid slice data returned");
unsigned int xy_size = dim[0]*dim[1];
unsigned int start_mid_slice = (dim[2]/2)*xy_size;
isEqual = true;
for(unsigned int i=0; i<xy_size; ++i, ++p2)
{
if(*p2!=(signed int)(i+start_mid_slice))
{
isEqual = false;
}
}
MITK_TEST_CONDITION( isEqual, "The SliceData are correct [pixelwise comparison]. ");
imgMem = mitk::Image::New();
// testing re-initialization of test image
mitk::PixelType pType = mitk::MakePixelType<int, int, 1>();
imgMem->Initialize( pType , 3, dim);
MITK_TEST_CONDITION_REQUIRED(imgMem->GetDimension()== 3, "Testing initialization parameter dimension!");
MITK_TEST_CONDITION_REQUIRED(imgMem->GetPixelType() == pType, "Testing initialization parameter pixeltype!");
MITK_TEST_CONDITION_REQUIRED(imgMem->GetDimension(0) == dim[0] &&
imgMem->GetDimension(1)== dim[1] && imgMem->GetDimension(2)== dim[2], "Testing initialization of dimensions!");
MITK_TEST_CONDITION( imgMem->IsInitialized(), "Image is initialized.");
// Setting volume again:
try
{
mitk::ImageReadAccessor imgMemAcc(imgMem);
imgMem->SetVolume(imgMemAcc.GetData());
}
catch (mitk::Exception& e)
{
MITK_ERROR << e.what();
}
//-----------------
// geometry information for image
mitk::Point3D origin;
mitk::Vector3D right, bottom;
mitk::Vector3D spacing;
mitk::FillVector3D(origin, 17.0, 19.92, 7.83);
mitk::FillVector3D(right, 1.0, 2.0, 3.0);
mitk::FillVector3D(bottom, 0.0, -3.0, 2.0);
mitk::FillVector3D(spacing, 0.78, 0.91, 2.23);
//InitializeStandardPlane(rightVector, downVector, spacing)
mitk::PlaneGeometry::Pointer planegeometry = mitk::PlaneGeometry::New();
planegeometry->InitializeStandardPlane(100, 100, right, bottom, &spacing);
planegeometry->SetOrigin(origin);
// Testing Initialize(const mitk::PixelType& type, const mitk::Geometry3D& geometry, unsigned int slices) with PlaneGeometry and GetData(): ";
imgMem->Initialize( mitk::MakePixelType<int, int, 1>(), *planegeometry);
MITK_TEST_CONDITION_REQUIRED( imgMem->GetGeometry()->GetOrigin() == static_cast<mitk::Geometry3D*>(planegeometry)->GetOrigin(), "Testing correct setting of geometry via initialize!");
try
{
mitk::ImageReadAccessor imgMemAcc(imgMem);
p = (int*)imgMemAcc.GetData();
}
catch (mitk::Exception& e)
{
MITK_ERROR << e.what();
}
MITK_TEST_CONDITION_REQUIRED( p!=NULL, "GetData() returned valid pointer.");
// Testing Initialize(const mitk::PixelType& type, int sDim, const mitk::PlaneGeometry& geometry) and GetData(): ";
imgMem->Initialize( mitk::MakePixelType<int, int, 1>() , 40, *planegeometry);
try
{
mitk::ImageReadAccessor imgMemAcc(imgMem);
p = (int*)imgMemAcc.GetData();
}
catch (mitk::Exception& e)
{
MITK_ERROR << e.what();
}
MITK_TEST_CONDITION_REQUIRED( p != NULL, "GetData() returned valid pointer.");
//-----------------
// testing origin information and methods
MITK_TEST_CONDITION_REQUIRED( mitk::Equal(imgMem->GetGeometry()->GetOrigin(), origin), "Testing correctness of origin via GetGeometry()->GetOrigin(): ");
MITK_TEST_CONDITION_REQUIRED( mitk::Equal(imgMem->GetTimeSlicedGeometry()->GetOrigin(), origin), "Testing correctness of origin via GetTimeSlicedGeometry()->GetOrigin(): ");
// Setting origin via SetOrigin(origin): ";
mitk::FillVector3D(origin, 37.0, 17.92, 27.83);
imgMem->SetOrigin(origin);
// Test origin
MITK_TEST_CONDITION_REQUIRED( mitk::Equal(imgMem->GetGeometry()->GetOrigin(), origin), "Testing correctness of changed origin via GetGeometry()->GetOrigin(): ");
MITK_TEST_CONDITION_REQUIRED( mitk::Equal(imgMem->GetTimeSlicedGeometry()->GetOrigin(), origin), "Testing correctness of changed origin via GetTimeSlicedGeometry()->GetOrigin(): ");
MITK_TEST_CONDITION_REQUIRED( mitk::Equal(imgMem->GetSlicedGeometry()->GetGeometry2D(0)->GetOrigin(), origin), "Testing correctness of changed origin via GetSlicedGeometry()->GetGeometry2D(0)->GetOrigin(): ");
//-----------------
// testing spacing information and methods
MITK_TEST_CONDITION_REQUIRED(mitk::Equal(imgMem->GetGeometry()->GetSpacing(), spacing), "Testing correct spacing from Geometry3D!");
MITK_TEST_CONDITION_REQUIRED(mitk::Equal(imgMem->GetTimeSlicedGeometry()->GetSpacing(), spacing), "Testing correctspacing from TimeSlicedGeometry!");
mitk::FillVector3D(spacing, 7.0, 0.92, 1.83);
imgMem->SetSpacing(spacing);
MITK_TEST_CONDITION_REQUIRED( mitk::Equal(imgMem->GetGeometry()->GetSpacing(), spacing), "Testing correctness of changed spacing via GetGeometry()->GetSpacing(): ");
MITK_TEST_CONDITION_REQUIRED( mitk::Equal(imgMem->GetTimeSlicedGeometry()->GetSpacing(), spacing), "Testing correctness of changed spacing via GetTimeSlicedGeometry()->GetSpacing(): ");
MITK_TEST_CONDITION_REQUIRED( mitk::Equal(imgMem->GetSlicedGeometry()->GetGeometry2D(0)->GetSpacing(), spacing), "Testing correctness of changed spacing via GetSlicedGeometry()->GetGeometry2D(0)->GetSpacing(): ");
mitk::Image::Pointer vecImg = mitk::Image::New();
try
{
mitk::ImageReadAccessor imgMemAcc(imgMem);
vecImg->Initialize( imgMem->GetPixelType(), *imgMem->GetGeometry(), 2 /* #channels */, 0 /*tDim*/ );
vecImg->SetImportChannel(const_cast<void*>(imgMemAcc.GetData()), 0, mitk::Image::CopyMemory );
vecImg->SetImportChannel(const_cast<void*>(imgMemAcc.GetData()), 1, mitk::Image::CopyMemory );
mitk::ImageReadAccessor vecImgAcc(vecImg);
mitk::ImageReadAccessor vecImgAcc0(vecImg, vecImg->GetChannelData(0));
mitk::ImageReadAccessor vecImgAcc1(vecImg, vecImg->GetChannelData(1));
MITK_TEST_CONDITION_REQUIRED(vecImgAcc0.GetData() != NULL && vecImgAcc1.GetData() != NULL, "Testing set and return of channel data!");
MITK_TEST_CONDITION_REQUIRED( vecImg->IsValidSlice(0,0,1) , "");
MITK_TEST_OUTPUT(<< " Testing whether CopyMemory worked");
MITK_TEST_CONDITION_REQUIRED(imgMemAcc.GetData() != vecImgAcc.GetData(), "");
MITK_TEST_OUTPUT(<< " Testing destruction after SetImportChannel");
vecImg = NULL;
MITK_TEST_CONDITION_REQUIRED(vecImg.IsNull() , "testing destruction!");
}
catch (mitk::Exception& e)
{
MITK_ERROR << e.what();
}
//-----------------
MITK_TEST_OUTPUT(<< "Testing initialization via vtkImageData");
MITK_TEST_OUTPUT(<< " Setting up vtkImageData");
vtkImageData* vtkimage = vtkImageData::New();
vtkimage->Initialize();
vtkimage->SetDimensions( 2, 3, 4);
double vtkorigin[] = {-350,-358.203, -1363.5};
vtkimage->SetOrigin(vtkorigin);
mitk::Point3D vtkoriginAsMitkPoint;
mitk::vtk2itk(vtkorigin, vtkoriginAsMitkPoint);
double vtkspacing[] = {1.367, 1.367, 2};
vtkimage->SetSpacing(vtkspacing);
vtkimage->SetScalarType( VTK_SHORT );
vtkimage->AllocateScalars();
std::cout<<"[PASSED]"<<std::endl;
MITK_TEST_OUTPUT(<< " Testing mitk::Image::Initialize(vtkImageData*, ...)");
mitk::Image::Pointer mitkByVtkImage = mitk::Image::New();
mitkByVtkImage ->Initialize(vtkimage);
MITK_TEST_CONDITION_REQUIRED(mitkByVtkImage->IsInitialized(), "");
vtkimage->Delete();
MITK_TEST_OUTPUT(<< " Testing whether spacing has been correctly initialized from vtkImageData");
mitk::Vector3D spacing2 = mitkByVtkImage->GetGeometry()->GetSpacing();
mitk::Vector3D vtkspacingAsMitkVector;
mitk::vtk2itk(vtkspacing, vtkspacingAsMitkVector);
MITK_TEST_CONDITION_REQUIRED(mitk::Equal(spacing2,vtkspacingAsMitkVector), "");
MITK_TEST_OUTPUT(<< " Testing whether GetSlicedGeometry(0)->GetOrigin() has been correctly initialized from vtkImageData");
mitk::Point3D origin2 = mitkByVtkImage->GetSlicedGeometry(0)->GetOrigin();
MITK_TEST_CONDITION_REQUIRED(mitk::Equal(origin2,vtkoriginAsMitkPoint), "");
MITK_TEST_OUTPUT(<< " Testing whether GetGeometry()->GetOrigin() has been correctly initialized from vtkImageData");
origin2 = mitkByVtkImage->GetGeometry()->GetOrigin();
MITK_TEST_CONDITION_REQUIRED(mitk::Equal(origin2,vtkoriginAsMitkPoint), "");
MITK_TEST_OUTPUT(<< " Testing whether GetTimeSlicedGeometry()->GetOrigin() has been correctly initialized from vtkImageData");
origin2 = mitkByVtkImage->GetTimeSlicedGeometry()->GetOrigin();
MITK_TEST_CONDITION_REQUIRED(mitk::Equal(origin2,vtkoriginAsMitkPoint), "");
// TODO test the following initializers on channel-incorporation
// void mitk::Image::Initialize(const mitk::PixelType& type, unsigned int dimension, unsigned int *dimensions, unsigned int channels)
// void mitk::Image::Initialize(const mitk::PixelType& type, int sDim, const mitk::Geometry2D& geometry2d, bool flipped, unsigned int channels, int tDim )
// void mitk::Image::Initialize(const mitk::Image* image)
// void mitk::Image::Initialize(const mitkIpPicDescriptor* pic, int channels, int tDim, int sDim)
//mitk::Image::Pointer vecImg = mitk::Image::New();
//vecImg->Initialize(PixelType(typeid(float), 6, itk::ImageIOBase::SYMMETRICSECONDRANKTENSOR), *imgMem->GetGeometry(), 2 /* #channels */, 0 /*tDim*/, false /*shiftBoundingBoxMinimumToZero*/ );
//vecImg->Initialize(PixelType(typeid(itk::Vector<float,6>)), *imgMem->GetGeometry(), 2 /* #channels */, 0 /*tDim*/, false /*shiftBoundingBoxMinimumToZero*/ );
// testing access by index coordinates and by world coordinates
MITK_TEST_CONDITION_REQUIRED(argc == 2, "Check if test image is accessible!");
const std::string filename = std::string(argv[1]);
mitk::ItkImageFileReader::Pointer imageReader = mitk::ItkImageFileReader::New();
try
{
imageReader->SetFileName(filename);
imageReader->Update();
}
catch(...) {
MITK_TEST_FAILED_MSG(<< "Could not read file for testing: " << filename);
return 0;
}
mitk::Image::Pointer image = imageReader->GetOutput();
// generate a random point in world coordinates
mitk::Point3D xMax, yMax, zMax, xMaxIndex, yMaxIndex, zMaxIndex;
xMaxIndex.Fill(0.0f);
yMaxIndex.Fill(0.0f);
zMaxIndex.Fill(0.0f);
xMaxIndex[0] = image->GetLargestPossibleRegion().GetSize()[0];
yMaxIndex[1] = image->GetLargestPossibleRegion().GetSize()[1];
zMaxIndex[2] = image->GetLargestPossibleRegion().GetSize()[2];
image->GetGeometry()->IndexToWorld(xMaxIndex, xMax);
image->GetGeometry()->IndexToWorld(yMaxIndex, yMax);
image->GetGeometry()->IndexToWorld(zMaxIndex, zMax);
MITK_INFO << "Origin " << image->GetGeometry()->GetOrigin()[0] << " "<< image->GetGeometry()->GetOrigin()[1] << " "<< image->GetGeometry()->GetOrigin()[2] << "";
MITK_INFO << "MaxExtend " << xMax[0] << " "<< yMax[1] << " "<< zMax[2] << "";
mitk::Point3D point;
itk::Statistics::MersenneTwisterRandomVariateGenerator::Pointer randomGenerator = itk::Statistics::MersenneTwisterRandomVariateGenerator::New();
randomGenerator->Initialize( std::rand() ); // initialize with random value, to get sensible random points for the image
point[0] = randomGenerator->GetUniformVariate( image->GetGeometry()->GetOrigin()[0], xMax[0]);
point[1] = randomGenerator->GetUniformVariate( image->GetGeometry()->GetOrigin()[1], yMax[1]);
point[2] = randomGenerator->GetUniformVariate( image->GetGeometry()->GetOrigin()[2], zMax[2]);
MITK_INFO << "RandomPoint " << point[0] << " "<< point[1] << " "<< point[2] << "";
// test values and max/min
mitk::ScalarType imageMin = image->GetStatistics()->GetScalarValueMin();
mitk::ScalarType imageMax = image->GetStatistics()->GetScalarValueMax();
mitk::ScalarType value = image->GetPixelValueByWorldCoordinate(point);
MITK_INFO << imageMin << " "<< imageMax << " "<< value << "";
MITK_TEST_CONDITION( (value >= imageMin && value <= imageMax), "Value returned is between max/min");
// test accessing PixelValue with coordinate leading to a negative index
const mitk::Point3D geom_origin = image->GetGeometry()->GetOrigin();
const mitk::Point3D geom_center = image->GetGeometry()->GetCenter();
const unsigned int timestep = 0;
// shift position from origin outside of the image ( in the opposite direction to [center-origin] vector which points in the inside)
mitk::Point3D position = geom_origin + (geom_origin - geom_center);
MITK_TEST_CONDITION_REQUIRED( image->GetPixelValueByWorldCoordinate(position, timestep) == 0, "Test access to the outside of the image")
// testing the clone method of mitk::Image
mitk::Image::Pointer cloneImage = image->Clone();
MITK_TEST_CONDITION_REQUIRED(cloneImage->GetDimension() == image->GetDimension(), "Clone (testing dimension)");
MITK_TEST_CONDITION_REQUIRED(cloneImage->GetPixelType() == image->GetPixelType(), "Clone (testing pixel type)");
// After cloning an image the geometry of both images should be equal too
MITK_TEST_CONDITION_REQUIRED(cloneImage->GetGeometry()->GetOrigin() == image->GetGeometry()->GetOrigin(), "Clone (testing origin)");
MITK_TEST_CONDITION_REQUIRED(cloneImage->GetGeometry()->GetSpacing() == image->GetGeometry()->GetSpacing(), "Clone (testing spacing)");
MITK_TEST_CONDITION_REQUIRED(mitk::MatrixEqualElementWise(cloneImage->GetGeometry()->GetIndexToWorldTransform()->GetMatrix(), image->GetGeometry()->GetIndexToWorldTransform()->GetMatrix()),
"Clone (testing transformation matrix)");
MITK_TEST_CONDITION_REQUIRED(mitk::MatrixEqualElementWise(cloneImage->GetTimeSlicedGeometry()->GetGeometry3D(cloneImage->GetDimension(3)-1)->GetIndexToWorldTransform()->GetMatrix(),
cloneImage->GetTimeSlicedGeometry()->GetGeometry3D(image->GetDimension(3)-1)->GetIndexToWorldTransform()->GetMatrix()), "Clone(testing time sliced geometry)");
for (unsigned int i = 0u; i < cloneImage->GetDimension(); ++i)
{
MITK_TEST_CONDITION_REQUIRED(cloneImage->GetDimension(i) == image->GetDimension(i), "Clone (testing dimension " << i << ")");
}
//access via itk
if(image->GetDimension()> 3) // CastToItk only works with 3d images so we need to check for 4d images
{
mitk::ImageTimeSelector::Pointer selector = mitk::ImageTimeSelector::New();
selector->SetTimeNr(0);
selector->SetInput(image);
selector->Update();
image = selector->GetOutput();
}
if(image->GetDimension()==3)
{
typedef itk::Image<float,3> ItkFloatImage3D;
ItkFloatImage3D::Pointer itkimage;
mitk::CastToItkImage(image, itkimage);
MITK_TEST_CONDITION_REQUIRED(itkimage.IsNotNull(), "Test conversion to itk::Image!");
mitk::Point3D itkPhysicalPoint;
image->GetGeometry()->WorldToItkPhysicalPoint(point, itkPhysicalPoint);
MITK_INFO << "ITKPoint " << itkPhysicalPoint[0] << " "<< itkPhysicalPoint[1] << " "<< itkPhysicalPoint[2] << "";
mitk::Point3D backTransformedPoint;
image->GetGeometry()->ItkPhysicalPointToWorld(itkPhysicalPoint, backTransformedPoint);
MITK_TEST_CONDITION_REQUIRED( mitk::Equal(point,backTransformedPoint), "Testing world->itk-physical->world consistency");
itk::Index<3> idx;
bool status = itkimage->TransformPhysicalPointToIndex(itkPhysicalPoint, idx);
MITK_INFO << "ITK Index " << idx[0] << " "<< idx[1] << " "<< idx[2] << "";
if(status)
{
float valByItk = itkimage->GetPixel(idx);
MITK_TEST_CONDITION_REQUIRED( mitk::Equal(valByItk, value), "Compare value of pixel returned by mitk in comparison to itk");
}
else
{
MITK_WARN<< "Index is out buffered region!";
}
}
else
{
MITK_INFO << "Image does not contain three dimensions, some test cases are skipped!";
}
// clone generated 3D image with one slice in z direction (cf. bug 11058)
unsigned int* threeDdim = new unsigned int[3];
threeDdim[0] = 100;
threeDdim[1] = 200;
threeDdim[2] = 1;
mitk::Image::Pointer threeDImage = mitk::Image::New();
threeDImage->Initialize(mitk::MakeScalarPixelType<float>(), 3, threeDdim);
mitk::Image::Pointer cloneThreeDImage = threeDImage->Clone();
// check that the clone image has the same dimensionality as the source image
MITK_TEST_CONDITION_REQUIRED( cloneThreeDImage->GetDimension() == 3, "Testing if the clone image initializes with 3D!");
MITK_TEST_CONDITION_REQUIRED( ImageVtkDataReferenceCheck(argv[1]), "Checking reference count of Image after using GetVtkImageData()");
MITK_TEST_END();
}
| {
"content_hash": "8bc96ae09e5aa3ab7ace981655038765",
"timestamp": "",
"source": "github",
"line_count": 483,
"max_line_length": 216,
"avg_line_length": 43.29606625258799,
"alnum_prop": 0.6996939556235654,
"repo_name": "nocnokneo/MITK",
"id": "5e6f003e50eaebebebfc8e22aecfc580c838e221",
"size": "21410",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Core/Code/Testing/mitkImageTest.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "5991982"
},
{
"name": "C++",
"bytes": "29934042"
},
{
"name": "CSS",
"bytes": "52056"
},
{
"name": "IDL",
"bytes": "5583"
},
{
"name": "Java",
"bytes": "350330"
},
{
"name": "JavaScript",
"bytes": "287054"
},
{
"name": "Objective-C",
"bytes": "606620"
},
{
"name": "Perl",
"bytes": "982"
},
{
"name": "Python",
"bytes": "7545"
},
{
"name": "Shell",
"bytes": "5438"
},
{
"name": "TeX",
"bytes": "1204"
},
{
"name": "XSLT",
"bytes": "30684"
}
],
"symlink_target": ""
} |
<?php
namespace UserBundle\Forms;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\OptionsResolver\OptionsResolver;
class RegisterFormType extends AbstractType
{
public function getName()
{
return 'user_register';
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('username', TextType::class)
// ->add('email', EmailType::class)
->add('password', RepeatedType::class, array(
'type' => PasswordType::class
));
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'UserBundle\Entity\User',
));
}
} | {
"content_hash": "4b8164a8f8f449d0d6217728ecea64f5",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 76,
"avg_line_length": 28.61111111111111,
"alnum_prop": 0.6883495145631068,
"repo_name": "inoGiot/ino",
"id": "2dff3d3cf7f394f37762cf5ea5b4bfbc9704ac2b",
"size": "1030",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/UserBundle/Forms/RegisterFormType.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "3605"
},
{
"name": "HTML",
"bytes": "12806"
},
{
"name": "PHP",
"bytes": "68962"
}
],
"symlink_target": ""
} |
#pragma once
#include "../system.h"
#include "../Template/Common.h"
#include "../memory/MemoryOps.h"
#include "../memory/Pointer.h"
namespace Everest
{
template <class _Tree>
class TreeIterator
{
//typedefs
typedef TreeIterator<_Tree> _MyT;
typedef typename _Tree::ValueType ValueType;
typedef typename _Tree::NodePointer NodePointer;
public:
TreeIterator(NodePointer node, _Tree* tree) : _myNode(node), _tree(tree)
{}
ValueType& operator* ()
{
return _myNode->_value;
}
ValueType* operator-> ()
{
return &_myNode->_value;
}
_MyT& operator++ ()
{
NodePointer succ = _tree->Successor(_myNode);
if (!succ.IsNull() || !_tree->IsNil(succ))
{
_myNode = succ;
return *this;
}
else
{
while (!_tree->IsNil(_myNode->_parent))
{
auto comp = _tree->Traits().Compare(
_tree->Traits().KeyOf(_myNode->_value), _tree->Traits().KeyOf(_myNode->_parent->_value));
if (comp >= 0)
{
_myNode = _myNode->_parent;
return *this;
}
}
}
_myNode = _tree->Nil();
return *this;
}
_MyT& operator++ (int)
{
_MyT _Tmp = *this;
++*this;
return _Tmp;
}
_MyT& operator-- ()
{
if (_tree->IsNil(_myNode)) // End
{
_myNode = _tree->Max(_tree->Root());
return *this;
}
NodePointer pred = _tree->Predecessor(_myNode);
if (!pred.IsNull() || !_tree->IsNil(pred))
{
_myNode = pred;
}
else if (!_tree->IsNil(_myNode->_left))
{
_myNode = _myNode->_left;
}
return *this;
}
_MyT& operator-- (int)
{
_MyT _Tmp = *this;
--*this;
return _Tmp;
}
bool operator== (const _MyT& other)
{
return _myNode == other._myNode;
}
bool operator!= (const _MyT& other)
{
return !(*this == other);
}
NodePointer MyNode()
{
return _myNode;
}
const NodePointer MyNode() const
{
return _myNode;
}
private:
NodePointer _myNode;
_Tree* _tree;
};
template <class _Tree>
class TreeReverseIterator
{
//typedefs
typedef TreeReverseIterator<_Tree> _MyT;
typedef typename _Tree::ValueType ValueType;
typedef typename _Tree::NodePointer NodePointer;
public:
TreeReverseIterator(NodePointer node, _Tree* tree) : _myNode(node), _tree(tree)
{}
ValueType& operator* () const
{
return _myNode->_value;
}
ValueType* operator-> () const
{
return &_myNode->_value;
}
_MyT& operator++ ()
{
NodePointer pred = _tree->Predecessor(_myNode);
if (!pred.IsNull() || !_tree->IsNil(pred))
{
_myNode = pred;
}
else if (!_tree->IsNil(_myNode->_left))
{
_myNode = _myNode->_left;
}
else
{
_myNode = _tree->Nil();
}
return *this;
}
_MyT& operator++ (int)
{
_MyT _Tmp = *this;
++*this;
return _Tmp;
}
_MyT& operator-- ()
{
NodePointer succ = _tree->Successor(_myNode);
if (!succ.IsNull() || !_tree->IsNil(succ))
{
_myNode = succ;
return *this;
}
else
{
while (!_tree->IsNil(_myNode->_parent))
{
auto comp = _tree->Traits().Compare(
_tree->Traits().KeyOf(_myNode->_value), _tree->Traits().KeyOf(_myNode->_parent->_value));
if (comp >= 0)
{
_myNode = _myNode->_parent;
return *this;
}
}
}
_myNode = _tree->Nil();
return *this;
}
_MyT& operator-- (int)
{
_MyT _Tmp = *this;
--*this;
return _Tmp;
}
bool operator== (const _MyT& other)
{
return _myNode == other._myNode;
}
bool operator!= (const _MyT& other)
{
return !(*this == other);
}
NodePointer MyNode()
{
return _myNode;
}
const NodePointer MyNode() const
{
return _myNode;
}
private:
NodePointer _myNode;
_Tree* _tree;
};
// Red-Black tree node
template< class ValueType, class Parser >
struct Node_RB
{
typedef typename Node_RB<ValueType, Parser> type;
typedef typename NodePointer<Parser, type> Pointer;
Pointer _parent; // This node parent
Pointer _right; // The left node, larger
Pointer _left; // The right node, smaller
ValueType _value; // The node's element value
uint8 _color; // Red or black node color
//uint8 _isNil; // True if the node is null or leaf node
};
// Red black tree
template <class _Traits, class AllocatorType>
class Tree
{
public:
// Red-Black tree colors
enum RB_TREE_COLORS
{
TREE_COLOR_RED = 48,
TREE_COLOR_BLACK = 49
};
// Typedefs
typedef typename _Traits::ValueType ValueType;
typedef typename _Traits::KeyType KeyType;
typedef typename _Traits::Value Value;
typedef typename AllocatorType::Parser Parser;
typedef typename Node_RB<ValueType, Parser> Node;
typedef typename AllocatorType::template Rebind<Node>::Other Allocator;
typedef typename Node::Pointer NodePointer;
typedef Tree<_Traits, Allocator> _MyT;
typedef TreeIterator<Tree<_Traits, AllocatorType>> iterator;
typedef TreeReverseIterator<_MyT> reverse_iterator;
// Find results defs
typedef Pair<bool, iterator> Result;
typedef Pair<bool, reverse_iterator> rResult;
enum NIL_VAL
{
_TRUE = 49, _FALSE = 48
};
// Pair of node pointer & value position for search results
//typedef Pair<NodePointer, int32> Result;
Tree() = delete;
Tree(Allocator alloc) :
allocator(alloc),
_size(0)
{
_Init();
}
// Construct with other map
Tree(const _MyT& other) :
allocator(other.GetAllocator()),
_size(0)
{
_Init();
Append(other);
}
// Construct with other map
// Move temp version
Tree(_MyT&& other) :
allocator(other.GetAllocator()),
_size(0)
{
_Init();
Append(_EVEREST Move(other));
}
// Construct from range
//Tree(Iterator first, Iterator last)
//{
// while (first != last)
// Insert(*first++)
//}
// Destructor
~Tree()
{
Clear();
allocator.Deallocate(_root.GetHandle());
//_DELETE(_nil.Get());
}
// Insert new element in the tree
// Move temp
//
// @param: value - Element value to add
_INLINE NodePointer Add(ValueType&& value)
{
return Insert(_EVEREST Move(value));
}
// Insert new element in the tree
//
// @param: value - The key/value to add
// @return: pointer to the inserted node
_INLINE NodePointer Insert(ValueType&& value)
{
NodePointer node = allocator.Allocate();
new(&node->_value) ValueType(_EVEREST Move(value));
_Insert(node, _root);
return node;
}
// Insert element if not exsits
// If element found, then update its value
// NOTE: if element is not unique, the first found only updated
//
// @param: value - The key/value to add
// @return: pointer to the inserted node or the exsit node
NodePointer InsertUnique(ValueType&& value)
{
NodePointer found = _Find(_traits.KeyOf(value));
if (found.IsNull())
return Insert(_EVEREST Move(value));
else
new(&found->_value) ValueType(_EVEREST Move(value));
return found;
}
// Replace exsiting elements at some key with value
//
// @param: value - the value to update
// @return: Count updated
uint32 Replace(const KeyType& key, Value& value)
{
//const KeyType& key = _traits.KeyOf(value);
auto it = Begin();
uint32 count = 0;
for (; it != End(); ++it)
{
auto comp = _traits.Compare(_traits.KeyOf(*it), key);
if (comp == 0)
{
new(&_traits.ValueOf(*it)) Value(value);
++count;
}
else if (comp > 0)
{
break;
}
}
return count;
}
// Replace all elements in this tree with value
//
// @param: value - the value to update
// @return: Count updated
uint32 ReplaceAll(Value& value)
{
auto it = Begin();
uint32 count = 0;
for (; it != End(); ++it)
{
new(&_traits.ValueOf(*it)) Value(value);
++count;
}
return count;
}
// Appends other tree to this tree
//
// @param: other - the other tree
void Append(const _MyT& other)
{
auto it = other.Begin();
for (; it != other.End(); ++it)
Insert(*it);
}
// Appends other tree to this tree
// Move temp version
//
// @param: other - the other tree
void Append(_MyT&& other)
{
auto it = other.Begin();
for (; it != other.End(); ++it)
Insert(_EVEREST Move(*it));
other.Clear();
}
/*_MyT& operator= (const _MyT& right)
{
if (&right != this)
{
Clear();
Append(right);
}
return *this;
}
_MyT& operator= (_MyT&& right)
{
if (&right != this)
{
Clear();
Append(_EVEREST Move(right));
}
return *this;
}*/
// Remove a node given key
//
// @param: key - The key to remove
void Remove(const KeyType& key)
{
NodePointer z = _Find(key);
if (z.IsNull())
return;
NodePointer x = _nil, y = _nil;
if ((z->_left == _nil) || (z->_right == _nil))
y = z;
else
y = Successor(z);
if (y->_left != _nil)
x = y->_left;
else
x = y->_right;
x->_parent = y->_parent;
if (y->_parent == _nil)
_root = x;
else if ((y->_parent->_left != _nil) && (y->_parent->_left == y))
y->_parent->_left = x;
else if ((y->_parent->_right != _nil) && (y->_parent->_right == y))
y->_parent->_right = x;
if (y != z)
z->_value = y->_value;
if (y->_color == TREE_COLOR_BLACK)
_RemoveFix(x);
// free deleted node
(z->_value).~ValueType();
allocator.Deallocate(z.GetHandle());
--_size;
}
// TODO: test new optmizations
// Return the count of nodes contains key
uint32 Count(const KeyType& key)
{
auto it = Begin();
uint32 count = 0;
for (; it != End(); ++it)
{
auto comp = _traits.Compare(_traits.KeyOf(*it), key);
if (comp == 0)
++count;
else if (comp > 0)
break;
}
return count;
}
// Find an element value at key
// Return pointer to found element or nullptr
//
// @param: The key to find
// @return: found value
Value* Find(const KeyType& key)
{
NodePointer found = _Find(key);
if (found.IsNull() || found == Nil())
return nullptr;
else
return &(_traits.ValueOf(found->_value));
}
// Find an element value at key
// Return cosnt pointer to found element or nullptr
//
// @param: The key to find
// @return: found value as const
const Value* Find(const KeyType& key) const
{
NodePointer found = _Find(key);
if (found.IsNull() || found == Nil())
return nullptr;
else
return const_cast<Tree*>(this)->Find(key);
}
// Check if the tree has some value
// return true if found
bool Contains(const ValueType& value)
{
return Find(_traits.KeyOf(value)) != nullptr;
}
// Copy all keys in array
//
// @param: keys - ref Array to fill with keys
template <typename Container>
void GetKeys(_out_ref_ Container& keys)
{
keys.Reserve(_size);
auto it = Begin();
for (; it != End(); ++it)
keys.Add(_traits.KeyOf(*it));
}
// Copy UNIQUE keys in array
//
// @param: keys - ref Array to fill with keys
template <typename Container>
void GetUniqueKeys(_out_ref_ Container& keys)
{
keys.Reserve(_size);
auto it = Begin();
for (; it != End(); ++it)
{
auto& key = _traits.KeyOf(*it);
if (!keys.Contains(key))
keys.Add(key);
}
keys.ShrinkToFit();
}
// Copy all values in array
//
// @param: values - ref Array to fill with values
template <typename Container>
void GetValues(_out_ref_ Container& values)
{
values.Reserve(_size);
auto it = Begin();
for (; it != End(); ++it)
values.Add(_traits.ValueOf(*it));
}
// Copy all values in array that match a given key
//
// @param: values - ref Array to fill with values
// @param: key - The key to match
template <typename Container>
void GetValues(_out_ref_ Container& values, const KeyType& key)
{
values.Reserve(_size);
auto it = Begin();
for (; it != End(); ++it)
{
auto comp = _traits.Compare(key, _traits.KeyOf(*it));
if (comp == 0)
values.Add(_traits.ValueOf(*it));
else if (comp > 0)
break;
}
values.ShrinkToFit();
}
// Return a referece to this container allocator instance
Allocator& GetAllocator() const
{
return allocator;
}
// Compacts the tree nodes making them consecutive
// this will reallocate the hole tree
void Compact()
{
//TODO:
}
// Return the size of the tree
_INLINE uint32 Size()
{
return _size;
}
// Clear the tree by removing all its nodes
_INLINE void Clear()
{
_Clear(_root);
_root = _nil;
}
// Return the minimun node in the tree
NodePointer Min(NodePointer node)
{
while (node->_left != _nil)
node = node->_left;
return node;
}
// Return the miximun value in the tree
NodePointer Max(NodePointer node)
{
while (node->_right != _nil)
node = node->_right;
return node;
}
//
_INLINE const NodePointer Nil() const
{
return (const NodePointer)_nil;
}
_INLINE bool IsNil(NodePointer node) const
{
return node == _nil;
}
// Return a reference to the root node
_INLINE NodePointer& Root()
{
return _root;
}
// Return true if the tree is empty
_INLINE bool Empty()
{
return _size == 0;
}
// Return the given node successor
NodePointer Successor(NodePointer x)
{
/*if (x->_right != _nil)
return Min(x->_right);
return _nil;*/
if (x->_right != _nil)
return Min(x->_right);
NodePointer y = x->_parent;
while (y != _nil && x == y->_right)
{
x = y;
y = y->_parent;
}
return y;
}
// Return the given node successor
NodePointer Predecessor(NodePointer x)
{
if (x->_left != _nil)
return Max(x->_left);
NodePointer y = x->_parent;
while (y != _nil && x == y->_left)
{
x = y;
y = y->_parent;
}
return y;
}
// Return the traits object related to this tree
_INLINE _Traits Traits() const
{
return _traits;
}
// Create an iterator to a node
//
// @param: The start node
// @return: The iterator object
iterator CreateIterator(NodePointer node)
{
return iterator(node, this);
}
// Create an iterator to the begining of the tree
iterator Begin()
{
return iterator(Min(_root), this);
}
// Create an iterator to the end of the tree
iterator End()
{
return iterator(_nil, this);
}
// Create a reverese iterator to a node
//
// @param: The start node
// @return: The iterator object
reverse_iterator CreateRevereseIterator(NodePointer node)
{
return reverse_iterator(node, this);
}
// Create a reverese iterator to the begining of the tree
reverse_iterator rBegin()
{
return reverse_iterator(Max(_root), this);
}
// Create a reverese iterator to the end of the tree
reverse_iterator rEnd()
{
return reverse_iterator(_nil, this);
}
Node* NodeOf(NodePointer node)
{
return node.Get();
}
protected:
void _Init()
{
allocator.Init();
_nil = allocator.Allocate();
//_nil->_isNil = _TRUE;
_nil->_color = TREE_COLOR_BLACK;
_nil->_left = Allocator::null_handle();
_nil->_right = Allocator::null_handle();
_root = _nil;
_root->_left = _nil;
_root->_right = _nil;
_root->_parent = _nil;
}
// Insert a node to the tree using normal binary search tree insertion
void _Insert(NodePointer z, NodePointer hint)
{
NodePointer y = _nil;
NodePointer x = hint;
while (x != _nil)
{
y = x;
if (_traits.Compare(_traits.KeyOf(z->_value), _traits.KeyOf(x->_value)) < 0)
x = x->_left; // Go left
else
x = x->_right; // >= Go right
}
// Set new node parent
z->_parent = y;
// Set new node left or right
if (y == _nil)
_root = z;
else if (_traits.Compare(_traits.KeyOf(z->_value), _traits.KeyOf(y->_value)) < 0)
y->_left = z;
else
y->_right = z;
// Init new node color and children
z->_left = _nil;
z->_right = _nil;
z->_color = TREE_COLOR_RED;
++_size;
// Check & fix tree properties
_InsertFix(z);
}
// Fixes an insertion by apply rb tree rules to a given node
void _InsertFix(NodePointer z)
{
NodePointer y = _nil;
while (z->_parent->_color == TREE_COLOR_RED)
{
if (z->_parent == z->_parent->_parent->_left)
{
y = z->_parent->_parent->_right;
// Case 1: If y is color, then recolor nodes
if (y->_color == TREE_COLOR_RED)
{
z->_parent->_color = TREE_COLOR_BLACK;
y->_color = TREE_COLOR_BLACK;
z->_parent->_parent->_color = TREE_COLOR_RED;
z = z->_parent->_parent;
}
// Case 2: If y is black and z is a right child
else if (z == z->_parent->_right)
{
// left rotate around z
z = z->_parent;
RotateLeft(z);
}
// Case 3: y is black and z is a left child
else
{
// Recolor and grandpa right rotation
z->_parent->_color = TREE_COLOR_BLACK;
z->_parent->_parent->_color = TREE_COLOR_RED;
RotateRight(z->_parent->_parent);
}
}
else
{
y = z->_parent->_parent->_left;
if (y->_color == TREE_COLOR_RED)
{
z->_parent->_color = TREE_COLOR_BLACK;
y->_color = TREE_COLOR_BLACK;
z->_parent->_parent->_color = TREE_COLOR_RED;
z = z->_parent->_parent;
}
else if (z == z->_parent->_left)
{
z = z->_parent;
RotateRight(z);
}
else
{
z->_parent->_color = TREE_COLOR_BLACK;
z->_parent->_parent->_color = TREE_COLOR_RED;
RotateLeft(z->_parent->_parent);
}
}
}
// Root always black
_root->_color = TREE_COLOR_BLACK;
}
// fixup remove rules
void _RemoveFix(NodePointer x)
{
NodePointer w = Allocator::null_handle();
while (x != _root && x->_color == TREE_COLOR_BLACK)
{
if (x == x->_parent->_left)
{
w = x->_parent->_right;
if (w->_color == TREE_COLOR_RED) // w is ref
{
w->_color = TREE_COLOR_BLACK;
x->_parent->_color = TREE_COLOR_RED;
RotateLeft(x->_parent);
w = x->_parent->_right;
}
if (w->_left->_color == TREE_COLOR_BLACK // w left is red
&& w->_right->_color == TREE_COLOR_BLACK)
{
w->_color = TREE_COLOR_RED;
x = x->_parent;
}
else
{
if (w->_right->_color == TREE_COLOR_BLACK) // w right is black
{
w->_left->_color = TREE_COLOR_BLACK;
w->_color = TREE_COLOR_RED;
RotateRight(w);
w = x->_parent->_right;
}
w->_color = x->_parent->_color;
x->_parent->_color = TREE_COLOR_BLACK;
w->_right->_color = TREE_COLOR_BLACK;
RotateLeft(x->_parent);
x = _root;
}
}
else
{
w = x->_parent->_left;
if (w->_color == TREE_COLOR_RED)
{
w->_color = TREE_COLOR_BLACK;
x->_parent->_color = TREE_COLOR_RED;
RotateRight(x->_parent);
w = x->_parent->_left;
}
if (w->_right->_color == TREE_COLOR_BLACK
&& w->_left->_color == TREE_COLOR_BLACK)
{
w->_color = TREE_COLOR_RED;
x = x->_parent;
}
else
{
if (w->_left->_color == TREE_COLOR_BLACK)
{
w->_right->_color = TREE_COLOR_BLACK;
w->_color = TREE_COLOR_RED;
RotateLeft(w);
w = x->_parent->_left;
}
w->_color = x->_parent->_color;
x->_parent->_color = TREE_COLOR_BLACK;
w->_left->_color = TREE_COLOR_BLACK;
RotateRight(x->_parent);
x = _root;
}
}
}
x->_color = TREE_COLOR_BLACK;
}
// Search for a key in this tree
//
// @param: key - the key to search for
// @return: Pointer to found key's node or nullptr
NodePointer _Find(const KeyType& key)
{
NodePointer current = _root;
while (current != _nil)
{
auto comp = _traits.Compare(key, _traits.KeyOf(current->_value));
if (comp == 0)
return current;
else if (comp > 0)
current = current->_right;
else if (comp < 0)
current = current->_left;
}
// Nothing found
return Allocator::null_handle();
}
// Apply a left rotation to a node
void RotateLeft(NodePointer x)
{
// Perfrom the rotation
NodePointer y = x->_right;
x->_right = y->_left;
// Update and fix pointers
if (y->_left != _nil)
y->_left->_parent = x;
y->_parent = x->_parent;
// Update root if requires
if (x->_parent == _nil)
_root = y;
else if (x->_parent->_left == x)
x->_parent->_left = y;
else
x->_parent->_right = y;
y->_left = x;
x->_parent = y;
}
// Apply a left rotation to a node
void RotateRight(NodePointer y)
{
NodePointer x = y->_left;
y->_left = x->_right;
if (x->_right != _nil)
x->_right->_parent = y;
x->_parent = y->_parent;
if (y->_parent == _nil)
_root = x;
else if (y->_parent->_right == y)
y->_parent->_right = x;
else
y->_parent->_left = x;
x->_right = y;
y->_parent = x;
}
// Clear by remove all given node and its children
void _Clear(NodePointer node)
{
if (!node.IsNull() && node != _nil)
{
_Clear(node->_right);
_Clear(node->_left);
(node->_value).~ValueType();
allocator.Deallocate(node.GetHandle());
--_size;
}
}
private:
// This is the tree's root node,
// We always start here
NodePointer _root;
// Null node for leafs and null uses
NodePointer _nil;
// The traits object,
// that allow tree to behaive like other containers types
_Traits _traits;
// Count of elements in the tree
uint32 _size;
// Define allocator type
Allocator allocator;
};
// TODO: To Add
// 1- Compact
// 2- Recycling nodes
}
| {
"content_hash": "e67d621aad152a827dd06ae21b23a822",
"timestamp": "",
"source": "github",
"line_count": 1093,
"max_line_length": 95,
"avg_line_length": 19.7035681610247,
"alnum_prop": 0.5709509658246656,
"repo_name": "everest3d/boxyto",
"id": "ece2e6f28b664f4578d1348368bbaf303015b427",
"size": "22772",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "boxyto/containers/Tree.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1444"
},
{
"name": "C++",
"bytes": "180282"
}
],
"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_27) on Sat Oct 06 03:04:46 EDT 2012 -->
<META http-equiv="Content-Type" content="text/html; charset=utf-8">
<TITLE>
Uses of Class org.apache.solr.update.TransactionLog.LogCodec (Solr 4.0.0 API)
</TITLE>
<META NAME="date" CONTENT="2012-10-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="Uses of Class org.apache.solr.update.TransactionLog.LogCodec (Solr 4.0.0 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="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="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/solr/update/TransactionLog.LogCodec.html" title="class in org.apache.solr.update"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../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
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/apache/solr/update//class-useTransactionLog.LogCodec.html" target="_top"><B>FRAMES</B></A>
<A HREF="TransactionLog.LogCodec.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>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.apache.solr.update.TransactionLog.LogCodec</B></H2>
</CENTER>
No usage of org.apache.solr.update.TransactionLog.LogCodec
<P>
<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="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/solr/update/TransactionLog.LogCodec.html" title="class in org.apache.solr.update"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../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
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/apache/solr/update//class-useTransactionLog.LogCodec.html" target="_top"><B>FRAMES</B></A>
<A HREF="TransactionLog.LogCodec.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>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
<address>Copyright © 2000-2012 Apache Software Foundation. All Rights Reserved.</address>
<script src='../../../../../prettify.js' type='text/javascript'></script>
<script type='text/javascript'>
(function(){
var oldonload = window.onload;
if (typeof oldonload != 'function') {
window.onload = prettyPrint;
} else {
window.onload = function() {
oldonload();
prettyPrint();
}
}
})();
</script>
</BODY>
</HTML>
| {
"content_hash": "b304cf29486e9e61099845564a9e0b1b",
"timestamp": "",
"source": "github",
"line_count": 159,
"max_line_length": 225,
"avg_line_length": 40.25157232704402,
"alnum_prop": 0.604375,
"repo_name": "BibAlex/bhl_rails_solr",
"id": "66669ffded2903cd1bd4b63581c7d329bc70f2d9",
"size": "6400",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "docs/solr-core/org/apache/solr/update/class-use/TransactionLog.LogCodec.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "282"
},
{
"name": "CSS",
"bytes": "94317"
},
{
"name": "HTML",
"bytes": "63063"
},
{
"name": "JavaScript",
"bytes": "963476"
},
{
"name": "Shell",
"bytes": "5094"
},
{
"name": "XSLT",
"bytes": "98495"
}
],
"symlink_target": ""
} |
title: State Geographic Information Database (SGID) Data Sharing Agreement
layout: page_nocrumb
author:
display_name: UGRC Office
email: ugrc@utah.gov
tags:
- license
- policy
categories: []
date: 2021-07-14 17:00:00 -0700
---
## Applicability
{: .text-left}
The following Data Sharing Agreement applies to all individuals and organizations sharing data with the SGID in any way.
You consent to this Data Sharing Agreement when you submit a [Porter issue](https://github.com/agrc/porter/issues/new?assignees=%40steveoh%2C+%40gregbunce%2C+%40rkelson&labels=introduction%2C+porter&template=1-introduce-sgid-dataset.md&title=Add+%3Cdataset+name%3E+from+%3Csource%3E) to introduce your data to the SGID. In cases where UGRC submits the Porter issue on your behalf, UGRC will contact you via email to get your consent to this agreement. If you need to discuss different GRAMA/license/disclaimer terms, please note this in the Porter issue.
## Definitions
{: .text-left}
**"Aggregate data"** refers to any data that cover a specific area of the state and are provided by another organization (such as a city or county) for UGRC to combine with other similar data into statewide datasets.
**"External data"** refers to any data stored or hosted by a person or organization outside of UGRC.
**"Hosted data"** refers to any data stored, maintained, and served by UGRC, whether created by UGRC or provided by another organization. It may include aggregate data.
**"SGID entry"** refers to any of the following:
1. Links in the SGID Index to external data
1. Links and references in [opendata.gis.utah.gov](https://opendata.gis.utah.gov) to external data in the form of ArcGIS Online items owned by other organizations
1. Hosted data in the Open SGID
1. Hosted data in UGRC's ArcGIS Online organization that are shared with an SGID ArcGIS Online group or the "AGRC Shelf" group
The **"steward"** refers to the individual or organization that shares data with UGRC for inclusion in the SGID.
## General Provisions
{: .text-left}
- UGRC will make all SGID entries available to the general public without any form of login or account.
- UGRC may edit any hosted data to fix any technical errors that prevent the data from being shared in the SGID.
- UGRC may edit any aggregate data to conform with established standards and schemas for statewide datasets.
- UGRC will follow our established [SGID policies]({% link about/policy/sgid/index.md %}).
- The steward will ensure any links or connections to external data remain live and do not require any form of login or account.
- The steward will take reasonable efforts to not modify the schema of all external data, with the exception of adding new fields.
- The steward will provide UGRC with two weeks prior notice, if possible, of any schema changes to hosted data.
- UGRC will remove SGID entries according to our [removal policy]({% link about/policy/sgid/index.md %}#dataset-deprecation-and-removal) through the normal [dataset deprecation process](https://github.com/agrc/porter/blob/main/.github/ISSUE_TEMPLATE/2-deprecate-sgid-dataset.md).
- UGRC will grant requests for immediate removal of accidentally shared non-public data or other urgent situations and will handle these on a case-by-case basis.
## License and Disclaimer
{: .text-left}
The following items apply unless the steward and UGRC specifically negotiate different terms:
- UGRC considers all SGID entries "Public" for purposes of the Utah [Government Records Access and Management Act (GRAMA)](https://archives.utah.gov/rim/government-records-law.html).
- UGRC licenses all hosted data under a [Creative Commons Attribution 4.0 International License](https://creativecommons.org/licenses/by/4.0/).
- All hosted data are subject to the [standard UGRC disclaimer]({% link about/policy/license-disclaimer/index.md %}#disclaimer).
- UGRC will include the aforementioned license and disclaimer in the metadata of all hosted data.
| {
"content_hash": "80f0b0bad34aacb53f167ec8e30320a3",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 554,
"avg_line_length": 67.11864406779661,
"alnum_prop": 0.7823232323232323,
"repo_name": "agrc/agrc.github.io",
"id": "534e05607ba308d142357d2c133f3ce43338b794",
"size": "3964",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "about/policy/data-sharing-agreement/index.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "42827"
},
{
"name": "HTML",
"bytes": "9770686"
},
{
"name": "JavaScript",
"bytes": "12791"
},
{
"name": "Python",
"bytes": "28534"
},
{
"name": "Ruby",
"bytes": "385"
},
{
"name": "Shell",
"bytes": "200"
}
],
"symlink_target": ""
} |
package org.apache.jackrabbit.oak.scalability.benchmarks.search;
import java.util.Calendar;
import java.util.TimeZone;
import javax.annotation.Nonnull;
import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.query.Query;
import javax.jcr.query.QueryManager;
import javax.jcr.query.QueryResult;
import javax.jcr.query.RowIterator;
import org.apache.jackrabbit.oak.scalability.suites.ScalabilityNodeSuite;
import org.apache.jackrabbit.oak.scalability.suites.ScalabilityAbstractSuite.ExecutionContext;
/**
* Abstract class which defines utility methods for processing results like
* pagination and no pagination.
*
*/
public abstract class PaginationEnabledSearcher extends SearchScalabilityBenchmark {
/**
* Pagination limit for one page
*/
protected static final int LIMIT = Integer.getInteger("limit", 25);
/**
* Number of page accesses
*/
protected static final int PAGES = Integer.getInteger("pages", 5);
protected static final String KEYSET_VAL_PROP = "keysetval";
protected void processResultsOffsetPagination(@Nonnull final QueryManager qm,
ExecutionContext context) throws RepositoryException {
for (int page = 0; page < PAGES; page++) {
Query query = getQuery(qm, context);
query.setLimit(LIMIT);
query.setOffset(page * LIMIT);
iterate(query);
}
}
private Node iterate(Query query) throws RepositoryException {
QueryResult r = query.execute();
RowIterator it = r.getRows();
Node last = null;
while (it.hasNext()) {
last = it.nextRow().getNode();
LOG.debug(last.getPath());
}
return last;
}
protected void processResultsKeysetPagination(@Nonnull final QueryManager qm,
ExecutionContext context) throws RepositoryException {
Calendar now = Calendar.getInstance();
now.setTimeZone(TimeZone.getTimeZone("GMT"));
context.getMap().put(KEYSET_VAL_PROP, now);
for (int page = 0; page < PAGES; page++) {
Query query = getQuery(qm, context);
query.setLimit(LIMIT);
Node lastNode = iterate(query);
if (lastNode != null) {
Property prop =
lastNode.getProperty(ScalabilityNodeSuite.CTX_PAGINATION_KEY_PROP);
context.getMap().put(KEYSET_VAL_PROP, prop.getDate());
}
}
context.getMap().remove(KEYSET_VAL_PROP);
}
protected String getOrderByClause() {
return " order by" + " @" + ScalabilityNodeSuite.SORT_PROP + " descending," + " @"
+ ScalabilityNodeSuite.DATE_PROP + " descending";
}
}
| {
"content_hash": "623a3328091747d5b26d53a07735f8ac",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 94,
"avg_line_length": 32.92857142857143,
"alnum_prop": 0.6529284164859002,
"repo_name": "FlakyTestDetection/jackrabbit-oak",
"id": "d16925c1bbf080a58f285ffc762d7018eca392fd",
"size": "3586",
"binary": false,
"copies": "2",
"ref": "refs/heads/trunk",
"path": "oak-benchmarks/src/main/java/org/apache/jackrabbit/oak/scalability/benchmarks/search/PaginationEnabledSearcher.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "24037"
},
{
"name": "Groovy",
"bytes": "145173"
},
{
"name": "HTML",
"bytes": "1406"
},
{
"name": "Java",
"bytes": "24605119"
},
{
"name": "JavaScript",
"bytes": "42991"
},
{
"name": "Perl",
"bytes": "7585"
},
{
"name": "Shell",
"bytes": "17433"
}
],
"symlink_target": ""
} |
{% extends "base.html" %}
{% load i18n %}
{% block h_title %}Clan-panel plans and pricing{% endblock %}
{% block content %}
<h2>Clan-panel pricing</h2>
<p>
Clan-panel is completely free to start. But for those who need more, the Base and Premium plans delivers more features at a great value.
</p>
<div class="table-container table-responsive">
<table class="table table-hover">
<thead>
<tr><th></th><th>Free plan</th><th>Base plan</th><th>Premium plan</th></tr>
</thead>
<tr>
<td>
<ul>
<li><a href="{% url action_doc_page page='clan_news' %}">Track events</a> of the clan</li>
<li>Keeping <a href="{% url action_doc_page page='top_vehicles' %}">records of the top-tanks</a></li>
<li>Tracking the <a href="{% url action_doc_page page='members_activity' %}">current activity</a> of clan members</li>
<li>Forming and supporting <a href="{% url action_doc_page page='company' %}">tank companies</a></li>
<li>Coordination for <a href="{% url action_doc_page page='stronghold' %}">defense of Stronghold</a></li>
</ul>
</td>
<td><img alt="Yes" src="/media/img/true.gif"></td>
<td><img alt="Yes" src="/media/img/true.gif"></td>
<td><img alt="Yes" src="/media/img/true.gif"></td>
</tr>
<tr>
<td>
<ul>
<li>Data updates</li>
</ul>
</td>
<td>Manually, once per tree days</td>
<td>Automatically, daily</td>
<td>Automatically, daily</td>
</tr>
<tr>
<td>
{% include "text_base.html" %}
</td>
<td><img alt="No" src="/media/img/false.gif"></td>
<td><img alt="Yes" src="/media/img/true.gif"></td>
<td><img alt="Yes" src="/media/img/true.gif"></td>
</tr>
<tr>
<td>
{% include "text_prem.html" %}
</td>
<td><img alt="No" src="/media/img/false.gif"></td>
<td><img alt="No" src="/media/img/false.gif"></td>
<td><img alt="Yes" src="/media/img/true.gif"></td>
</tr>
<tr class="info">
<td><strong>Cost</strong></td>
<td><strong>Free</strong></td>
<td><strong>${{base_mode_usd}} per {{base_mode_days}} days</strong></td>
<td><strong>${{prem_mode_usd}} per {{prem_mode_days}} days</strong></td>
</tr>
</table>
</div>
<p>
<strong>How to pay.</strong>
Go to any page of clan by your choice, then click "Upgrade to base plan" or "Upgrade to premium plan" button at the top part of the page.
</p>
{% endblock %}
| {
"content_hash": "b60dc7f7565068064b97f22306cd00e8",
"timestamp": "",
"source": "github",
"line_count": 80,
"max_line_length": 137,
"avg_line_length": 27.4625,
"alnum_prop": 0.6426945835229859,
"repo_name": "vb64/clan.panel.i18n",
"id": "76dcd9767315fa4de8cf2e24b85754f1473d7597",
"size": "2197",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "de/pricing.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "82901"
},
{
"name": "Python",
"bytes": "120"
}
],
"symlink_target": ""
} |
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace Raml.Parser.Expressions
{
public class RamlDocument
{
private readonly IDictionary<string, object> dynamicRaml;
public RamlDocument()
{
Resources = new Collection<Resource>();
Documentation = new Collection<DocumentationItem>();
BaseUriParameters = new Dictionary<string, Parameter>();
SecuredBy = new Collection<string>();
Protocols = new Collection<Protocol>();
SecuritySchemes = new Collection<IDictionary<string, SecurityScheme>>();
ResourceTypes = new Collection<IDictionary<string, ResourceType>>();
Traits = new Collection<IDictionary<string, Method>>();
Schemas = new Collection<IDictionary<string, string>>();
}
public RamlDocument(IDictionary<string, object> dynamicRaml)
{
this.dynamicRaml = dynamicRaml;
}
public IDictionary<string, object> RawContent { get { return dynamicRaml; } }
public string BaseUri { get; set; }
public string Title { get; set; }
public string Version { get; set; }
public string MediaType { get; set; }
public IEnumerable<DocumentationItem> Documentation { get; set; }
public IDictionary<string, Parameter> BaseUriParameters { get; set; }
public IEnumerable<string> SecuredBy { get; set; }
public IEnumerable<Protocol> Protocols { get; set; }
public string Method { get; set; }
public IEnumerable<IDictionary<string, SecurityScheme>> SecuritySchemes { get; set; }
public IEnumerable<IDictionary<string, ResourceType>> ResourceTypes { get; set; }
public IEnumerable<IDictionary<string, Method>> Traits { get; set; }
public IEnumerable<IDictionary<string, string>> Schemas { get; set; }
public ICollection<Resource> Resources { get; set; }
}
}
| {
"content_hash": "c22edb481867956b539fed65f8ef4c46",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 87,
"avg_line_length": 30.80701754385965,
"alnum_prop": 0.7306378132118451,
"repo_name": "giserh/raml-dotnet-parser",
"id": "42058dcbca5aa53283326ce9ddd77ef2af490df9",
"size": "1758",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Raml.Parser/Expressions/RamlDocument.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "40046"
},
{
"name": "JavaScript",
"bytes": "7047"
},
{
"name": "PowerShell",
"bytes": "564"
},
{
"name": "RAML",
"bytes": "361675"
}
],
"symlink_target": ""
} |
package com.vladmihalcea.book.hpjp.hibernate.inheritance.discriminator.description;
import java.util.Date;
import jakarta.persistence.DiscriminatorValue;
import jakarta.persistence.Entity;
import jakarta.persistence.Table;
import jakarta.persistence.Temporal;
import jakarta.persistence.TemporalType;
/**
* @author Vlad Mihalcea
*/
@Entity
@Table(name = "announcement")
@DiscriminatorValue("2")
public class Announcement extends Topic {
@Temporal(TemporalType.TIMESTAMP)
private Date validUntil;
public Date getValidUntil() {
return validUntil;
}
public void setValidUntil(Date validUntil) {
this.validUntil = validUntil;
}
}
| {
"content_hash": "a010647c119a0e3dc53fe3e3f3dbc965",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 83,
"avg_line_length": 22.964285714285715,
"alnum_prop": 0.7931570762052877,
"repo_name": "vladmihalcea/high-performance-java-persistence",
"id": "594cb6d4b622b4123085d355699c140f9aba14e2",
"size": "643",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/inheritance/discriminator/description/Announcement.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "49"
},
{
"name": "Java",
"bytes": "3429717"
},
{
"name": "PLpgSQL",
"bytes": "1778"
},
{
"name": "Shell",
"bytes": "43"
}
],
"symlink_target": ""
} |
from __future__ import print_function
import os
from . import py3k_compat as pickle
import numpy as np
def pickle_results(filename=None, verbose=True):
"""Generator for decorator which allows pickling the results of a funcion
Pickle is python's built-in object serialization. This decorator, when
used on a function, saves the results of the computation in the function
to a pickle file. If the function is called a second time with the
same inputs, then the computation will not be repeated and the previous
results will be used.
This functionality is useful for computations which take a long time,
but will need to be repeated (such as the first step of a data analysis).
Parameters
----------
filename : string (optional)
pickle file to which results will be saved.
If not specified, then the file is '<funcname>_output.pkl'
where '<funcname>' is replaced by the name of the decorated function.
verbose : boolean (optional)
if True, then print a message to standard out specifying when the
pickle file is written or read.
Examples
--------
>>> @pickle_results('tmp.pkl', verbose=True)
... def f(x):
... return x * x
>>> f(4)
@pickle_results: computing results and saving to 'tmp.pkl'
16
>>> f(4)
@pickle_results: using precomputed results from 'tmp.pkl'
16
>>> f(6)
@pickle_results: computing results and saving to 'tmp.pkl'
36
>>> import os; os.remove('tmp.pkl')
"""
def pickle_func(f, filename=filename, verbose=verbose):
if filename is None:
filename = '%s_output.pkl' % f.__name__
def new_f(*args, **kwargs):
try:
D = pickle.load(open(filename, 'rb'))
cache_exists = True
except:
D = {}
cache_exists = False
# simple comparison doesn't work in the case of numpy arrays
Dargs = D.get('args')
Dkwargs = D.get('kwargs')
try:
args_match = (args == Dargs)
except:
args_match = np.all([np.all(a1 == a2)
for (a1, a2) in zip(Dargs, args)])
try:
kwargs_match = (kwargs == Dkwargs)
except:
kwargs_match = ((sorted(Dkwargs.keys())
== sorted(kwargs.keys()))
and (np.all([np.all(Dkwargs[key]
== kwargs[key])
for key in kwargs])))
if (type(D) == dict and D.get('funcname') == f.__name__
and args_match and kwargs_match):
if verbose:
print("@pickle_results: using precomputed "
"results from '%s'" % filename)
retval = D['retval']
else:
if verbose:
print("@pickle_results: computing results "
"and saving to '%s'" % filename)
if cache_exists:
print(" warning: cache file '%s' exists" % filename)
print(" - args match: %s" % args_match)
print(" - kwargs match: %s" % kwargs_match)
retval = f(*args, **kwargs)
funcdict = dict(funcname=f.__name__, retval=retval,
args=args, kwargs=kwargs)
with open(filename, 'wb') as outfile:
pickle.dump(funcdict, outfile)
return retval
return new_f
return pickle_func
| {
"content_hash": "8afd6c4a65d0ad2afd33d6ed0c508a2a",
"timestamp": "",
"source": "github",
"line_count": 101,
"max_line_length": 77,
"avg_line_length": 37.05940594059406,
"alnum_prop": 0.5153620090836227,
"repo_name": "kcavagnolo/astroML",
"id": "7dc0a239a6eeb818130d51aedb2f3ad7c2034908",
"size": "3743",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "astroML/decorators.py",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Makefile",
"bytes": "696"
},
{
"name": "Python",
"bytes": "1087103"
}
],
"symlink_target": ""
} |
#ifndef _DT_BINDINGS_THERMAL_THERMAL_H
#define _DT_BINDINGS_THERMAL_THERMAL_H
/* On cooling devices upper and lower limits */
#define THERMAL_NO_LIMIT (~0)
#endif
| {
"content_hash": "120e94517ca732d70072e1a421e3d078",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 47,
"avg_line_length": 16.9,
"alnum_prop": 0.727810650887574,
"repo_name": "jrobhoward/SCADAbase",
"id": "b5e6b0069ac7703b927a0c040ffcbd764c1afd89",
"size": "342",
"binary": false,
"copies": "1724",
"ref": "refs/heads/SCADAbase",
"path": "sys/gnu/dts/include/dt-bindings/thermal/thermal.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "AGS Script",
"bytes": "62471"
},
{
"name": "Assembly",
"bytes": "4615704"
},
{
"name": "Awk",
"bytes": "273794"
},
{
"name": "Batchfile",
"bytes": "20333"
},
{
"name": "C",
"bytes": "457666547"
},
{
"name": "C++",
"bytes": "91495356"
},
{
"name": "CMake",
"bytes": "17632"
},
{
"name": "CSS",
"bytes": "104220"
},
{
"name": "ChucK",
"bytes": "39"
},
{
"name": "D",
"bytes": "6321"
},
{
"name": "DIGITAL Command Language",
"bytes": "10638"
},
{
"name": "DTrace",
"bytes": "1904158"
},
{
"name": "Emacs Lisp",
"bytes": "32010"
},
{
"name": "EmberScript",
"bytes": "286"
},
{
"name": "Forth",
"bytes": "204603"
},
{
"name": "GAP",
"bytes": "72078"
},
{
"name": "Groff",
"bytes": "32376243"
},
{
"name": "HTML",
"bytes": "5776268"
},
{
"name": "Haskell",
"bytes": "2458"
},
{
"name": "IGOR Pro",
"bytes": "6510"
},
{
"name": "Java",
"bytes": "112547"
},
{
"name": "KRL",
"bytes": "4950"
},
{
"name": "Lex",
"bytes": "425858"
},
{
"name": "Limbo",
"bytes": "4037"
},
{
"name": "Logos",
"bytes": "179088"
},
{
"name": "Makefile",
"bytes": "12750766"
},
{
"name": "Mathematica",
"bytes": "21782"
},
{
"name": "Max",
"bytes": "4105"
},
{
"name": "Module Management System",
"bytes": "816"
},
{
"name": "Objective-C",
"bytes": "1571960"
},
{
"name": "PHP",
"bytes": "2471"
},
{
"name": "PLSQL",
"bytes": "96552"
},
{
"name": "PLpgSQL",
"bytes": "2212"
},
{
"name": "Perl",
"bytes": "3947402"
},
{
"name": "Perl6",
"bytes": "122803"
},
{
"name": "PostScript",
"bytes": "152255"
},
{
"name": "Prolog",
"bytes": "42792"
},
{
"name": "Protocol Buffer",
"bytes": "54964"
},
{
"name": "Python",
"bytes": "381066"
},
{
"name": "R",
"bytes": "764"
},
{
"name": "Rebol",
"bytes": "738"
},
{
"name": "Ruby",
"bytes": "67015"
},
{
"name": "Scheme",
"bytes": "5087"
},
{
"name": "Scilab",
"bytes": "196"
},
{
"name": "Shell",
"bytes": "10963470"
},
{
"name": "SourcePawn",
"bytes": "2293"
},
{
"name": "SuperCollider",
"bytes": "80208"
},
{
"name": "Tcl",
"bytes": "7102"
},
{
"name": "TeX",
"bytes": "720582"
},
{
"name": "VimL",
"bytes": "19597"
},
{
"name": "XS",
"bytes": "17496"
},
{
"name": "XSLT",
"bytes": "4564"
},
{
"name": "Yacc",
"bytes": "1881915"
}
],
"symlink_target": ""
} |
[xxaxxelxx/xx_account](https://index.docker.io/u/xxaxxelxx/xx_account/)
## Synopsis
This repo is the base for an [automated docker build](https://hub.docker.com/r/xxaxxelxx/xx_account/) and is part of a dockerized distributed streaming system consisting of following elements:
* [xxaxxelxx/xx_account](https://github.com/xxaxxelxx/xx_account)
* [xxaxxelxx/xx_bridgehead](https://github.com/xxaxxelxx/xx_bridgehead)
* [xxaxxelxx/xx_coverter](https://github.com/xxaxxelxx/xx_converter)
* [xxaxxelxx/xx_customerweb](https://github.com/xxaxxelxx/xx_customerweb)
* [xxaxxelxx/xx_geograph](https://github.com/xxaxxelxx/xx_geograph)
* [xxaxxelxx/xx_icecast](https://github.com/xxaxxelxx/xx_icecast)
* [xxaxxelxx/xx_liquidsoap](https://github.com/xxaxxelxx/xx_liquidsoap)
* [xxaxxelxx/xx_loadbalancer](https://github.com/xxaxxelxx/xx_loadbalancer)
* [xxaxxelxx/xx_logsplitter](https://github.com/xxaxxelxx/xx_logsplitter)
* [xxaxxelxx/xx_pulse](https://github.com/xxaxxelxx/xx_pulse)
* [xxaxxelxx/xx_reflector](https://github.com/xxaxxelxx/xx_reflector)
* [xxaxxelxx/xx_rrdcollect](https://github.com/xxaxxelxx/xx_rrdcollect)
* [xxaxxelxx/xx_rrdgraph](https://github.com/xxaxxelxx/xx_rrdgraph)
* [xxaxxelxx/xx_sshdepot](https://github.com/xxaxxelxx/xx_sshdepot)
* [xxaxxelxx/xx_sshsatellite](https://github.com/xxaxxelxx/xx_sshsatellite)
The running docker container provides a service for very special streaming purposes usable for a distributed architecture.
It presumably will not fit for you, but it is possible to tune it. If you need some additional information, please do not hesitate to ask.
This [xxaxxelxx/xx_account](https://hub.docker.com/r/xxaxxelxx/xx_account/) repo is an essential part of a complex compound used for streaming.
All the player machines drop their raw icecast log files to this place and grab their intro files from here.
### Example
```bash
$ docker run -d --name sshdepot --volumes-from depotdatavolume --volumes-from customerdatavolume -p 65522:22 --restart=always xxaxxelxx/xx_sshdepot
```
***
## License
[MIT](https://github.com/xxaxxelxx/xx_Liquidsoap/blob/master/LICENSE.md)
| {
"content_hash": "29c43b5e50131066f647f31e6082a1b9",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 192,
"avg_line_length": 60.31428571428572,
"alnum_prop": 0.7759355755566082,
"repo_name": "xxaxxelxx/xx_sshdepot",
"id": "a5d82b547ee59898a95aab63adb4fbc5f62986bb",
"size": "2228",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Shell",
"bytes": "204"
}
],
"symlink_target": ""
} |
package com.ttdevs.superimageview;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | {
"content_hash": "510463034b77d022b4d40ace7e493939",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 93,
"avg_line_length": 27.384615384615383,
"alnum_prop": 0.7528089887640449,
"repo_name": "b2b2244424/SuperImageView",
"id": "83f0bd7e078c3777b61ebe6971f3e63586c1819a",
"size": "356",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/androidTest/java/com/ttdevs/superimageview/ApplicationTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1481"
}
],
"symlink_target": ""
} |
/// Copyright (c) 2012 Ecma International. All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms"). Any redistribution of this code must retain the above
/// copyright and this notice and otherwise comply with the Use Terms.
/**
* @path ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-i-9.js
* @description Array.prototype.forEach - element to be retrieved is own accessor property on an Array-like object
*/
function testcase() {
var testResult = false;
function callbackfn(val, idx, obj) {
if (idx === 0) {
testResult = (val === 11);
}
}
var obj = { 10: 10, length: 20 };
Object.defineProperty(obj, "0", {
get: function () {
return 11;
},
configurable: true
});
Array.prototype.forEach.call(obj, callbackfn);
return testResult;
}
runTestCase(testcase);
| {
"content_hash": "77199abcb394e11b512973aa31dcd09d",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 114,
"avg_line_length": 31.542857142857144,
"alnum_prop": 0.5788043478260869,
"repo_name": "hippich/typescript",
"id": "f2869ff6d63209c2be9344234cd851e1853e6b6b",
"size": "1104",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "tests/Fidelity/test262/suite/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-i-9.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Elixir",
"bytes": "3294"
},
{
"name": "JavaScript",
"bytes": "24658966"
},
{
"name": "Shell",
"bytes": "386"
},
{
"name": "TypeScript",
"bytes": "18276884"
}
],
"symlink_target": ""
} |
module.exports = function(config){
config.set({
basePath : './',
files : [
'demo/client/app/bower_components/angular/angular.js',
'demo/client/app/bower_components/angular-route/angular-route.js',
'demo/client/app/bower_components/angular-aria/angular-aria.js',
'demo/client/app/bower_components/angular-mocks/angular-mocks.js',
'demo/client/app/bower_components/angular-material/angular-material.js',
'demo/client/app/components/**/*.js',
'demo/client/app/view*/**/*.js'
],
autoWatch : true,
frameworks: ['jasmine'],
browsers : ['Chrome'],
plugins : [
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-jasmine',
'karma-junit-reporter'
],
junitReporter : {
outputFile: 'test_out/unit.xml',
suite: 'unit'
}
});
};
| {
"content_hash": "e2a3cc66367135cfc0cba95ef12d7992",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 78,
"avg_line_length": 25.228571428571428,
"alnum_prop": 0.5922989807474519,
"repo_name": "christianacca/angular-cc-servercaches",
"id": "f8570ece7d0d52d17d103614cb7c5b60f084b43d",
"size": "883",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "karma.conf.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1875"
},
{
"name": "HTML",
"bytes": "3834"
},
{
"name": "JavaScript",
"bytes": "9577"
}
],
"symlink_target": ""
} |
/**
* @license AngularJS v1.0.6
* (c) 2010-2012 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window, document, undefined) {
'use strict';
////////////////////////////////////
/**
* @ngdoc function
* @name angular.lowercase
* @function
*
* @description Converts the specified string to lowercase.
* @param {string} string String to be converted to lowercase.
* @returns {string} Lowercased string.
*/
var lowercase = function(string) {
return isString(string) ? string.toLowerCase() : string;
};
/**
* @ngdoc function
* @name angular.uppercase
* @function
*
* @description Converts the specified string to uppercase.
* @param {string} string String to be converted to uppercase.
* @returns {string} Uppercased string.
*/
var uppercase = function(string) {
return isString(string) ? string.toUpperCase() : string;
};
var manualLowercase = function(s) {
return isString(s) ? s.replace(/[A-Z]/g, function(ch) {
return String.fromCharCode(ch.charCodeAt(0) | 32);
}) : s;
};
var manualUppercase = function(s) {
return isString(s) ? s.replace(/[a-z]/g, function(ch) {
return String.fromCharCode(ch.charCodeAt(0) & ~32);
}) : s;
};
// String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
// locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
// with correct but slower alternatives.
if ('i' !== 'I'.toLowerCase()) {
lowercase = manualLowercase;
uppercase = manualUppercase;
}
var /** holds major version number for IE or NaN for real browsers */
msie = int((/msie (\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]),
jqLite, // delay binding since jQuery could be loaded after us.
jQuery, // delay binding
slice = [].slice,
push = [].push,
toString = Object.prototype.toString,
/** @name angular */
angular = window.angular || (window.angular = {}),
angularModule,
nodeName_,
uid = ['0', '0', '0'];
/**
* @ngdoc function
* @name angular.forEach
* @function
*
* @description
* Invokes the `iterator` function once for each item in `obj` collection, which can be either an
* object or an array. The `iterator` function is invoked with `iterator(value, key)`, where `value`
* is the value of an object property or an array element and `key` is the object property key or
* array element index. Specifying a `context` for the function is optional.
*
* Note: this function was previously known as `angular.foreach`.
*
<pre>
var values = {name: 'misko', gender: 'male'};
var log = [];
angular.forEach(values, function(value, key){
this.push(key + ': ' + value);
}, log);
expect(log).toEqual(['name: misko', 'gender:male']);
</pre>
*
* @param {Object|Array} obj Object to iterate over.
* @param {Function} iterator Iterator function.
* @param {Object=} context Object to become context (`this`) for the iterator function.
* @returns {Object|Array} Reference to `obj`.
*/
/**
* @private
* @param {*} obj
* @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments, ...)
*/
function isArrayLike(obj) {
if (!obj || (typeof obj.length !== 'number')) return false;
// We have on object which has length property. Should we treat it as array?
if (typeof obj.hasOwnProperty != 'function' &&
typeof obj.constructor != 'function') {
// This is here for IE8: it is a bogus object treat it as array;
return true;
} else {
return obj instanceof JQLite || // JQLite
(jQuery && obj instanceof jQuery) || // jQuery
toString.call(obj) !== '[object Object]' || // some browser native object
typeof obj.callee === 'function'; // arguments (on IE8 looks like regular obj)
}
}
function forEach(obj, iterator, context) {
var key;
if (obj) {
if (isFunction(obj)) {
for (key in obj) {
if (key != 'prototype' && key != 'length' && key != 'name' &&
obj.hasOwnProperty(key)) {
iterator.call(context, obj[key], key);
}
}
} else if (obj.forEach && obj.forEach !== forEach) {
obj.forEach(iterator, context);
} else if (isArrayLike(obj)) {
for (key = 0; key < obj.length; key++)
iterator.call(context, obj[key], key);
} else {
for (key in obj) {
if (obj.hasOwnProperty(key)) {
iterator.call(context, obj[key], key);
}
}
}
}
return obj;
}
function sortedKeys(obj) {
var keys = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
keys.push(key);
}
}
return keys.sort();
}
function forEachSorted(obj, iterator, context) {
var keys = sortedKeys(obj);
for (var i = 0; i < keys.length; i++) {
iterator.call(context, obj[keys[i]], keys[i]);
}
return keys;
}
/**
* when using forEach the params are value, key, but it is often useful to have key, value.
* @param {function(string, *)} iteratorFn
* @returns {function(*, string)}
*/
function reverseParams(iteratorFn) {
return function(value, key) {
iteratorFn(key, value)
};
}
/**
* A consistent way of creating unique IDs in angular. The ID is a sequence of alpha numeric
* characters such as '012ABC'. The reason why we are not using simply a number counter is that
* the number string gets longer over time, and it can also overflow, where as the nextId
* will grow much slower, it is a string, and it will never overflow.
*
* @returns an unique alpha-numeric string
*/
function nextUid() {
var index = uid.length;
var digit;
while (index) {
index--;
digit = uid[index].charCodeAt(0);
if (digit == 57 /*'9'*/ ) {
uid[index] = 'A';
return uid.join('');
}
if (digit == 90 /*'Z'*/ ) {
uid[index] = '0';
} else {
uid[index] = String.fromCharCode(digit + 1);
return uid.join('');
}
}
uid.unshift('0');
return uid.join('');
}
/**
* @ngdoc function
* @name angular.extend
* @function
*
* @description
* Extends the destination object `dst` by copying all of the properties from the `src` object(s)
* to `dst`. You can specify multiple `src` objects.
*
* @param {Object} dst Destination object.
* @param {...Object} src Source object(s).
*/
function extend(dst) {
forEach(arguments, function(obj) {
if (obj !== dst) {
forEach(obj, function(value, key) {
dst[key] = value;
});
}
});
return dst;
}
function int(str) {
return parseInt(str, 10);
}
function inherit(parent, extra) {
return extend(new(extend(function() {}, {
prototype: parent
}))(), extra);
}
/**
* @ngdoc function
* @name angular.noop
* @function
*
* @description
* A function that performs no operations. This function can be useful when writing code in the
* functional style.
<pre>
function foo(callback) {
var result = calculateResult();
(callback || angular.noop)(result);
}
</pre>
*/
function noop() {}
noop.$inject = [];
/**
* @ngdoc function
* @name angular.identity
* @function
*
* @description
* A function that returns its first argument. This function is useful when writing code in the
* functional style.
*
<pre>
function transformer(transformationFn, value) {
return (transformationFn || identity)(value);
};
</pre>
*/
function identity($) {
return $;
}
identity.$inject = [];
function valueFn(value) {
return function() {
return value;
};
}
/**
* @ngdoc function
* @name angular.isUndefined
* @function
*
* @description
* Determines if a reference is undefined.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is undefined.
*/
function isUndefined(value) {
return typeof value == 'undefined';
}
/**
* @ngdoc function
* @name angular.isDefined
* @function
*
* @description
* Determines if a reference is defined.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is defined.
*/
function isDefined(value) {
return typeof value != 'undefined';
}
/**
* @ngdoc function
* @name angular.isObject
* @function
*
* @description
* Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
* considered to be objects.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is an `Object` but not `null`.
*/
function isObject(value) {
return value != null && typeof value == 'object';
}
/**
* @ngdoc function
* @name angular.isString
* @function
*
* @description
* Determines if a reference is a `String`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `String`.
*/
function isString(value) {
return typeof value == 'string';
}
/**
* @ngdoc function
* @name angular.isNumber
* @function
*
* @description
* Determines if a reference is a `Number`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Number`.
*/
function isNumber(value) {
return typeof value == 'number';
}
/**
* @ngdoc function
* @name angular.isDate
* @function
*
* @description
* Determines if a value is a date.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Date`.
*/
function isDate(value) {
return toString.apply(value) == '[object Date]';
}
/**
* @ngdoc function
* @name angular.isArray
* @function
*
* @description
* Determines if a reference is an `Array`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is an `Array`.
*/
function isArray(value) {
return toString.apply(value) == '[object Array]';
}
/**
* @ngdoc function
* @name angular.isFunction
* @function
*
* @description
* Determines if a reference is a `Function`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Function`.
*/
function isFunction(value) {
return typeof value == 'function';
}
/**
* Checks if `obj` is a window object.
*
* @private
* @param {*} obj Object to check
* @returns {boolean} True if `obj` is a window obj.
*/
function isWindow(obj) {
return obj && obj.document && obj.location && obj.alert && obj.setInterval;
}
function isScope(obj) {
return obj && obj.$evalAsync && obj.$watch;
}
function isFile(obj) {
return toString.apply(obj) === '[object File]';
}
function isBoolean(value) {
return typeof value == 'boolean';
}
function trim(value) {
return isString(value) ? value.replace(/^\s*/, '').replace(/\s*$/, '') :
value;
}
/**
* @ngdoc function
* @name angular.isElement
* @function
*
* @description
* Determines if a reference is a DOM element (or wrapped jQuery element).
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
*/
function isElement(node) {
return node &&
(node.nodeName // we are a direct element
|| (node.bind && node.find)); // we have a bind and find method part of jQuery API
}
/**
* @param str 'key1,key2,...'
* @returns {object} in the form of {key1:true, key2:true, ...}
*/
function makeMap(str) {
var obj = {}, items = str.split(","),
i;
for (i = 0; i < items.length; i++)
obj[items[i]] = true;
return obj;
}
if (msie < 9) {
nodeName_ = function(element) {
element = element.nodeName ? element : element[0];
return (element.scopeName && element.scopeName != 'HTML') ?
uppercase(element.scopeName + ':' + element.nodeName) : element
.nodeName;
};
} else {
nodeName_ = function(element) {
return element.nodeName ? element.nodeName : element[0].nodeName;
};
}
function map(obj, iterator, context) {
var results = [];
forEach(obj, function(value, index, list) {
results.push(iterator.call(context, value, index, list));
});
return results;
}
/**
* @description
* Determines the number of elements in an array, the number of properties an object has, or
* the length of a string.
*
* Note: This function is used to augment the Object type in Angular expressions. See
* {@link angular.Object} for more information about Angular arrays.
*
* @param {Object|Array|string} obj Object, array, or string to inspect.
* @param {boolean} [ownPropsOnly=false] Count only "own" properties in an object
* @returns {number} The size of `obj` or `0` if `obj` is neither an object nor an array.
*/
function size(obj, ownPropsOnly) {
var size = 0,
key;
if (isArray(obj) || isString(obj)) {
return obj.length;
} else if (isObject(obj)) {
for (key in obj)
if (!ownPropsOnly || obj.hasOwnProperty(key))
size++;
}
return size;
}
function includes(array, obj) {
return indexOf(array, obj) != -1;
}
function indexOf(array, obj) {
if (array.indexOf) return array.indexOf(obj);
for (var i = 0; i < array.length; i++) {
if (obj === array[i]) return i;
}
return -1;
}
function arrayRemove(array, value) {
var index = indexOf(array, value);
if (index >= 0)
array.splice(index, 1);
return value;
}
function isLeafNode(node) {
if (node) {
switch (node.nodeName) {
case "OPTION":
case "PRE":
case "TITLE":
return true;
}
}
return false;
}
/**
* @ngdoc function
* @name angular.copy
* @function
*
* @description
* Creates a deep copy of `source`, which should be an object or an array.
*
* * If no destination is supplied, a copy of the object or array is created.
* * If a destination is provided, all of its elements (for array) or properties (for objects)
* are deleted and then all elements/properties from the source are copied to it.
* * If `source` is not an object or array, `source` is returned.
*
* Note: this function is used to augment the Object type in Angular expressions. See
* {@link ng.$filter} for more information about Angular arrays.
*
* @param {*} source The source that will be used to make a copy.
* Can be any type, including primitives, `null`, and `undefined`.
* @param {(Object|Array)=} destination Destination into which the source is copied. If
* provided, must be of the same type as `source`.
* @returns {*} The copy or updated `destination`, if `destination` was specified.
*/
function copy(source, destination) {
if (isWindow(source) || isScope(source)) throw Error(
"Can't copy Window or Scope");
if (!destination) {
destination = source;
if (source) {
if (isArray(source)) {
destination = copy(source, []);
} else if (isDate(source)) {
destination = new Date(source.getTime());
} else if (isObject(source)) {
destination = copy(source, {});
}
}
} else {
if (source === destination) throw Error(
"Can't copy equivalent objects or arrays");
if (isArray(source)) {
destination.length = 0;
for (var i = 0; i < source.length; i++) {
destination.push(copy(source[i]));
}
} else {
forEach(destination, function(value, key) {
delete destination[key];
});
for (var key in source) {
destination[key] = copy(source[key]);
}
}
}
return destination;
}
/**
* Create a shallow copy of an object
*/
function shallowCopy(src, dst) {
dst = dst || {};
for (var key in src) {
if (src.hasOwnProperty(key) && key.substr(0, 2) !== '$$') {
dst[key] = src[key];
}
}
return dst;
}
/**
* @ngdoc function
* @name angular.equals
* @function
*
* @description
* Determines if two objects or two values are equivalent. Supports value types, arrays and
* objects.
*
* Two objects or values are considered equivalent if at least one of the following is true:
*
* * Both objects or values pass `===` comparison.
* * Both objects or values are of the same type and all of their properties pass `===` comparison.
* * Both values are NaN. (In JavasScript, NaN == NaN => false. But we consider two NaN as equal)
*
* During a property comparision, properties of `function` type and properties with names
* that begin with `$` are ignored.
*
* Scope and DOMWindow objects are being compared only be identify (`===`).
*
* @param {*} o1 Object or value to compare.
* @param {*} o2 Object or value to compare.
* @returns {boolean} True if arguments are equal.
*/
function equals(o1, o2) {
if (o1 === o2) return true;
if (o1 === null || o2 === null) return false;
if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
var t1 = typeof o1,
t2 = typeof o2,
length, key, keySet;
if (t1 == t2) {
if (t1 == 'object') {
if (isArray(o1)) {
if ((length = o1.length) == o2.length) {
for (key = 0; key < length; key++) {
if (!equals(o1[key], o2[key])) return false;
}
return true;
}
} else if (isDate(o1)) {
return isDate(o2) && o1.getTime() == o2.getTime();
} else {
if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(
o2)) return false;
keySet = {};
for (key in o1) {
if (key.charAt(0) === '$' || isFunction(o1[key]))
continue;
if (!equals(o1[key], o2[key])) return false;
keySet[key] = true;
}
for (key in o2) {
if (!keySet[key] &&
key.charAt(0) !== '$' &&
o2[key] !== undefined && !isFunction(o2[key]))
return false;
}
return true;
}
}
}
return false;
}
function concat(array1, array2, index) {
return array1.concat(slice.call(array2, index));
}
function sliceArgs(args, startIndex) {
return slice.call(args, startIndex || 0);
}
/**
* @ngdoc function
* @name angular.bind
* @function
*
* @description
* Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
* `fn`). You can supply optional `args` that are are prebound to the function. This feature is also
* known as [function currying](http://en.wikipedia.org/wiki/Currying).
*
* @param {Object} self Context which `fn` should be evaluated in.
* @param {function()} fn Function to be bound.
* @param {...*} args Optional arguments to be prebound to the `fn` function call.
* @returns {function()} Function that wraps the `fn` with all the specified bindings.
*/
function bind(self, fn) {
var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
if (isFunction(fn) && !(fn instanceof RegExp)) {
return curryArgs.length ? function() {
return arguments.length ? fn.apply(self, curryArgs.concat(slice
.call(arguments, 0))) : fn.apply(self, curryArgs);
} : function() {
return arguments.length ? fn.apply(self, arguments) : fn.call(
self);
};
} else {
// in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
return fn;
}
}
function toJsonReplacer(key, value) {
var val = value;
if (/^\$+/.test(key)) {
val = undefined;
} else if (isWindow(value)) {
val = '$WINDOW';
} else if (value && document === value) {
val = '$DOCUMENT';
} else if (isScope(value)) {
val = '$SCOPE';
}
return val;
}
/**
* @ngdoc function
* @name angular.toJson
* @function
*
* @description
* Serializes input into a JSON-formatted string.
*
* @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
* @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace.
* @returns {string} Jsonified string representing `obj`.
*/
function toJson(obj, pretty) {
return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null);
}
/**
* @ngdoc function
* @name angular.fromJson
* @function
*
* @description
* Deserializes a JSON string.
*
* @param {string} json JSON string to deserialize.
* @returns {Object|Array|Date|string|number} Deserialized thingy.
*/
function fromJson(json) {
return isString(json) ? JSON.parse(json) : json;
}
function toBoolean(value) {
if (value && value.length !== 0) {
var v = lowercase("" + value);
value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v ==
'n' || v == '[]');
} else {
value = false;
}
return value;
}
/**
* @returns {string} Returns the string representation of the element.
*/
function startingTag(element) {
element = jqLite(element).clone();
try {
// turns out IE does not let you set .html() on elements which
// are not allowed to have children. So we just ignore it.
element.html('');
} catch (e) {}
// As Per DOM Standards
var TEXT_NODE = 3;
var elemHtml = jqLite('<div>').append(element).html();
try {
return element[0].nodeType === TEXT_NODE ? lowercase(elemHtml) :
elemHtml.
match(/^(<[^>]+>)/)[1].
replace(/^<([\w\-]+)/, function(match, nodeName) {
return '<' + lowercase(nodeName);
});
} catch (e) {
return lowercase(elemHtml);
}
}
/////////////////////////////////////////////////
/**
* Parses an escaped url query string into key-value pairs.
* @returns Object.<(string|boolean)>
*/
function parseKeyValue( /**string*/ keyValue) {
var obj = {}, key_value, key;
forEach((keyValue || "").split('&'), function(keyValue) {
if (keyValue) {
key_value = keyValue.split('=');
key = decodeURIComponent(key_value[0]);
obj[key] = isDefined(key_value[1]) ? decodeURIComponent(
key_value[1]) : true;
}
});
return obj;
}
function toKeyValue(obj) {
var parts = [];
forEach(obj, function(value, key) {
parts.push(encodeUriQuery(key, true) + (value === true ? '' : '=' +
encodeUriQuery(value, true)));
});
return parts.length ? parts.join('&') : '';
}
/**
* We need our custom method because encodeURIComponent is too agressive and doesn't follow
* http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
* segments:
* segment = *pchar
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* pct-encoded = "%" HEXDIG HEXDIG
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*/
function encodeUriSegment(val) {
return encodeUriQuery(val, true).
replace(/%26/gi, '&').
replace(/%3D/gi, '=').
replace(/%2B/gi, '+');
}
/**
* This method is intended for encoding *key* or *value* parts of query component. We need a custom
* method becuase encodeURIComponent is too agressive and encodes stuff that doesn't have to be
* encoded per http://tools.ietf.org/html/rfc3986:
* query = *( pchar / "/" / "?" )
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* pct-encoded = "%" HEXDIG HEXDIG
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*/
function encodeUriQuery(val, pctEncodeSpaces) {
return encodeURIComponent(val).
replace(/%40/gi, '@').
replace(/%3A/gi, ':').
replace(/%24/g, '$').
replace(/%2C/gi, ',').
replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
}
/**
* @ngdoc directive
* @name ng.directive:ngApp
*
* @element ANY
* @param {angular.Module} ngApp an optional application
* {@link angular.module module} name to load.
*
* @description
*
* Use this directive to auto-bootstrap on application. Only
* one directive can be used per HTML document. The directive
* designates the root of the application and is typically placed
* at the root of the page.
*
* In the example below if the `ngApp` directive would not be placed
* on the `html` element then the document would not be compiled
* and the `{{ 1+2 }}` would not be resolved to `3`.
*
* `ngApp` is the easiest way to bootstrap an application.
*
<doc:example>
<doc:source>
I can add: 1 + 2 = {{ 1+2 }}
</doc:source>
</doc:example>
*
*/
function angularInit(element, bootstrap) {
var elements = [element],
appElement,
module,
names = ['ng:app', 'ng-app', 'x-ng-app', 'data-ng-app'],
NG_APP_CLASS_REGEXP = /\sng[:\-]app(:\s*([\w\d_]+);?)?\s/;
function append(element) {
element && elements.push(element);
}
forEach(names, function(name) {
names[name] = true;
append(document.getElementById(name));
name = name.replace(':', '\\:');
if (element.querySelectorAll) {
forEach(element.querySelectorAll('.' + name), append);
forEach(element.querySelectorAll('.' + name + '\\:'), append);
forEach(element.querySelectorAll('[' + name + ']'), append);
}
});
forEach(elements, function(element) {
if (!appElement) {
var className = ' ' + element.className + ' ';
var match = NG_APP_CLASS_REGEXP.exec(className);
if (match) {
appElement = element;
module = (match[2] || '').replace(/\s+/g, ',');
} else {
forEach(element.attributes, function(attr) {
if (!appElement && names[attr.name]) {
appElement = element;
module = attr.value;
}
});
}
}
});
if (appElement) {
bootstrap(appElement, module ? [module] : []);
}
}
/**
* @ngdoc function
* @name angular.bootstrap
* @description
* Use this function to manually start up angular application.
*
* See: {@link guide/bootstrap Bootstrap}
*
* @param {Element} element DOM element which is the root of angular application.
* @param {Array<String|Function>=} modules an array of module declarations. See: {@link angular.module modules}
* @returns {AUTO.$injector} Returns the newly created injector for this app.
*/
function bootstrap(element, modules) {
var resumeBootstrapInternal = function() {
element = jqLite(element);
modules = modules || [];
modules.unshift(['$provide',
function($provide) {
$provide.value('$rootElement', element);
}
]);
modules.unshift('ng');
var injector = createInjector(modules);
injector.invoke(['$rootScope', '$rootElement', '$compile',
'$injector',
function(scope, element, compile, injector) {
scope.$apply(function() {
element.data('$injector', injector);
compile(element)(scope);
});
}
]);
return injector;
};
var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
return resumeBootstrapInternal();
}
window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
angular.resumeBootstrap = function(extraModules) {
forEach(extraModules, function(module) {
modules.push(module);
});
resumeBootstrapInternal();
};
}
var SNAKE_CASE_REGEXP = /[A-Z]/g;
function snake_case(name, separator) {
separator = separator || '_';
return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
return (pos ? separator : '') + letter.toLowerCase();
});
}
function bindJQuery() {
// bind to jQuery if present;
jQuery = window.jQuery;
// reset to jQuery or default to us.
if (jQuery) {
jqLite = jQuery;
extend(jQuery.fn, {
scope: JQLitePrototype.scope,
controller: JQLitePrototype.controller,
injector: JQLitePrototype.injector,
inheritedData: JQLitePrototype.inheritedData
});
JQLitePatchJQueryRemove('remove', true);
JQLitePatchJQueryRemove('empty');
JQLitePatchJQueryRemove('html');
} else {
jqLite = JQLite;
}
angular.element = jqLite;
}
/**
* throw error of the argument is falsy.
*/
function assertArg(arg, name, reason) {
if (!arg) {
throw new Error("Argument '" + (name || '?') + "' is " + (reason ||
"required"));
}
return arg;
}
function assertArgFn(arg, name, acceptArrayAnnotation) {
if (acceptArrayAnnotation && isArray(arg)) {
arg = arg[arg.length - 1];
}
assertArg(isFunction(arg), name, 'not a function, got ' +
(arg && typeof arg == 'object' ? arg.constructor.name || 'Object' :
typeof arg));
return arg;
}
/**
* @ngdoc interface
* @name angular.Module
* @description
*
* Interface for configuring angular {@link angular.module modules}.
*/
function setupModuleLoader(window) {
function ensure(obj, name, factory) {
return obj[name] || (obj[name] = factory());
}
return ensure(ensure(window, 'angular', Object), 'module', function() {
/** @type {Object.<string, angular.Module>} */
var modules = {};
/**
* @ngdoc function
* @name angular.module
* @description
*
* The `angular.module` is a global place for creating and registering Angular modules. All
* modules (angular core or 3rd party) that should be available to an application must be
* registered using this mechanism.
*
*
* # Module
*
* A module is a collocation of services, directives, filters, and configuration information. Module
* is used to configure the {@link AUTO.$injector $injector}.
*
* <pre>
* // Create a new module
* var myModule = angular.module('myModule', []);
*
* // register a new service
* myModule.value('appName', 'MyCoolApp');
*
* // configure existing services inside initialization blocks.
* myModule.config(function($locationProvider) {
* // Configure existing providers
* $locationProvider.hashPrefix('!');
* });
* </pre>
*
* Then you can create an injector and load your modules like this:
*
* <pre>
* var injector = angular.injector(['ng', 'MyModule'])
* </pre>
*
* However it's more likely that you'll just use
* {@link ng.directive:ngApp ngApp} or
* {@link angular.bootstrap} to simplify this process for you.
*
* @param {!string} name The name of the module to create or retrieve.
* @param {Array.<string>=} requires If specified then new module is being created. If unspecified then the
* the module is being retrieved for further configuration.
* @param {Function} configFn Optional configuration function for the module. Same as
* {@link angular.Module#config Module#config()}.
* @returns {module} new module with the {@link angular.Module} api.
*/
return function module(name, requires, configFn) {
if (requires && modules.hasOwnProperty(name)) {
modules[name] = null;
}
return ensure(modules, name, function() {
if (!requires) {
throw Error('No module: ' + name);
}
/** @type {!Array.<Array.<*>>} */
var invokeQueue = [];
/** @type {!Array.<Function>} */
var runBlocks = [];
var config = invokeLater('$injector', 'invoke');
/** @type {angular.Module} */
var moduleInstance = {
// Private state
_invokeQueue: invokeQueue,
_runBlocks: runBlocks,
/**
* @ngdoc property
* @name angular.Module#requires
* @propertyOf angular.Module
* @returns {Array.<string>} List of module names which must be loaded before this module.
* @description
* Holds the list of modules which the injector will load before the current module is loaded.
*/
requires: requires,
/**
* @ngdoc property
* @name angular.Module#name
* @propertyOf angular.Module
* @returns {string} Name of the module.
* @description
*/
name: name,
/**
* @ngdoc method
* @name angular.Module#provider
* @methodOf angular.Module
* @param {string} name service name
* @param {Function} providerType Construction function for creating new instance of the service.
* @description
* See {@link AUTO.$provide#provider $provide.provider()}.
*/
provider: invokeLater('$provide', 'provider'),
/**
* @ngdoc method
* @name angular.Module#factory
* @methodOf angular.Module
* @param {string} name service name
* @param {Function} providerFunction Function for creating new instance of the service.
* @description
* See {@link AUTO.$provide#factory $provide.factory()}.
*/
factory: invokeLater('$provide', 'factory'),
/**
* @ngdoc method
* @name angular.Module#service
* @methodOf angular.Module
* @param {string} name service name
* @param {Function} constructor A constructor function that will be instantiated.
* @description
* See {@link AUTO.$provide#service $provide.service()}.
*/
service: invokeLater('$provide', 'service'),
/**
* @ngdoc method
* @name angular.Module#value
* @methodOf angular.Module
* @param {string} name service name
* @param {*} object Service instance object.
* @description
* See {@link AUTO.$provide#value $provide.value()}.
*/
value: invokeLater('$provide', 'value'),
/**
* @ngdoc method
* @name angular.Module#constant
* @methodOf angular.Module
* @param {string} name constant name
* @param {*} object Constant value.
* @description
* Because the constant are fixed, they get applied before other provide methods.
* See {@link AUTO.$provide#constant $provide.constant()}.
*/
constant: invokeLater('$provide', 'constant', 'unshift'),
/**
* @ngdoc method
* @name angular.Module#filter
* @methodOf angular.Module
* @param {string} name Filter name.
* @param {Function} filterFactory Factory function for creating new instance of filter.
* @description
* See {@link ng.$filterProvider#register $filterProvider.register()}.
*/
filter: invokeLater('$filterProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#controller
* @methodOf angular.Module
* @param {string} name Controller name.
* @param {Function} constructor Controller constructor function.
* @description
* See {@link ng.$controllerProvider#register $controllerProvider.register()}.
*/
controller: invokeLater('$controllerProvider',
'register'),
/**
* @ngdoc method
* @name angular.Module#directive
* @methodOf angular.Module
* @param {string} name directive name
* @param {Function} directiveFactory Factory function for creating new instance of
* directives.
* @description
* See {@link ng.$compileProvider#directive $compileProvider.directive()}.
*/
directive: invokeLater('$compileProvider', 'directive'),
/**
* @ngdoc method
* @name angular.Module#config
* @methodOf angular.Module
* @param {Function} configFn Execute this function on module load. Useful for service
* configuration.
* @description
* Use this method to register work which needs to be performed on module loading.
*/
config: config,
/**
* @ngdoc method
* @name angular.Module#run
* @methodOf angular.Module
* @param {Function} initializationFn Execute this function after injector creation.
* Useful for application initialization.
* @description
* Use this method to register work which should be performed when the injector is done
* loading all modules.
*/
run: function(block) {
runBlocks.push(block);
return this;
}
};
if (configFn) {
config(configFn);
}
return moduleInstance;
/**
* @param {string} provider
* @param {string} method
* @param {String=} insertMethod
* @returns {angular.Module}
*/
function invokeLater(provider, method, insertMethod) {
return function() {
invokeQueue[insertMethod || 'push']([provider,
method, arguments
]);
return moduleInstance;
}
}
});
};
});
}
/**
* @ngdoc property
* @name angular.version
* @description
* An object that contains information about the current AngularJS version. This object has the
* following properties:
*
* - `full` – `{string}` – Full version string, such as "0.9.18".
* - `major` – `{number}` – Major version number, such as "0".
* - `minor` – `{number}` – Minor version number, such as "9".
* - `dot` – `{number}` – Dot version number, such as "18".
* - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
*/
var version = {
full: '1.0.6', // all of these placeholder strings will be replaced by grunt's
major: 1, // package task
minor: 0,
dot: 6,
codeName: 'universal-irreversibility'
};
function publishExternalAPI(angular) {
extend(angular, {
'bootstrap': bootstrap,
'copy': copy,
'extend': extend,
'equals': equals,
'element': jqLite,
'forEach': forEach,
'injector': createInjector,
'noop': noop,
'bind': bind,
'toJson': toJson,
'fromJson': fromJson,
'identity': identity,
'isUndefined': isUndefined,
'isDefined': isDefined,
'isString': isString,
'isFunction': isFunction,
'isObject': isObject,
'isNumber': isNumber,
'isElement': isElement,
'isArray': isArray,
'version': version,
'isDate': isDate,
'lowercase': lowercase,
'uppercase': uppercase,
'callbacks': {
counter: 0
}
});
angularModule = setupModuleLoader(window);
try {
angularModule('ngLocale');
} catch (e) {
angularModule('ngLocale', []).provider('$locale', $LocaleProvider);
}
angularModule('ng', ['ngLocale'], ['$provide',
function ngModule($provide) {
$provide.provider('$compile', $CompileProvider).
directive({
a: htmlAnchorDirective,
input: inputDirective,
textarea: inputDirective,
form: formDirective,
script: scriptDirective,
select: selectDirective,
style: styleDirective,
option: optionDirective,
ngBind: ngBindDirective,
ngBindHtmlUnsafe: ngBindHtmlUnsafeDirective,
ngBindTemplate: ngBindTemplateDirective,
ngClass: ngClassDirective,
ngClassEven: ngClassEvenDirective,
ngClassOdd: ngClassOddDirective,
ngCsp: ngCspDirective,
ngCloak: ngCloakDirective,
ngController: ngControllerDirective,
ngForm: ngFormDirective,
ngHide: ngHideDirective,
ngInclude: ngIncludeDirective,
ngInit: ngInitDirective,
ngNonBindable: ngNonBindableDirective,
ngPluralize: ngPluralizeDirective,
ngRepeat: ngRepeatDirective,
ngShow: ngShowDirective,
ngSubmit: ngSubmitDirective,
ngStyle: ngStyleDirective,
ngSwitch: ngSwitchDirective,
ngSwitchWhen: ngSwitchWhenDirective,
ngSwitchDefault: ngSwitchDefaultDirective,
ngOptions: ngOptionsDirective,
ngView: ngViewDirective,
ngTransclude: ngTranscludeDirective,
ngModel: ngModelDirective,
ngList: ngListDirective,
ngChange: ngChangeDirective,
required: requiredDirective,
ngRequired: requiredDirective,
ngValue: ngValueDirective
}).
directive(ngAttributeAliasDirectives).
directive(ngEventDirectives);
$provide.provider({
$anchorScroll: $AnchorScrollProvider,
$browser: $BrowserProvider,
$cacheFactory: $CacheFactoryProvider,
$controller: $ControllerProvider,
$document: $DocumentProvider,
$exceptionHandler: $ExceptionHandlerProvider,
$filter: $FilterProvider,
$interpolate: $InterpolateProvider,
$http: $HttpProvider,
$httpBackend: $HttpBackendProvider,
$location: $LocationProvider,
$log: $LogProvider,
$parse: $ParseProvider,
$route: $RouteProvider,
$routeParams: $RouteParamsProvider,
$rootScope: $RootScopeProvider,
$q: $QProvider,
$sniffer: $SnifferProvider,
$templateCache: $TemplateCacheProvider,
$timeout: $TimeoutProvider,
$window: $WindowProvider
});
}
]);
}
//////////////////////////////////
//JQLite
//////////////////////////////////
/**
* @ngdoc function
* @name angular.element
* @function
*
* @description
* Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
* `angular.element` can be either an alias for [jQuery](http://api.jquery.com/jQuery/) function, if
* jQuery is available, or a function that wraps the element or string in Angular's jQuery lite
* implementation (commonly referred to as jqLite).
*
* Real jQuery always takes precedence over jqLite, provided it was loaded before `DOMContentLoaded`
* event fired.
*
* jqLite is a tiny, API-compatible subset of jQuery that allows
* Angular to manipulate the DOM. jqLite implements only the most commonly needed functionality
* within a very small footprint, so only a subset of the jQuery API - methods, arguments and
* invocation styles - are supported.
*
* Note: All element references in Angular are always wrapped with jQuery or jqLite; they are never
* raw DOM references.
*
* ## Angular's jQuery lite provides the following methods:
*
* - [addClass()](http://api.jquery.com/addClass/)
* - [after()](http://api.jquery.com/after/)
* - [append()](http://api.jquery.com/append/)
* - [attr()](http://api.jquery.com/attr/)
* - [bind()](http://api.jquery.com/bind/)
* - [children()](http://api.jquery.com/children/)
* - [clone()](http://api.jquery.com/clone/)
* - [contents()](http://api.jquery.com/contents/)
* - [css()](http://api.jquery.com/css/)
* - [data()](http://api.jquery.com/data/)
* - [eq()](http://api.jquery.com/eq/)
* - [find()](http://api.jquery.com/find/) - Limited to lookups by tag name.
* - [hasClass()](http://api.jquery.com/hasClass/)
* - [html()](http://api.jquery.com/html/)
* - [next()](http://api.jquery.com/next/)
* - [parent()](http://api.jquery.com/parent/)
* - [prepend()](http://api.jquery.com/prepend/)
* - [prop()](http://api.jquery.com/prop/)
* - [ready()](http://api.jquery.com/ready/)
* - [remove()](http://api.jquery.com/remove/)
* - [removeAttr()](http://api.jquery.com/removeAttr/)
* - [removeClass()](http://api.jquery.com/removeClass/)
* - [removeData()](http://api.jquery.com/removeData/)
* - [replaceWith()](http://api.jquery.com/replaceWith/)
* - [text()](http://api.jquery.com/text/)
* - [toggleClass()](http://api.jquery.com/toggleClass/)
* - [triggerHandler()](http://api.jquery.com/triggerHandler/) - Doesn't pass native event objects to handlers.
* - [unbind()](http://api.jquery.com/unbind/)
* - [val()](http://api.jquery.com/val/)
* - [wrap()](http://api.jquery.com/wrap/)
*
* ## In addtion to the above, Angular provides additional methods to both jQuery and jQuery lite:
*
* - `controller(name)` - retrieves the controller of the current element or its parent. By default
* retrieves controller associated with the `ngController` directive. If `name` is provided as
* camelCase directive name, then the controller for this directive will be retrieved (e.g.
* `'ngModel'`).
* - `injector()` - retrieves the injector of the current element or its parent.
* - `scope()` - retrieves the {@link api/ng.$rootScope.Scope scope} of the current
* element or its parent.
* - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
* parent element is reached.
*
* @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
* @returns {Object} jQuery object.
*/
var jqCache = JQLite.cache = {},
jqName = JQLite.expando = 'ng-' + new Date().getTime(),
jqId = 1,
addEventListenerFn = (window.document.addEventListener ? function(
element, type, fn) {
element.addEventListener(type, fn, false);
} : function(element, type, fn) {
element.attachEvent('on' + type, fn);
}),
removeEventListenerFn = (window.document.removeEventListener ? function(
element, type, fn) {
element.removeEventListener(type, fn, false);
} : function(element, type, fn) {
element.detachEvent('on' + type, fn);
});
function jqNextId() {
return ++jqId;
}
var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
var MOZ_HACK_REGEXP = /^moz([A-Z])/;
/**
* Converts snake_case to camelCase.
* Also there is special case for Moz prefix starting with upper case letter.
* @param name Name to normalize
*/
function camelCase(name) {
return name.
replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
return offset ? letter.toUpperCase() : letter;
}).
replace(MOZ_HACK_REGEXP, 'Moz$1');
}
/////////////////////////////////////////////
// jQuery mutation patch
//
// In conjunction with bindJQuery intercepts all jQuery's DOM destruction apis and fires a
// $destroy event on all DOM nodes being removed.
//
/////////////////////////////////////////////
function JQLitePatchJQueryRemove(name, dispatchThis) {
var originalJqFn = jQuery.fn[name];
originalJqFn = originalJqFn.$original || originalJqFn;
removePatch.$original = originalJqFn;
jQuery.fn[name] = removePatch;
function removePatch() {
var list = [this],
fireEvent = dispatchThis,
set, setIndex, setLength,
element, childIndex, childLength, children,
fns, events;
while (list.length) {
set = list.shift();
for (setIndex = 0, setLength = set.length; setIndex < setLength; setIndex++) {
element = jqLite(set[setIndex]);
if (fireEvent) {
element.triggerHandler('$destroy');
} else {
fireEvent = !fireEvent;
}
for (childIndex = 0, childLength = (children = element.children())
.length; childIndex < childLength; childIndex++) {
list.push(jQuery(children[childIndex]));
}
}
}
return originalJqFn.apply(this, arguments);
}
}
/////////////////////////////////////////////
function JQLite(element) {
if (element instanceof JQLite) {
return element;
}
if (!(this instanceof JQLite)) {
if (isString(element) && element.charAt(0) != '<') {
throw Error('selectors not implemented');
}
return new JQLite(element);
}
if (isString(element)) {
var div = document.createElement('div');
// Read about the NoScope elements here:
// http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx
div.innerHTML = '<div> </div>' + element; // IE insanity to make NoScope elements work!
div.removeChild(div.firstChild); // remove the superfluous div
JQLiteAddNodes(this, div.childNodes);
this.remove(); // detach the elements from the temporary DOM div.
} else {
JQLiteAddNodes(this, element);
}
}
function JQLiteClone(element) {
return element.cloneNode(true);
}
function JQLiteDealoc(element) {
JQLiteRemoveData(element);
for (var i = 0, children = element.childNodes || []; i < children.length; i++) {
JQLiteDealoc(children[i]);
}
}
function JQLiteUnbind(element, type, fn) {
var events = JQLiteExpandoStore(element, 'events'),
handle = JQLiteExpandoStore(element, 'handle');
if (!handle) return; //no listeners registered
if (isUndefined(type)) {
forEach(events, function(eventHandler, type) {
removeEventListenerFn(element, type, eventHandler);
delete events[type];
});
} else {
if (isUndefined(fn)) {
removeEventListenerFn(element, type, events[type]);
delete events[type];
} else {
arrayRemove(events[type], fn);
}
}
}
function JQLiteRemoveData(element) {
var expandoId = element[jqName],
expandoStore = jqCache[expandoId];
if (expandoStore) {
if (expandoStore.handle) {
expandoStore.events.$destroy && expandoStore.handle({},
'$destroy');
JQLiteUnbind(element);
}
delete jqCache[expandoId];
element[jqName] = undefined; // ie does not allow deletion of attributes on elements.
}
}
function JQLiteExpandoStore(element, key, value) {
var expandoId = element[jqName],
expandoStore = jqCache[expandoId || -1];
if (isDefined(value)) {
if (!expandoStore) {
element[jqName] = expandoId = jqNextId();
expandoStore = jqCache[expandoId] = {};
}
expandoStore[key] = value;
} else {
return expandoStore && expandoStore[key];
}
}
function JQLiteData(element, key, value) {
var data = JQLiteExpandoStore(element, 'data'),
isSetter = isDefined(value),
keyDefined = !isSetter && isDefined(key),
isSimpleGetter = keyDefined && !isObject(key);
if (!data && !isSimpleGetter) {
JQLiteExpandoStore(element, 'data', data = {});
}
if (isSetter) {
data[key] = value;
} else {
if (keyDefined) {
if (isSimpleGetter) {
// don't create data in this case.
return data && data[key];
} else {
extend(data, key);
}
} else {
return data;
}
}
}
function JQLiteHasClass(element, selector) {
return ((" " + element.className + " ").replace(/[\n\t]/g, " ").indexOf(
" " + selector + " ") > -1);
}
function JQLiteRemoveClass(element, cssClasses) {
if (cssClasses) {
forEach(cssClasses.split(' '), function(cssClass) {
element.className = trim(
(" " + element.className + " ")
.replace(/[\n\t]/g, " ")
.replace(" " + trim(cssClass) + " ", " "));
});
}
}
function JQLiteAddClass(element, cssClasses) {
if (cssClasses) {
forEach(cssClasses.split(' '), function(cssClass) {
if (!JQLiteHasClass(element, cssClass)) {
element.className = trim(element.className + ' ' + trim(
cssClass));
}
});
}
}
function JQLiteAddNodes(root, elements) {
if (elements) {
elements = (!elements.nodeName && isDefined(elements.length) && !
isWindow(elements)) ? elements : [elements];
for (var i = 0; i < elements.length; i++) {
root.push(elements[i]);
}
}
}
function JQLiteController(element, name) {
return JQLiteInheritedData(element, '$' + (name || 'ngController') +
'Controller');
}
function JQLiteInheritedData(element, name, value) {
element = jqLite(element);
// if element is the document object work with the html element instead
// this makes $(document).scope() possible
if (element[0].nodeType == 9) {
element = element.find('html');
}
while (element.length) {
if (value = element.data(name)) return value;
element = element.parent();
}
}
//////////////////////////////////////////
// Functions which are declared directly.
//////////////////////////////////////////
var JQLitePrototype = JQLite.prototype = {
ready: function(fn) {
var fired = false;
function trigger() {
if (fired) return;
fired = true;
fn();
}
this.bind('DOMContentLoaded', trigger); // works for modern browsers and IE9
// we can not use jqLite since we are not done loading and jQuery could be loaded later.
JQLite(window).bind('load', trigger); // fallback to window.onload for others
},
toString: function() {
var value = [];
forEach(this, function(e) {
value.push('' + e);
});
return '[' + value.join(', ') + ']';
},
eq: function(index) {
return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length +
index]);
},
length: 0,
push: push,
sort: [].sort,
splice: [].splice
};
//////////////////////////////////////////
// Functions iterating getter/setters.
// these functions return self on setter and
// value on get.
//////////////////////////////////////////
var BOOLEAN_ATTR = {};
forEach('multiple,selected,checked,disabled,readOnly,required'.split(','), function(
value) {
BOOLEAN_ATTR[lowercase(value)] = value;
});
var BOOLEAN_ELEMENTS = {};
forEach('input,select,option,textarea,button,form'.split(','), function(
value) {
BOOLEAN_ELEMENTS[uppercase(value)] = true;
});
function getBooleanAttrName(element, name) {
// check dom last since we will most likely fail on name
var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
// booleanAttr is here twice to minimize DOM access
return booleanAttr && BOOLEAN_ELEMENTS[element.nodeName] && booleanAttr;
}
forEach({
data: JQLiteData,
inheritedData: JQLiteInheritedData,
scope: function(element) {
return JQLiteInheritedData(element, '$scope');
},
controller: JQLiteController,
injector: function(element) {
return JQLiteInheritedData(element, '$injector');
},
removeAttr: function(element, name) {
element.removeAttribute(name);
},
hasClass: JQLiteHasClass,
css: function(element, name, value) {
name = camelCase(name);
if (isDefined(value)) {
element.style[name] = value;
} else {
var val;
if (msie <= 8) {
// this is some IE specific weirdness that jQuery 1.6.4 does not sure why
val = element.currentStyle && element.currentStyle[name];
if (val === '') val = 'auto';
}
val = val || element.style[name];
if (msie <= 8) {
// jquery weirdness :-/
val = (val === '') ? undefined : val;
}
return val;
}
},
attr: function(element, name, value) {
var lowercasedName = lowercase(name);
if (BOOLEAN_ATTR[lowercasedName]) {
if (isDefined(value)) {
if ( !! value) {
element[name] = true;
element.setAttribute(name, lowercasedName);
} else {
element[name] = false;
element.removeAttribute(lowercasedName);
}
} else {
return (element[name] ||
(element.attributes.getNamedItem(name) || noop).specified) ?
lowercasedName : undefined;
}
} else if (isDefined(value)) {
element.setAttribute(name, value);
} else if (element.getAttribute) {
// the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
// some elements (e.g. Document) don't have get attribute, so return undefined
var ret = element.getAttribute(name, 2);
// normalize non-existing attributes to undefined (as jQuery)
return ret === null ? undefined : ret;
}
},
prop: function(element, name, value) {
if (isDefined(value)) {
element[name] = value;
} else {
return element[name];
}
},
text: extend((msie < 9) ? function(element, value) {
if (element.nodeType == 1 /** Element */ ) {
if (isUndefined(value))
return element.innerText;
element.innerText = value;
} else {
if (isUndefined(value))
return element.nodeValue;
element.nodeValue = value;
}
} : function(element, value) {
if (isUndefined(value)) {
return element.textContent;
}
element.textContent = value;
}, {
$dv: ''
}),
val: function(element, value) {
if (isUndefined(value)) {
return element.value;
}
element.value = value;
},
html: function(element, value) {
if (isUndefined(value)) {
return element.innerHTML;
}
for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) {
JQLiteDealoc(childNodes[i]);
}
element.innerHTML = value;
}
}, function(fn, name) {
/**
* Properties: writes return selection, reads return first value
*/
JQLite.prototype[name] = function(arg1, arg2) {
var i, key;
// JQLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
// in a way that survives minification.
if (((fn.length == 2 && (fn !== JQLiteHasClass && fn !==
JQLiteController)) ? arg1 : arg2) === undefined) {
if (isObject(arg1)) {
// we are a write, but the object properties are the key/values
for (i = 0; i < this.length; i++) {
if (fn === JQLiteData) {
// data() takes the whole object in jQuery
fn(this[i], arg1);
} else {
for (key in arg1) {
fn(this[i], key, arg1[key]);
}
}
}
// return self for chaining
return this;
} else {
// we are a read, so read the first child.
if (this.length)
return fn(this[0], arg1, arg2);
}
} else {
// we are a write, so apply to all children
for (i = 0; i < this.length; i++) {
fn(this[i], arg1, arg2);
}
// return self for chaining
return this;
}
return fn.$dv;
};
});
function createEventHandler(element, events) {
var eventHandler = function(event, type) {
if (!event.preventDefault) {
event.preventDefault = function() {
event.returnValue = false; //ie
};
}
if (!event.stopPropagation) {
event.stopPropagation = function() {
event.cancelBubble = true; //ie
};
}
if (!event.target) {
event.target = event.srcElement || document;
}
if (isUndefined(event.defaultPrevented)) {
var prevent = event.preventDefault;
event.preventDefault = function() {
event.defaultPrevented = true;
prevent.call(event);
};
event.defaultPrevented = false;
}
event.isDefaultPrevented = function() {
return event.defaultPrevented;
};
forEach(events[type || event.type], function(fn) {
fn.call(element, event);
});
// Remove monkey-patched methods (IE),
// as they would cause memory leaks in IE8.
if (msie <= 8) {
// IE7/8 does not allow to delete property on native object
event.preventDefault = null;
event.stopPropagation = null;
event.isDefaultPrevented = null;
} else {
// It shouldn't affect normal browsers (native methods are defined on prototype).
delete event.preventDefault;
delete event.stopPropagation;
delete event.isDefaultPrevented;
}
};
eventHandler.elem = element;
return eventHandler;
}
//////////////////////////////////////////
// Functions iterating traversal.
// These functions chain results into a single
// selector.
//////////////////////////////////////////
forEach({
removeData: JQLiteRemoveData,
dealoc: JQLiteDealoc,
bind: function bindFn(element, type, fn) {
var events = JQLiteExpandoStore(element, 'events'),
handle = JQLiteExpandoStore(element, 'handle');
if (!events) JQLiteExpandoStore(element, 'events', events = {});
if (!handle) JQLiteExpandoStore(element, 'handle', handle =
createEventHandler(element, events));
forEach(type.split(' '), function(type) {
var eventFns = events[type];
if (!eventFns) {
if (type == 'mouseenter' || type == 'mouseleave') {
var counter = 0;
events.mouseenter = [];
events.mouseleave = [];
bindFn(element, 'mouseover', function(event) {
counter++;
if (counter == 1) {
handle(event, 'mouseenter');
}
});
bindFn(element, 'mouseout', function(event) {
counter--;
if (counter == 0) {
handle(event, 'mouseleave');
}
});
} else {
addEventListenerFn(element, type, handle);
events[type] = [];
}
eventFns = events[type]
}
eventFns.push(fn);
});
},
unbind: JQLiteUnbind,
replaceWith: function(element, replaceNode) {
var index, parent = element.parentNode;
JQLiteDealoc(element);
forEach(new JQLite(replaceNode), function(node) {
if (index) {
parent.insertBefore(node, index.nextSibling);
} else {
parent.replaceChild(node, element);
}
index = node;
});
},
children: function(element) {
var children = [];
forEach(element.childNodes, function(element) {
if (element.nodeType === 1)
children.push(element);
});
return children;
},
contents: function(element) {
return element.childNodes || [];
},
append: function(element, node) {
forEach(new JQLite(node), function(child) {
if (element.nodeType === 1)
element.appendChild(child);
});
},
prepend: function(element, node) {
if (element.nodeType === 1) {
var index = element.firstChild;
forEach(new JQLite(node), function(child) {
if (index) {
element.insertBefore(child, index);
} else {
element.appendChild(child);
index = child;
}
});
}
},
wrap: function(element, wrapNode) {
wrapNode = jqLite(wrapNode)[0];
var parent = element.parentNode;
if (parent) {
parent.replaceChild(wrapNode, element);
}
wrapNode.appendChild(element);
},
remove: function(element) {
JQLiteDealoc(element);
var parent = element.parentNode;
if (parent) parent.removeChild(element);
},
after: function(element, newElement) {
var index = element,
parent = element.parentNode;
forEach(new JQLite(newElement), function(node) {
parent.insertBefore(node, index.nextSibling);
index = node;
});
},
addClass: JQLiteAddClass,
removeClass: JQLiteRemoveClass,
toggleClass: function(element, selector, condition) {
if (isUndefined(condition)) {
condition = !JQLiteHasClass(element, selector);
}
(condition ? JQLiteAddClass : JQLiteRemoveClass)(element, selector);
},
parent: function(element) {
var parent = element.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
next: function(element) {
if (element.nextElementSibling) {
return element.nextElementSibling;
}
// IE8 doesn't have nextElementSibling
var elm = element.nextSibling;
while (elm != null && elm.nodeType !== 1) {
elm = elm.nextSibling;
}
return elm;
},
find: function(element, selector) {
return element.getElementsByTagName(selector);
},
clone: JQLiteClone,
triggerHandler: function(element, eventName) {
var eventFns = (JQLiteExpandoStore(element, 'events') || {})[
eventName];
forEach(eventFns, function(fn) {
fn.call(element, null);
});
}
}, function(fn, name) {
/**
* chaining functions
*/
JQLite.prototype[name] = function(arg1, arg2) {
var value;
for (var i = 0; i < this.length; i++) {
if (value == undefined) {
value = fn(this[i], arg1, arg2);
if (value !== undefined) {
// any function which returns a value needs to be wrapped
value = jqLite(value);
}
} else {
JQLiteAddNodes(value, fn(this[i], arg1, arg2));
}
}
return value == undefined ? this : value;
};
});
/**
* Computes a hash of an 'obj'.
* Hash of a:
* string is string
* number is number as string
* object is either result of calling $$hashKey function on the object or uniquely generated id,
* that is also assigned to the $$hashKey property of the object.
*
* @param obj
* @returns {string} hash string such that the same input will have the same hash string.
* The resulting string key is in 'type:hashKey' format.
*/
function hashKey(obj) {
var objType = typeof obj,
key;
if (objType == 'object' && obj !== null) {
if (typeof(key = obj.$$hashKey) == 'function') {
// must invoke on object to keep the right this
key = obj.$$hashKey();
} else if (key === undefined) {
key = obj.$$hashKey = nextUid();
}
} else {
key = obj;
}
return objType + ':' + key;
}
/**
* HashMap which can use objects as keys
*/
function HashMap(array) {
forEach(array, this.put, this);
}
HashMap.prototype = {
/**
* Store key value pair
* @param key key to store can be any type
* @param value value to store can be any type
*/
put: function(key, value) {
this[hashKey(key)] = value;
},
/**
* @param key
* @returns the value for the key
*/
get: function(key) {
return this[hashKey(key)];
},
/**
* Remove the key/value pair
* @param key
*/
remove: function(key) {
var value = this[key = hashKey(key)];
delete this[key];
return value;
}
};
/**
* A map where multiple values can be added to the same key such that they form a queue.
* @returns {HashQueueMap}
*/
function HashQueueMap() {}
HashQueueMap.prototype = {
/**
* Same as array push, but using an array as the value for the hash
*/
push: function(key, value) {
var array = this[key = hashKey(key)];
if (!array) {
this[key] = [value];
} else {
array.push(value);
}
},
/**
* Same as array shift, but using an array as the value for the hash
*/
shift: function(key) {
var array = this[key = hashKey(key)];
if (array) {
if (array.length == 1) {
delete this[key];
return array[0];
} else {
return array.shift();
}
}
},
/**
* return the first item without deleting it
*/
peek: function(key) {
var array = this[hashKey(key)];
if (array) {
return array[0];
}
}
};
/**
* @ngdoc function
* @name angular.injector
* @function
*
* @description
* Creates an injector function that can be used for retrieving services as well as for
* dependency injection (see {@link guide/di dependency injection}).
*
* @param {Array.<string|Function>} modules A list of module functions or their aliases. See
* {@link angular.module}. The `ng` module must be explicitly added.
* @returns {function()} Injector function. See {@link AUTO.$injector $injector}.
*
* @example
* Typical usage
* <pre>
* // create an injector
* var $injector = angular.injector(['ng']);
*
* // use the injector to kick off your application
* // use the type inference to auto inject arguments, or use implicit injection
* $injector.invoke(function($rootScope, $compile, $document){
* $compile($document)($rootScope);
* $rootScope.$digest();
* });
* </pre>
*/
/**
* @ngdoc overview
* @name AUTO
* @description
*
* Implicit module which gets automatically added to each {@link AUTO.$injector $injector}.
*/
var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
var FN_ARG_SPLIT = /,/;
var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
function annotate(fn) {
var $inject,
fnText,
argDecl,
last;
if (typeof fn == 'function') {
if (!($inject = fn.$inject)) {
$inject = [];
fnText = fn.toString().replace(STRIP_COMMENTS, '');
argDecl = fnText.match(FN_ARGS);
forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
arg.replace(FN_ARG, function(all, underscore, name) {
$inject.push(name);
});
});
fn.$inject = $inject;
}
} else if (isArray(fn)) {
last = fn.length - 1;
assertArgFn(fn[last], 'fn')
$inject = fn.slice(0, last);
} else {
assertArgFn(fn, 'fn', true);
}
return $inject;
}
///////////////////////////////////////
/**
* @ngdoc object
* @name AUTO.$injector
* @function
*
* @description
*
* `$injector` is used to retrieve object instances as defined by
* {@link AUTO.$provide provider}, instantiate types, invoke methods,
* and load modules.
*
* The following always holds true:
*
* <pre>
* var $injector = angular.injector();
* expect($injector.get('$injector')).toBe($injector);
* expect($injector.invoke(function($injector){
* return $injector;
* }).toBe($injector);
* </pre>
*
* # Injection Function Annotation
*
* JavaScript does not have annotations, and annotations are needed for dependency injection. The
* following ways are all valid way of annotating function with injection arguments and are equivalent.
*
* <pre>
* // inferred (only works if code not minified/obfuscated)
* $injector.invoke(function(serviceA){});
*
* // annotated
* function explicit(serviceA) {};
* explicit.$inject = ['serviceA'];
* $injector.invoke(explicit);
*
* // inline
* $injector.invoke(['serviceA', function(serviceA){}]);
* </pre>
*
* ## Inference
*
* In JavaScript calling `toString()` on a function returns the function definition. The definition can then be
* parsed and the function arguments can be extracted. *NOTE:* This does not work with minification, and obfuscation
* tools since these tools change the argument names.
*
* ## `$inject` Annotation
* By adding a `$inject` property onto a function the injection parameters can be specified.
*
* ## Inline
* As an array of injection names, where the last item in the array is the function to call.
*/
/**
* @ngdoc method
* @name AUTO.$injector#get
* @methodOf AUTO.$injector
*
* @description
* Return an instance of the service.
*
* @param {string} name The name of the instance to retrieve.
* @return {*} The instance.
*/
/**
* @ngdoc method
* @name AUTO.$injector#invoke
* @methodOf AUTO.$injector
*
* @description
* Invoke the method and supply the method arguments from the `$injector`.
*
* @param {!function} fn The function to invoke. The function arguments come form the function annotation.
* @param {Object=} self The `this` for the invoked method.
* @param {Object=} locals Optional object. If preset then any argument names are read from this object first, before
* the `$injector` is consulted.
* @returns {*} the value returned by the invoked `fn` function.
*/
/**
* @ngdoc method
* @name AUTO.$injector#instantiate
* @methodOf AUTO.$injector
* @description
* Create a new instance of JS type. The method takes a constructor function invokes the new operator and supplies
* all of the arguments to the constructor function as specified by the constructor annotation.
*
* @param {function} Type Annotated constructor function.
* @param {Object=} locals Optional object. If preset then any argument names are read from this object first, before
* the `$injector` is consulted.
* @returns {Object} new instance of `Type`.
*/
/**
* @ngdoc method
* @name AUTO.$injector#annotate
* @methodOf AUTO.$injector
*
* @description
* Returns an array of service names which the function is requesting for injection. This API is used by the injector
* to determine which services need to be injected into the function when the function is invoked. There are three
* ways in which the function can be annotated with the needed dependencies.
*
* # Argument names
*
* The simplest form is to extract the dependencies from the arguments of the function. This is done by converting
* the function into a string using `toString()` method and extracting the argument names.
* <pre>
* // Given
* function MyController($scope, $route) {
* // ...
* }
*
* // Then
* expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
* </pre>
*
* This method does not work with code minfication / obfuscation. For this reason the following annotation strategies
* are supported.
*
* # The `$inject` property
*
* If a function has an `$inject` property and its value is an array of strings, then the strings represent names of
* services to be injected into the function.
* <pre>
* // Given
* var MyController = function(obfuscatedScope, obfuscatedRoute) {
* // ...
* }
* // Define function dependencies
* MyController.$inject = ['$scope', '$route'];
*
* // Then
* expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
* </pre>
*
* # The array notation
*
* It is often desirable to inline Injected functions and that's when setting the `$inject` property is very
* inconvenient. In these situations using the array notation to specify the dependencies in a way that survives
* minification is a better choice:
*
* <pre>
* // We wish to write this (not minification / obfuscation safe)
* injector.invoke(function($compile, $rootScope) {
* // ...
* });
*
* // We are forced to write break inlining
* var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
* // ...
* };
* tmpFn.$inject = ['$compile', '$rootScope'];
* injector.invoke(tempFn);
*
* // To better support inline function the inline annotation is supported
* injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
* // ...
* }]);
*
* // Therefore
* expect(injector.annotate(
* ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
* ).toEqual(['$compile', '$rootScope']);
* </pre>
*
* @param {function|Array.<string|Function>} fn Function for which dependent service names need to be retrieved as described
* above.
*
* @returns {Array.<string>} The names of the services which the function requires.
*/
/**
* @ngdoc object
* @name AUTO.$provide
*
* @description
*
* Use `$provide` to register new providers with the `$injector`. The providers are the factories for the instance.
* The providers share the same name as the instance they create with `Provider` suffixed to them.
*
* A provider is an object with a `$get()` method. The injector calls the `$get` method to create a new instance of
* a service. The Provider can have additional methods which would allow for configuration of the provider.
*
* <pre>
* function GreetProvider() {
* var salutation = 'Hello';
*
* this.salutation = function(text) {
* salutation = text;
* };
*
* this.$get = function() {
* return function (name) {
* return salutation + ' ' + name + '!';
* };
* };
* }
*
* describe('Greeter', function(){
*
* beforeEach(module(function($provide) {
* $provide.provider('greet', GreetProvider);
* });
*
* it('should greet', inject(function(greet) {
* expect(greet('angular')).toEqual('Hello angular!');
* }));
*
* it('should allow configuration of salutation', function() {
* module(function(greetProvider) {
* greetProvider.salutation('Ahoj');
* });
* inject(function(greet) {
* expect(greet('angular')).toEqual('Ahoj angular!');
* });
* )};
*
* });
* </pre>
*/
/**
* @ngdoc method
* @name AUTO.$provide#provider
* @methodOf AUTO.$provide
* @description
*
* Register a provider for a service. The providers can be retrieved and can have additional configuration methods.
*
* @param {string} name The name of the instance. NOTE: the provider will be available under `name + 'Provider'` key.
* @param {(Object|function())} provider If the provider is:
*
* - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
* {@link AUTO.$injector#invoke $injector.invoke()} when an instance needs to be created.
* - `Constructor`: a new instance of the provider will be created using
* {@link AUTO.$injector#instantiate $injector.instantiate()}, then treated as `object`.
*
* @returns {Object} registered provider instance
*/
/**
* @ngdoc method
* @name AUTO.$provide#factory
* @methodOf AUTO.$provide
* @description
*
* A short hand for configuring services if only `$get` method is required.
*
* @param {string} name The name of the instance.
* @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand for
* `$provide.provider(name, {$get: $getFn})`.
* @returns {Object} registered provider instance
*/
/**
* @ngdoc method
* @name AUTO.$provide#service
* @methodOf AUTO.$provide
* @description
*
* A short hand for registering service of given class.
*
* @param {string} name The name of the instance.
* @param {Function} constructor A class (constructor function) that will be instantiated.
* @returns {Object} registered provider instance
*/
/**
* @ngdoc method
* @name AUTO.$provide#value
* @methodOf AUTO.$provide
* @description
*
* A short hand for configuring services if the `$get` method is a constant.
*
* @param {string} name The name of the instance.
* @param {*} value The value.
* @returns {Object} registered provider instance
*/
/**
* @ngdoc method
* @name AUTO.$provide#constant
* @methodOf AUTO.$provide
* @description
*
* A constant value, but unlike {@link AUTO.$provide#value value} it can be injected
* into configuration function (other modules) and it is not interceptable by
* {@link AUTO.$provide#decorator decorator}.
*
* @param {string} name The name of the constant.
* @param {*} value The constant value.
* @returns {Object} registered instance
*/
/**
* @ngdoc method
* @name AUTO.$provide#decorator
* @methodOf AUTO.$provide
* @description
*
* Decoration of service, allows the decorator to intercept the service instance creation. The
* returned instance may be the original instance, or a new instance which delegates to the
* original instance.
*
* @param {string} name The name of the service to decorate.
* @param {function()} decorator This function will be invoked when the service needs to be
* instanciated. The function is called using the {@link AUTO.$injector#invoke
* injector.invoke} method and is therefore fully injectable. Local injection arguments:
*
* * `$delegate` - The original service instance, which can be monkey patched, configured,
* decorated or delegated to.
*/
function createInjector(modulesToLoad) {
var INSTANTIATING = {},
providerSuffix = 'Provider',
path = [],
loadedModules = new HashMap(),
providerCache = {
$provide: {
provider: supportObject(provider),
factory: supportObject(factory),
service: supportObject(service),
value: supportObject(value),
constant: supportObject(constant),
decorator: decorator
}
},
providerInjector = createInternalInjector(providerCache, function() {
throw Error("Unknown provider: " + path.join(' <- '));
}),
instanceCache = {},
instanceInjector = (instanceCache.$injector =
createInternalInjector(instanceCache, function(servicename) {
var provider = providerInjector.get(servicename +
providerSuffix);
return instanceInjector.invoke(provider.$get, provider);
}));
forEach(loadModules(modulesToLoad), function(fn) {
instanceInjector.invoke(fn || noop);
});
return instanceInjector;
////////////////////////////////////
// $provider
////////////////////////////////////
function supportObject(delegate) {
return function(key, value) {
if (isObject(key)) {
forEach(key, reverseParams(delegate));
} else {
return delegate(key, value);
}
}
}
function provider(name, provider_) {
if (isFunction(provider_) || isArray(provider_)) {
provider_ = providerInjector.instantiate(provider_);
}
if (!provider_.$get) {
throw Error('Provider ' + name +
' must define $get factory method.');
}
return providerCache[name + providerSuffix] = provider_;
}
function factory(name, factoryFn) {
return provider(name, {
$get: factoryFn
});
}
function service(name, constructor) {
return factory(name, ['$injector',
function($injector) {
return $injector.instantiate(constructor);
}
]);
}
function value(name, value) {
return factory(name, valueFn(value));
}
function constant(name, value) {
providerCache[name] = value;
instanceCache[name] = value;
}
function decorator(serviceName, decorFn) {
var origProvider = providerInjector.get(serviceName +
providerSuffix),
orig$get = origProvider.$get;
origProvider.$get = function() {
var origInstance = instanceInjector.invoke(orig$get,
origProvider);
return instanceInjector.invoke(decorFn, null, {
$delegate: origInstance
});
};
}
////////////////////////////////////
// Module Loading
////////////////////////////////////
function loadModules(modulesToLoad) {
var runBlocks = [];
forEach(modulesToLoad, function(module) {
if (loadedModules.get(module)) return;
loadedModules.put(module, true);
if (isString(module)) {
var moduleFn = angularModule(module);
runBlocks = runBlocks.concat(loadModules(moduleFn.requires))
.concat(moduleFn._runBlocks);
try {
for (var invokeQueue = moduleFn._invokeQueue, i = 0, ii =
invokeQueue.length; i < ii; i++) {
var invokeArgs = invokeQueue[i],
provider = invokeArgs[0] == '$injector' ?
providerInjector : providerInjector.get(
invokeArgs[0]);
provider[invokeArgs[1]].apply(provider, invokeArgs[
2]);
}
} catch (e) {
if (e.message) e.message += ' from ' + module;
throw e;
}
} else if (isFunction(module)) {
try {
runBlocks.push(providerInjector.invoke(module));
} catch (e) {
if (e.message) e.message += ' from ' + module;
throw e;
}
} else if (isArray(module)) {
try {
runBlocks.push(providerInjector.invoke(module));
} catch (e) {
if (e.message) e.message += ' from ' + String(module[
module.length - 1]);
throw e;
}
} else {
assertArgFn(module, 'module');
}
});
return runBlocks;
}
////////////////////////////////////
// internal Injector
////////////////////////////////////
function createInternalInjector(cache, factory) {
function getService(serviceName) {
if (typeof serviceName !== 'string') {
throw Error('Service name expected');
}
if (cache.hasOwnProperty(serviceName)) {
if (cache[serviceName] === INSTANTIATING) {
throw Error('Circular dependency: ' + path.join(' <- '));
}
return cache[serviceName];
} else {
try {
path.unshift(serviceName);
cache[serviceName] = INSTANTIATING;
return cache[serviceName] = factory(serviceName);
} finally {
path.shift();
}
}
}
function invoke(fn, self, locals) {
var args = [],
$inject = annotate(fn),
length, i,
key;
for (i = 0, length = $inject.length; i < length; i++) {
key = $inject[i];
args.push(
locals && locals.hasOwnProperty(key) ? locals[key] :
getService(key));
}
if (!fn.$inject) {
// this means that we must be an array.
fn = fn[length];
}
// Performance optimization: http://jsperf.com/apply-vs-call-vs-invoke
switch (self ? -1 : args.length) {
case 0:
return fn();
case 1:
return fn(args[0]);
case 2:
return fn(args[0], args[1]);
case 3:
return fn(args[0], args[1], args[2]);
case 4:
return fn(args[0], args[1], args[2], args[3]);
case 5:
return fn(args[0], args[1], args[2], args[3], args[4]);
case 6:
return fn(args[0], args[1], args[2], args[3], args[4],
args[5]);
case 7:
return fn(args[0], args[1], args[2], args[3], args[4],
args[5], args[6]);
case 8:
return fn(args[0], args[1], args[2], args[3], args[4],
args[5], args[6], args[7]);
case 9:
return fn(args[0], args[1], args[2], args[3], args[4],
args[5], args[6], args[7], args[8]);
case 10:
return fn(args[0], args[1], args[2], args[3], args[4],
args[5], args[6], args[7], args[8], args[9]);
default:
return fn.apply(self, args);
}
}
function instantiate(Type, locals) {
var Constructor = function() {},
instance, returnedValue;
Constructor.prototype = (isArray(Type) ? Type[Type.length - 1] :
Type).prototype;
instance = new Constructor();
returnedValue = invoke(Type, instance, locals);
return isObject(returnedValue) ? returnedValue : instance;
}
return {
invoke: invoke,
instantiate: instantiate,
get: getService,
annotate: annotate
};
}
}
/**
* @ngdoc function
* @name ng.$anchorScroll
* @requires $window
* @requires $location
* @requires $rootScope
*
* @description
* When called, it checks current value of `$location.hash()` and scroll to related element,
* according to rules specified in
* {@link http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document Html5 spec}.
*
* It also watches the `$location.hash()` and scroll whenever it changes to match any anchor.
* This can be disabled by calling `$anchorScrollProvider.disableAutoScrolling()`.
*/
function $AnchorScrollProvider() {
var autoScrollingEnabled = true;
this.disableAutoScrolling = function() {
autoScrollingEnabled = false;
};
this.$get = ['$window', '$location', '$rootScope',
function($window, $location, $rootScope) {
var document = $window.document;
// helper function to get first anchor from a NodeList
// can't use filter.filter, as it accepts only instances of Array
// and IE can't convert NodeList to an array using [].slice
// TODO(vojta): use filter if we change it to accept lists as well
function getFirstAnchor(list) {
var result = null;
forEach(list, function(element) {
if (!result && lowercase(element.nodeName) === 'a')
result = element;
});
return result;
}
function scroll() {
var hash = $location.hash(),
elm;
// empty hash, scroll to the top of the page
if (!hash) $window.scrollTo(0, 0);
// element with given id
else if ((elm = document.getElementById(hash))) elm.scrollIntoView();
// first anchor with given name :-D
else if ((elm = getFirstAnchor(document.getElementsByName(
hash)))) elm.scrollIntoView();
// no element and hash == 'top', scroll to the top of the page
else if (hash === 'top') $window.scrollTo(0, 0);
}
// does not scroll when user clicks on anchor link that is currently on
// (no url change, no $location.hash() change), browser native does scroll
if (autoScrollingEnabled) {
$rootScope.$watch(function autoScrollWatch() {
return $location.hash();
}, function autoScrollWatchAction() {
$rootScope.$evalAsync(scroll);
});
}
return scroll;
}
];
}
/**
* ! This is a private undocumented service !
*
* @name ng.$browser
* @requires $log
* @description
* This object has two goals:
*
* - hide all the global state in the browser caused by the window object
* - abstract away all the browser specific features and inconsistencies
*
* For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
* service, which can be used for convenient testing of the application without the interaction with
* the real browser apis.
*/
/**
* @param {object} window The global window object.
* @param {object} document jQuery wrapped document.
* @param {function()} XHR XMLHttpRequest constructor.
* @param {object} $log console.log or an object with the same interface.
* @param {object} $sniffer $sniffer service
*/
function Browser(window, document, $log, $sniffer) {
var self = this,
rawDocument = document[0],
location = window.location,
history = window.history,
setTimeout = window.setTimeout,
clearTimeout = window.clearTimeout,
pendingDeferIds = {};
self.isMock = false;
var outstandingRequestCount = 0;
var outstandingRequestCallbacks = [];
// TODO(vojta): remove this temporary api
self.$$completeOutstandingRequest = completeOutstandingRequest;
self.$$incOutstandingRequestCount = function() {
outstandingRequestCount++;
};
/**
* Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
* counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
*/
function completeOutstandingRequest(fn) {
try {
fn.apply(null, sliceArgs(arguments, 1));
} finally {
outstandingRequestCount--;
if (outstandingRequestCount === 0) {
while (outstandingRequestCallbacks.length) {
try {
outstandingRequestCallbacks.pop()();
} catch (e) {
$log.error(e);
}
}
}
}
}
/**
* @private
* Note: this method is used only by scenario runner
* TODO(vojta): prefix this method with $$ ?
* @param {function()} callback Function that will be called when no outstanding request
*/
self.notifyWhenNoOutstandingRequests = function(callback) {
// force browser to execute all pollFns - this is needed so that cookies and other pollers fire
// at some deterministic time in respect to the test runner's actions. Leaving things up to the
// regular poller would result in flaky tests.
forEach(pollFns, function(pollFn) {
pollFn();
});
if (outstandingRequestCount === 0) {
callback();
} else {
outstandingRequestCallbacks.push(callback);
}
};
//////////////////////////////////////////////////////////////
// Poll Watcher API
//////////////////////////////////////////////////////////////
var pollFns = [],
pollTimeout;
/**
* @name ng.$browser#addPollFn
* @methodOf ng.$browser
*
* @param {function()} fn Poll function to add
*
* @description
* Adds a function to the list of functions that poller periodically executes,
* and starts polling if not started yet.
*
* @returns {function()} the added function
*/
self.addPollFn = function(fn) {
if (isUndefined(pollTimeout)) startPoller(100, setTimeout);
pollFns.push(fn);
return fn;
};
/**
* @param {number} interval How often should browser call poll functions (ms)
* @param {function()} setTimeout Reference to a real or fake `setTimeout` function.
*
* @description
* Configures the poller to run in the specified intervals, using the specified
* setTimeout fn and kicks it off.
*/
function startPoller(interval, setTimeout) {
(function check() {
forEach(pollFns, function(pollFn) {
pollFn();
});
pollTimeout = setTimeout(check, interval);
})();
}
//////////////////////////////////////////////////////////////
// URL API
//////////////////////////////////////////////////////////////
var lastBrowserUrl = location.href,
baseElement = document.find('base');
/**
* @name ng.$browser#url
* @methodOf ng.$browser
*
* @description
* GETTER:
* Without any argument, this method just returns current value of location.href.
*
* SETTER:
* With at least one argument, this method sets url to new value.
* If html5 history api supported, pushState/replaceState is used, otherwise
* location.href/location.replace is used.
* Returns its own instance to allow chaining
*
* NOTE: this api is intended for use only by the $location service. Please use the
* {@link ng.$location $location service} to change url.
*
* @param {string} url New url (when used as setter)
* @param {boolean=} replace Should new url replace current history record ?
*/
self.url = function(url, replace) {
// setter
if (url) {
if (lastBrowserUrl == url) return;
lastBrowserUrl = url;
if ($sniffer.history) {
if (replace) history.replaceState(null, '', url);
else {
history.pushState(null, '', url);
// Crazy Opera Bug: http://my.opera.com/community/forums/topic.dml?id=1185462
baseElement.attr('href', baseElement.attr('href'));
}
} else {
if (replace) location.replace(url);
else location.href = url;
}
return self;
// getter
} else {
// the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
return location.href.replace(/%27/g, "'");
}
};
var urlChangeListeners = [],
urlChangeInit = false;
function fireUrlChange() {
if (lastBrowserUrl == self.url()) return;
lastBrowserUrl = self.url();
forEach(urlChangeListeners, function(listener) {
listener(self.url());
});
}
/**
* @name ng.$browser#onUrlChange
* @methodOf ng.$browser
* @TODO(vojta): refactor to use node's syntax for events
*
* @description
* Register callback function that will be called, when url changes.
*
* It's only called when the url is changed by outside of angular:
* - user types different url into address bar
* - user clicks on history (forward/back) button
* - user clicks on a link
*
* It's not called when url is changed by $browser.url() method
*
* The listener gets called with new url as parameter.
*
* NOTE: this api is intended for use only by the $location service. Please use the
* {@link ng.$location $location service} to monitor url changes in angular apps.
*
* @param {function(string)} listener Listener function to be called when url changes.
* @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
*/
self.onUrlChange = function(callback) {
if (!urlChangeInit) {
// We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
// don't fire popstate when user change the address bar and don't fire hashchange when url
// changed by push/replaceState
// html5 history api - popstate event
if ($sniffer.history) jqLite(window).bind('popstate',
fireUrlChange);
// hashchange event
if ($sniffer.hashchange) jqLite(window).bind('hashchange',
fireUrlChange);
// polling
else self.addPollFn(fireUrlChange);
urlChangeInit = true;
}
urlChangeListeners.push(callback);
return callback;
};
//////////////////////////////////////////////////////////////
// Misc API
//////////////////////////////////////////////////////////////
/**
* Returns current <base href>
* (always relative - without domain)
*
* @returns {string=}
*/
self.baseHref = function() {
var href = baseElement.attr('href');
return href ? href.replace(/^https?\:\/\/[^\/]*/, '') : '';
};
//////////////////////////////////////////////////////////////
// Cookies API
//////////////////////////////////////////////////////////////
var lastCookies = {};
var lastCookieString = '';
var cookiePath = self.baseHref();
/**
* @name ng.$browser#cookies
* @methodOf ng.$browser
*
* @param {string=} name Cookie name
* @param {string=} value Cokkie value
*
* @description
* The cookies method provides a 'private' low level access to browser cookies.
* It is not meant to be used directly, use the $cookie service instead.
*
* The return values vary depending on the arguments that the method was called with as follows:
* <ul>
* <li>cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify it</li>
* <li>cookies(name, value) -> set name to value, if value is undefined delete the cookie</li>
* <li>cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that way)</li>
* </ul>
*
* @returns {Object} Hash of all cookies (if called without any parameter)
*/
self.cookies = function(name, value) {
var cookieLength, cookieArray, cookie, i, index;
if (name) {
if (value === undefined) {
rawDocument.cookie = escape(name) + "=;path=" + cookiePath +
";expires=Thu, 01 Jan 1970 00:00:00 GMT";
} else {
if (isString(value)) {
cookieLength = (rawDocument.cookie = escape(name) + '=' +
escape(value) + ';path=' + cookiePath).length + 1;
// per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum:
// - 300 cookies
// - 20 cookies per unique domain
// - 4096 bytes per cookie
if (cookieLength > 4096) {
$log.warn("Cookie '" + name +
"' possibly not set or overflowed because it was too large (" +
cookieLength + " > 4096 bytes)!");
}
}
}
} else {
if (rawDocument.cookie !== lastCookieString) {
lastCookieString = rawDocument.cookie;
cookieArray = lastCookieString.split("; ");
lastCookies = {};
for (i = 0; i < cookieArray.length; i++) {
cookie = cookieArray[i];
index = cookie.indexOf('=');
if (index > 0) { //ignore nameless cookies
lastCookies[unescape(cookie.substring(0, index))] =
unescape(cookie.substring(index + 1));
}
}
}
return lastCookies;
}
};
/**
* @name ng.$browser#defer
* @methodOf ng.$browser
* @param {function()} fn A function, who's execution should be defered.
* @param {number=} [delay=0] of milliseconds to defer the function execution.
* @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
*
* @description
* Executes a fn asynchroniously via `setTimeout(fn, delay)`.
*
* Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
* `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
* via `$browser.defer.flush()`.
*
*/
self.defer = function(fn, delay) {
var timeoutId;
outstandingRequestCount++;
timeoutId = setTimeout(function() {
delete pendingDeferIds[timeoutId];
completeOutstandingRequest(fn);
}, delay || 0);
pendingDeferIds[timeoutId] = true;
return timeoutId;
};
/**
* @name ng.$browser#defer.cancel
* @methodOf ng.$browser.defer
*
* @description
* Cancels a defered task identified with `deferId`.
*
* @param {*} deferId Token returned by the `$browser.defer` function.
* @returns {boolean} Returns `true` if the task hasn't executed yet and was successfuly canceled.
*/
self.defer.cancel = function(deferId) {
if (pendingDeferIds[deferId]) {
delete pendingDeferIds[deferId];
clearTimeout(deferId);
completeOutstandingRequest(noop);
return true;
}
return false;
};
}
function $BrowserProvider() {
this.$get = ['$window', '$log', '$sniffer', '$document',
function($window, $log, $sniffer, $document) {
return new Browser($window, $document, $log, $sniffer);
}
];
}
/**
* @ngdoc object
* @name ng.$cacheFactory
*
* @description
* Factory that constructs cache objects.
*
*
* @param {string} cacheId Name or id of the newly created cache.
* @param {object=} options Options object that specifies the cache behavior. Properties:
*
* - `{number=}` `capacity` — turns the cache into LRU cache.
*
* @returns {object} Newly created cache object with the following set of methods:
*
* - `{object}` `info()` — Returns id, size, and options of cache.
* - `{void}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache.
* - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
* - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
* - `{void}` `removeAll()` — Removes all cached values.
* - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
*
*/
function $CacheFactoryProvider() {
this.$get = function() {
var caches = {};
function cacheFactory(cacheId, options) {
if (cacheId in caches) {
throw Error('cacheId ' + cacheId + ' taken');
}
var size = 0,
stats = extend({}, options, {
id: cacheId
}),
data = {},
capacity = (options && options.capacity) || Number.MAX_VALUE,
lruHash = {},
freshEnd = null,
staleEnd = null;
return caches[cacheId] = {
put: function(key, value) {
var lruEntry = lruHash[key] || (lruHash[key] = {
key: key
});
refresh(lruEntry);
if (isUndefined(value)) return;
if (!(key in data)) size++;
data[key] = value;
if (size > capacity) {
this.remove(staleEnd.key);
}
},
get: function(key) {
var lruEntry = lruHash[key];
if (!lruEntry) return;
refresh(lruEntry);
return data[key];
},
remove: function(key) {
var lruEntry = lruHash[key];
if (!lruEntry) return;
if (lruEntry == freshEnd) freshEnd = lruEntry.p;
if (lruEntry == staleEnd) staleEnd = lruEntry.n;
link(lruEntry.n, lruEntry.p);
delete lruHash[key];
delete data[key];
size--;
},
removeAll: function() {
data = {};
size = 0;
lruHash = {};
freshEnd = staleEnd = null;
},
destroy: function() {
data = null;
stats = null;
lruHash = null;
delete caches[cacheId];
},
info: function() {
return extend({}, stats, {
size: size
});
}
};
/**
* makes the `entry` the freshEnd of the LRU linked list
*/
function refresh(entry) {
if (entry != freshEnd) {
if (!staleEnd) {
staleEnd = entry;
} else if (staleEnd == entry) {
staleEnd = entry.n;
}
link(entry.n, entry.p);
link(entry, freshEnd);
freshEnd = entry;
freshEnd.n = null;
}
}
/**
* bidirectionally links two entries of the LRU linked list
*/
function link(nextEntry, prevEntry) {
if (nextEntry != prevEntry) {
if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
}
}
}
cacheFactory.info = function() {
var info = {};
forEach(caches, function(cache, cacheId) {
info[cacheId] = cache.info();
});
return info;
};
cacheFactory.get = function(cacheId) {
return caches[cacheId];
};
return cacheFactory;
};
}
/**
* @ngdoc object
* @name ng.$templateCache
*
* @description
* Cache used for storing html templates.
*
* See {@link ng.$cacheFactory $cacheFactory}.
*
*/
function $TemplateCacheProvider() {
this.$get = ['$cacheFactory',
function($cacheFactory) {
return $cacheFactory('templates');
}
];
}
/* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
*
* DOM-related variables:
*
* - "node" - DOM Node
* - "element" - DOM Element or Node
* - "$node" or "$element" - jqLite-wrapped node or element
*
*
* Compiler related stuff:
*
* - "linkFn" - linking fn of a single directive
* - "nodeLinkFn" - function that aggregates all linking fns for a particular node
* - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
* - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
*/
var NON_ASSIGNABLE_MODEL_EXPRESSION = 'Non-assignable model expression: ';
/**
* @ngdoc function
* @name ng.$compile
* @function
*
* @description
* Compiles a piece of HTML string or DOM into a template and produces a template function, which
* can then be used to link {@link ng.$rootScope.Scope scope} and the template together.
*
* The compilation is a process of walking the DOM tree and trying to match DOM elements to
* {@link ng.$compileProvider#directive directives}. For each match it
* executes corresponding template function and collects the
* instance functions into a single template function which is then returned.
*
* The template function can then be used once to produce the view or as it is the case with
* {@link ng.directive:ngRepeat repeater} many-times, in which
* case each call results in a view that is a DOM clone of the original template.
*
<doc:example module="compile">
<doc:source>
<script>
// declare a new module, and inject the $compileProvider
angular.module('compile', [], function($compileProvider) {
// configure new 'compile' directive by passing a directive
// factory function. The factory function injects the '$compile'
$compileProvider.directive('compile', function($compile) {
// directive factory creates a link function
return function(scope, element, attrs) {
scope.$watch(
function(scope) {
// watch the 'compile' expression for changes
return scope.$eval(attrs.compile);
},
function(value) {
// when the 'compile' expression changes
// assign it into the current DOM
element.html(value);
// compile the new DOM and link it to the current
// scope.
// NOTE: we only compile .childNodes so that
// we don't get into infinite loop compiling ourselves
$compile(element.contents())(scope);
}
);
};
})
});
function Ctrl($scope) {
$scope.name = 'Angular';
$scope.html = 'Hello {{name}}';
}
</script>
<div ng-controller="Ctrl">
<input ng-model="name"> <br>
<textarea ng-model="html"></textarea> <br>
<div compile="html"></div>
</div>
</doc:source>
<doc:scenario>
it('should auto compile', function() {
expect(element('div[compile]').text()).toBe('Hello Angular');
input('html').enter('{{name}}!');
expect(element('div[compile]').text()).toBe('Angular!');
});
</doc:scenario>
</doc:example>
*
*
* @param {string|DOMElement} element Element or HTML string to compile into a template function.
* @param {function(angular.Scope[, cloneAttachFn]} transclude function available to directives.
* @param {number} maxPriority only apply directives lower then given priority (Only effects the
* root element(s), not their children)
* @returns {function(scope[, cloneAttachFn])} a link function which is used to bind template
* (a DOM element/tree) to a scope. Where:
*
* * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
* * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
* `template` and call the `cloneAttachFn` function allowing the caller to attach the
* cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
* called as: <br> `cloneAttachFn(clonedElement, scope)` where:
*
* * `clonedElement` - is a clone of the original `element` passed into the compiler.
* * `scope` - is the current scope with which the linking function is working with.
*
* Calling the linking function returns the element of the template. It is either the original element
* passed in, or the clone of the element if the `cloneAttachFn` is provided.
*
* After linking the view is not updated until after a call to $digest which typically is done by
* Angular automatically.
*
* If you need access to the bound view, there are two ways to do it:
*
* - If you are not asking the linking function to clone the template, create the DOM element(s)
* before you send them to the compiler and keep this reference around.
* <pre>
* var element = $compile('<p>{{total}}</p>')(scope);
* </pre>
*
* - if on the other hand, you need the element to be cloned, the view reference from the original
* example would not point to the clone, but rather to the original template that was cloned. In
* this case, you can access the clone via the cloneAttachFn:
* <pre>
* var templateHTML = angular.element('<p>{{total}}</p>'),
* scope = ....;
*
* var clonedElement = $compile(templateHTML)(scope, function(clonedElement, scope) {
* //attach the clone to DOM document at the right place
* });
*
* //now we have reference to the cloned DOM via `clone`
* </pre>
*
*
* For information on how the compiler works, see the
* {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
*/
/**
* @ngdoc service
* @name ng.$compileProvider
* @function
*
* @description
*/
$CompileProvider.$inject = ['$provide'];
function $CompileProvider($provide) {
var hasDirectives = {},
Suffix = 'Directive',
COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w\-_]+)\s+(.*)$/,
CLASS_DIRECTIVE_REGEXP = /(([\d\w\-_]+)(?:\:([^;]+))?;?)/,
MULTI_ROOT_TEMPLATE_ERROR =
'Template must have exactly one root element. was: ',
urlSanitizationWhitelist = /^\s*(https?|ftp|mailto|file):/;
/**
* @ngdoc function
* @name ng.$compileProvider#directive
* @methodOf ng.$compileProvider
* @function
*
* @description
* Register a new directives with the compiler.
*
* @param {string} name Name of the directive in camel-case. (ie <code>ngBind</code> which will match as
* <code>ng-bind</code>).
* @param {function} directiveFactory An injectable directive factroy function. See {@link guide/directive} for more
* info.
* @returns {ng.$compileProvider} Self for chaining.
*/
this.directive = function registerDirective(name, directiveFactory) {
if (isString(name)) {
assertArg(directiveFactory, 'directive');
if (!hasDirectives.hasOwnProperty(name)) {
hasDirectives[name] = [];
$provide.factory(name + Suffix, ['$injector',
'$exceptionHandler',
function($injector, $exceptionHandler) {
var directives = [];
forEach(hasDirectives[name], function(
directiveFactory) {
try {
var directive = $injector.invoke(
directiveFactory);
if (isFunction(directive)) {
directive = {
compile: valueFn(directive)
};
} else if (!directive.compile && directive.link) {
directive.compile = valueFn(directive.link);
}
directive.priority = directive.priority ||
0;
directive.name = directive.name || name;
directive.require = directive.require || (
directive.controller && directive.name);
directive.restrict = directive.restrict ||
'A';
directives.push(directive);
} catch (e) {
$exceptionHandler(e);
}
});
return directives;
}
]);
}
hasDirectives[name].push(directiveFactory);
} else {
forEach(name, reverseParams(registerDirective));
}
return this;
};
/**
* @ngdoc function
* @name ng.$compileProvider#urlSanitizationWhitelist
* @methodOf ng.$compileProvider
* @function
*
* @description
* Retrieves or overrides the default regular expression that is used for whitelisting of safe
* urls during a[href] sanitization.
*
* The sanitization is a security measure aimed at prevent XSS attacks via html links.
*
* Any url about to be assigned to a[href] via data-binding is first normalized and turned into an
* absolute url. Afterwards the url is matched against the `urlSanitizationWhitelist` regular
* expression. If a match is found the original url is written into the dom. Otherwise the
* absolute url is prefixed with `'unsafe:'` string and only then it is written into the DOM.
*
* @param {RegExp=} regexp New regexp to whitelist urls with.
* @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
* chaining otherwise.
*/
this.urlSanitizationWhitelist = function(regexp) {
if (isDefined(regexp)) {
urlSanitizationWhitelist = regexp;
return this;
}
return urlSanitizationWhitelist;
};
this.$get = [
'$injector', '$interpolate', '$exceptionHandler', '$http',
'$templateCache', '$parse',
'$controller', '$rootScope', '$document',
function($injector, $interpolate, $exceptionHandler, $http,
$templateCache, $parse,
$controller, $rootScope, $document) {
var Attributes = function(element, attr) {
this.$$element = element;
this.$attr = attr || {};
};
Attributes.prototype = {
$normalize: directiveNormalize,
/**
* Set a normalized attribute on the element in a way such that all directives
* can share the attribute. This function properly handles boolean attributes.
* @param {string} key Normalized key. (ie ngAttribute)
* @param {string|boolean} value The value to set. If `null` attribute will be deleted.
* @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
* Defaults to true.
* @param {string=} attrName Optional none normalized name. Defaults to key.
*/
$set: function(key, value, writeAttr, attrName) {
var booleanKey = getBooleanAttrName(this.$$element[0],
key),
$$observers = this.$$observers,
normalizedVal;
if (booleanKey) {
this.$$element.prop(key, value);
attrName = booleanKey;
}
this[key] = value;
// translate normalized key to actual key
if (attrName) {
this.$attr[key] = attrName;
} else {
attrName = this.$attr[key];
if (!attrName) {
this.$attr[key] = attrName = snake_case(key,
'-');
}
}
// sanitize a[href] values
if (nodeName_(this.$$element[0]) === 'A' && key ===
'href') {
urlSanitizationNode.setAttribute('href', value);
// href property always returns normalized absolute url, so we can match against that
normalizedVal = urlSanitizationNode.href;
if (!normalizedVal.match(urlSanitizationWhitelist)) {
this[key] = value = 'unsafe:' + normalizedVal;
}
}
if (writeAttr !== false) {
if (value === null || value === undefined) {
this.$$element.removeAttr(attrName);
} else {
this.$$element.attr(attrName, value);
}
}
// fire observers
$$observers && forEach($$observers[key], function(fn) {
try {
fn(value);
} catch (e) {
$exceptionHandler(e);
}
});
},
/**
* Observe an interpolated attribute.
* The observer will never be called, if given attribute is not interpolated.
*
* @param {string} key Normalized key. (ie ngAttribute) .
* @param {function(*)} fn Function that will be called whenever the attribute value changes.
* @returns {function(*)} the `fn` Function passed in.
*/
$observe: function(key, fn) {
var attrs = this,
$$observers = (attrs.$$observers || (attrs.$$observers = {})),
listeners = ($$observers[key] || ($$observers[key] = []));
listeners.push(fn);
$rootScope.$evalAsync(function() {
if (!listeners.$$inter) {
// no one registered attribute interpolation function, so lets call it manually
fn(attrs[key]);
}
});
return fn;
}
};
var urlSanitizationNode = $document[0].createElement('a'),
startSymbol = $interpolate.startSymbol(),
endSymbol = $interpolate.endSymbol(),
denormalizeTemplate = (startSymbol == '{{' || endSymbol ==
'}}') ? identity : function denormalizeTemplate(
template) {
return template.replace(/\{\{/g, startSymbol).replace(
/}}/g, endSymbol);
};
return compile;
//================================
function compile($compileNodes, transcludeFn, maxPriority) {
if (!($compileNodes instanceof jqLite)) {
// jquery always rewraps, whereas we need to preserve the original selector so that we can modify it.
$compileNodes = jqLite($compileNodes);
}
// We can not compile top level text elements since text nodes can be merged and we will
// not be able to attach scope data to them, so we will wrap them in <span>
forEach($compileNodes, function(node, index) {
if (node.nodeType == 3 /* text node */ && node.nodeValue
.match(/\S+/) /* non-empty */ ) {
$compileNodes[index] = jqLite(node).wrap(
'<span></span>').parent()[0];
}
});
var compositeLinkFn = compileNodes($compileNodes,
transcludeFn, $compileNodes, maxPriority);
return function publicLinkFn(scope, cloneConnectFn) {
assertArg(scope, 'scope');
// important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
// and sometimes changes the structure of the DOM.
var $linkNode = cloneConnectFn ? JQLitePrototype.clone.call(
$compileNodes) // IMPORTANT!!!
: $compileNodes;
// Attach scope only to non-text nodes.
for (var i = 0, ii = $linkNode.length; i < ii; i++) {
var node = $linkNode[i];
if (node.nodeType == 1 /* element */ || node.nodeType ==
9 /* document */ ) {
$linkNode.eq(i).data('$scope', scope);
}
}
safeAddClass($linkNode, 'ng-scope');
if (cloneConnectFn) cloneConnectFn($linkNode, scope);
if (compositeLinkFn) compositeLinkFn(scope, $linkNode,
$linkNode);
return $linkNode;
};
}
function wrongMode(localName, mode) {
throw Error("Unsupported '" + mode + "' for '" + localName +
"'.");
}
function safeAddClass($element, className) {
try {
$element.addClass(className);
} catch (e) {
// ignore, since it means that we are trying to set class on
// SVG element, where class name is read-only.
}
}
/**
* Compile function matches each node in nodeList against the directives. Once all directives
* for a particular node are collected their compile functions are executed. The compile
* functions return values - the linking functions - are combined into a composite linking
* function, which is the a linking function for the node.
*
* @param {NodeList} nodeList an array of nodes or NodeList to compile
* @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the
* scope argument is auto-generated to the new child of the transcluded parent scope.
* @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then the
* rootElement must be set the jqLite collection of the compile root. This is
* needed so that the jqLite collection items can be replaced with widgets.
* @param {number=} max directive priority
* @returns {?function} A composite linking function of all of the matched directives or null.
*/
function compileNodes(nodeList, transcludeFn, $rootElement,
maxPriority) {
var linkFns = [],
nodeLinkFn, childLinkFn, directives, attrs, linkFnFound;
for (var i = 0; i < nodeList.length; i++) {
attrs = new Attributes();
// we must always refer to nodeList[i] since the nodes can be replaced underneath us.
directives = collectDirectives(nodeList[i], [], attrs,
maxPriority);
nodeLinkFn = (directives.length) ?
applyDirectivesToNode(directives, nodeList[i],
attrs, transcludeFn, $rootElement) : null;
childLinkFn = (nodeLinkFn && nodeLinkFn.terminal || !
nodeList[i].childNodes || !nodeList[i].childNodes.length) ?
null : compileNodes(nodeList[i].childNodes,
nodeLinkFn ? nodeLinkFn.transclude : transcludeFn);
linkFns.push(nodeLinkFn);
linkFns.push(childLinkFn);
linkFnFound = (linkFnFound || nodeLinkFn || childLinkFn);
}
// return a linking function if we have found anything, null otherwise
return linkFnFound ? compositeLinkFn : null;
function compositeLinkFn(scope, nodeList, $rootElement,
boundTranscludeFn) {
var nodeLinkFn, childLinkFn, node, childScope,
childTranscludeFn, i, ii, n;
// copy nodeList so that linking doesn't break due to live list updates.
var stableNodeList = [];
for (i = 0, ii = nodeList.length; i < ii; i++) {
stableNodeList.push(nodeList[i]);
}
for (i = 0, n = 0, ii = linkFns.length; i < ii; n++) {
node = stableNodeList[n];
nodeLinkFn = linkFns[i++];
childLinkFn = linkFns[i++];
if (nodeLinkFn) {
if (nodeLinkFn.scope) {
childScope = scope.$new(isObject(nodeLinkFn
.scope));
jqLite(node).data('$scope', childScope);
} else {
childScope = scope;
}
childTranscludeFn = nodeLinkFn.transclude;
if (childTranscludeFn || (!boundTranscludeFn &&
transcludeFn)) {
nodeLinkFn(childLinkFn, childScope, node,
$rootElement, (function(transcludeFn) {
return function(cloneFn) {
var transcludeScope = scope.$new();
transcludeScope.$$transcluded =
true;
return transcludeFn(transcludeScope,
cloneFn).
bind('$destroy', bind(
transcludeScope,
transcludeScope.$destroy));
};
})(childTranscludeFn || transcludeFn));
} else {
nodeLinkFn(childLinkFn, childScope, node,
undefined, boundTranscludeFn);
}
} else if (childLinkFn) {
childLinkFn(scope, node.childNodes, undefined,
boundTranscludeFn);
}
}
}
}
/**
* Looks for directives on the given node and adds them to the directive collection which is
* sorted.
*
* @param node Node to search.
* @param directives An array to which the directives are added to. This array is sorted before
* the function returns.
* @param attrs The shared attrs object which is used to populate the normalized attributes.
* @param {number=} maxPriority Max directive priority.
*/
function collectDirectives(node, directives, attrs, maxPriority) {
var nodeType = node.nodeType,
attrsMap = attrs.$attr,
match,
className;
switch (nodeType) {
case 1:
/* Element */
// use the node name: <directive>
addDirective(directives,
directiveNormalize(nodeName_(node).toLowerCase()),
'E', maxPriority);
// iterate over the attributes
for (var attr, name, nName, value, nAttrs = node.attributes,
j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
attr = nAttrs[j];
if (attr.specified) {
name = attr.name;
nName = directiveNormalize(name.toLowerCase());
attrsMap[nName] = name;
attrs[nName] = value = trim((msie && name ==
'href') ? decodeURIComponent(node.getAttribute(
name, 2)) : attr.value);
if (getBooleanAttrName(node, nName)) {
attrs[nName] = true; // presence means true
}
addAttrInterpolateDirective(node,
directives, value, nName);
addDirective(directives, nName, 'A',
maxPriority);
}
}
// use class as directive
className = node.className;
if (isString(className) && className !== '') {
while (match = CLASS_DIRECTIVE_REGEXP.exec(
className)) {
nName = directiveNormalize(match[2]);
if (addDirective(directives, nName, 'C',
maxPriority)) {
attrs[nName] = trim(match[3]);
}
className = className.substr(match.index +
match[0].length);
}
}
break;
case 3:
/* Text Node */
addTextInterpolateDirective(directives, node.nodeValue);
break;
case 8:
/* Comment */
try {
match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
if (match) {
nName = directiveNormalize(match[1]);
if (addDirective(directives, nName, 'M',
maxPriority)) {
attrs[nName] = trim(match[2]);
}
}
} catch (e) {
// turns out that under some circumstances IE9 throws errors when one attempts to read comment's node value.
// Just ignore it and continue. (Can't seem to reproduce in test case.)
}
break;
}
directives.sort(byPriority);
return directives;
}
/**
* Once the directives have been collected their compile functions is executed. This method
* is responsible for inlining directive templates as well as terminating the application
* of the directives if the terminal directive has been reached..
*
* @param {Array} directives Array of collected directives to execute their compile function.
* this needs to be pre-sorted by priority order.
* @param {Node} compileNode The raw DOM node to apply the compile functions to
* @param {Object} templateAttrs The shared attribute function
* @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the
* scope argument is auto-generated to the new child of the transcluded parent scope.
* @param {DOMElement} $rootElement If we are working on the root of the compile tree then this
* argument has the root jqLite array so that we can replace widgets on it.
* @returns linkFn
*/
function applyDirectivesToNode(directives, compileNode,
templateAttrs, transcludeFn, $rootElement) {
var terminalPriority = -Number.MAX_VALUE,
preLinkFns = [],
postLinkFns = [],
newScopeDirective = null,
newIsolateScopeDirective = null,
templateDirective = null,
$compileNode = templateAttrs.$$element = jqLite(
compileNode),
directive,
directiveName,
$template,
transcludeDirective,
childTranscludeFn = transcludeFn,
controllerDirectives,
linkFn,
directiveValue;
// executes all directives on the current element
for (var i = 0, ii = directives.length; i < ii; i++) {
directive = directives[i];
$template = undefined;
if (terminalPriority > directive.priority) {
break; // prevent further processing of directives
}
if (directiveValue = directive.scope) {
assertNoDuplicate('isolated scope',
newIsolateScopeDirective, directive,
$compileNode);
if (isObject(directiveValue)) {
safeAddClass($compileNode, 'ng-isolate-scope');
newIsolateScopeDirective = directive;
}
safeAddClass($compileNode, 'ng-scope');
newScopeDirective = newScopeDirective || directive;
}
directiveName = directive.name;
if (directiveValue = directive.controller) {
controllerDirectives = controllerDirectives || {};
assertNoDuplicate("'" + directiveName +
"' controller",
controllerDirectives[directiveName], directive,
$compileNode);
controllerDirectives[directiveName] = directive;
}
if (directiveValue = directive.transclude) {
assertNoDuplicate('transclusion',
transcludeDirective, directive, $compileNode);
transcludeDirective = directive;
terminalPriority = directive.priority;
if (directiveValue == 'element') {
$template = jqLite(compileNode);
$compileNode = templateAttrs.$$element =
jqLite(document.createComment(' ' +
directiveName + ': ' + templateAttrs[
directiveName] + ' '));
compileNode = $compileNode[0];
replaceWith($rootElement, jqLite($template[0]),
compileNode);
childTranscludeFn = compile($template,
transcludeFn, terminalPriority);
} else {
$template = jqLite(JQLiteClone(compileNode)).contents();
$compileNode.html(''); // clear contents
childTranscludeFn = compile($template,
transcludeFn);
}
}
if ((directiveValue = directive.template)) {
assertNoDuplicate('template', templateDirective,
directive, $compileNode);
templateDirective = directive;
directiveValue = denormalizeTemplate(directiveValue);
if (directive.replace) {
$template = jqLite('<div>' +
trim(directiveValue) +
'</div>').contents();
compileNode = $template[0];
if ($template.length != 1 || compileNode.nodeType !==
1) {
throw new Error(MULTI_ROOT_TEMPLATE_ERROR +
directiveValue);
}
replaceWith($rootElement, $compileNode,
compileNode);
var newTemplateAttrs = {
$attr: {}
};
// combine directives from the original node and from the template:
// - take the array of directives for this element
// - split it into two parts, those that were already applied and those that weren't
// - collect directives from the template, add them to the second group and sort them
// - append the second group with new directives to the first group
directives = directives.concat(
collectDirectives(
compileNode,
directives.splice(i + 1, directives.length -
(i + 1)),
newTemplateAttrs));
mergeTemplateAttributes(templateAttrs,
newTemplateAttrs);
ii = directives.length;
} else {
$compileNode.html(directiveValue);
}
}
if (directive.templateUrl) {
assertNoDuplicate('template', templateDirective,
directive, $compileNode);
templateDirective = directive;
nodeLinkFn = compileTemplateUrl(directives.splice(i,
directives.length - i),
nodeLinkFn, $compileNode, templateAttrs,
$rootElement, directive.replace,
childTranscludeFn);
ii = directives.length;
} else if (directive.compile) {
try {
linkFn = directive.compile($compileNode,
templateAttrs, childTranscludeFn);
if (isFunction(linkFn)) {
addLinkFns(null, linkFn);
} else if (linkFn) {
addLinkFns(linkFn.pre, linkFn.post);
}
} catch (e) {
$exceptionHandler(e, startingTag($compileNode));
}
}
if (directive.terminal) {
nodeLinkFn.terminal = true;
terminalPriority = Math.max(terminalPriority,
directive.priority);
}
}
nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope;
nodeLinkFn.transclude = transcludeDirective &&
childTranscludeFn;
// might be normal or delayed nodeLinkFn depending on if templateUrl is present
return nodeLinkFn;
////////////////////
function addLinkFns(pre, post) {
if (pre) {
pre.require = directive.require;
preLinkFns.push(pre);
}
if (post) {
post.require = directive.require;
postLinkFns.push(post);
}
}
function getControllers(require, $element) {
var value, retrievalMethod = 'data',
optional = false;
if (isString(require)) {
while ((value = require.charAt(0)) == '^' || value ==
'?') {
require = require.substr(1);
if (value == '^') {
retrievalMethod = 'inheritedData';
}
optional = optional || value == '?';
}
value = $element[retrievalMethod]('$' + require +
'Controller');
if (!value && !optional) {
throw Error("No controller: " + require);
}
return value;
} else if (isArray(require)) {
value = [];
forEach(require, function(require) {
value.push(getControllers(require, $element));
});
}
return value;
}
function nodeLinkFn(childLinkFn, scope, linkNode,
$rootElement, boundTranscludeFn) {
var attrs, $element, i, ii, linkFn, controller;
if (compileNode === linkNode) {
attrs = templateAttrs;
} else {
attrs = shallowCopy(templateAttrs, new Attributes(
jqLite(linkNode), templateAttrs.$attr));
}
$element = attrs.$$element;
if (newIsolateScopeDirective) {
var LOCAL_REGEXP = /^\s*([@=&])\s*(\w*)\s*$/;
var parentScope = scope.$parent || scope;
forEach(newIsolateScopeDirective.scope, function(
definiton, scopeName) {
var match = definiton.match(LOCAL_REGEXP) || [],
attrName = match[2] || scopeName,
mode = match[1], // @, =, or &
lastValue,
parentGet, parentSet;
scope.$$isolateBindings[scopeName] = mode +
attrName;
switch (mode) {
case '@':
{
attrs.$observe(attrName, function(
value) {
scope[scopeName] = value;
});
attrs.$$observers[attrName].$$scope =
parentScope;
break;
}
case '=':
{
parentGet = $parse(attrs[attrName]);
parentSet = parentGet.assign || function() {
// reset the change, or we will throw this exception on every $digest
lastValue = scope[scopeName] =
parentGet(parentScope);
throw Error(
NON_ASSIGNABLE_MODEL_EXPRESSION +
attrs[attrName] +
' (directive: ' +
newIsolateScopeDirective.name +
')');
};
lastValue = scope[scopeName] =
parentGet(parentScope);
scope.$watch(function parentValueWatch() {
var parentValue = parentGet(
parentScope);
if (parentValue !== scope[
scopeName]) {
// we are out of sync and need to copy
if (parentValue !==
lastValue) {
// parent changed and it has precedence
lastValue = scope[
scopeName] =
parentValue;
} else {
// if the parent can be assigned then do so
parentSet(parentScope,
parentValue =
lastValue = scope[
scopeName]);
}
}
return parentValue;
});
break;
}
case '&':
{
parentGet = $parse(attrs[attrName]);
scope[scopeName] = function(locals) {
return parentGet(parentScope,
locals);
}
break;
}
default:
{
throw Error(
'Invalid isolate scope definition for directive ' +
newIsolateScopeDirective.name +
': ' + definiton);
}
}
});
}
if (controllerDirectives) {
forEach(controllerDirectives, function(directive) {
var locals = {
$scope: scope,
$element: $element,
$attrs: attrs,
$transclude: boundTranscludeFn
};
controller = directive.controller;
if (controller == '@') {
controller = attrs[directive.name];
}
$element.data(
'$' + directive.name + 'Controller',
$controller(controller, locals));
});
}
// PRELINKING
for (i = 0, ii = preLinkFns.length; i < ii; i++) {
try {
linkFn = preLinkFns[i];
linkFn(scope, $element, attrs,
linkFn.require && getControllers(linkFn.require,
$element));
} catch (e) {
$exceptionHandler(e, startingTag($element));
}
}
// RECURSION
childLinkFn && childLinkFn(scope, linkNode.childNodes,
undefined, boundTranscludeFn);
// POSTLINKING
for (i = 0, ii = postLinkFns.length; i < ii; i++) {
try {
linkFn = postLinkFns[i];
linkFn(scope, $element, attrs,
linkFn.require && getControllers(linkFn.require,
$element));
} catch (e) {
$exceptionHandler(e, startingTag($element));
}
}
}
}
/**
* looks up the directive and decorates it with exception handling and proper parameters. We
* call this the boundDirective.
*
* @param {string} name name of the directive to look up.
* @param {string} location The directive must be found in specific format.
* String containing any of theses characters:
*
* * `E`: element name
* * `A': attribute
* * `C`: class
* * `M`: comment
* @returns true if directive was added.
*/
function addDirective(tDirectives, name, location, maxPriority) {
var match = false;
if (hasDirectives.hasOwnProperty(name)) {
for (var directive, directives = $injector.get(name +
Suffix),
i = 0, ii = directives.length; i < ii; i++) {
try {
directive = directives[i];
if ((maxPriority === undefined || maxPriority >
directive.priority) &&
directive.restrict.indexOf(location) != -1) {
tDirectives.push(directive);
match = true;
}
} catch (e) {
$exceptionHandler(e);
}
}
}
return match;
}
/**
* When the element is replaced with HTML template then the new attributes
* on the template need to be merged with the existing attributes in the DOM.
* The desired effect is to have both of the attributes present.
*
* @param {object} dst destination attributes (original DOM)
* @param {object} src source attributes (from the directive template)
*/
function mergeTemplateAttributes(dst, src) {
var srcAttr = src.$attr,
dstAttr = dst.$attr,
$element = dst.$$element;
// reapply the old attributes to the new element
forEach(dst, function(value, key) {
if (key.charAt(0) != '$') {
if (src[key]) {
value += (key === 'style' ? ';' : ' ') + src[
key];
}
dst.$set(key, value, true, srcAttr[key]);
}
});
// copy the new attributes on the old attrs object
forEach(src, function(value, key) {
if (key == 'class') {
safeAddClass($element, value);
dst['class'] = (dst['class'] ? dst['class'] + ' ' :
'') + value;
} else if (key == 'style') {
$element.attr('style', $element.attr('style') + ';' +
value);
} else if (key.charAt(0) != '$' && !dst.hasOwnProperty(
key)) {
dst[key] = value;
dstAttr[key] = srcAttr[key];
}
});
}
function compileTemplateUrl(directives,
beforeTemplateNodeLinkFn, $compileNode, tAttrs,
$rootElement, replace, childTranscludeFn) {
var linkQueue = [],
afterTemplateNodeLinkFn,
afterTemplateChildLinkFn,
beforeTemplateCompileNode = $compileNode[0],
origAsyncDirective = directives.shift(),
// The fact that we have to copy and patch the directive seems wrong!
derivedSyncDirective = extend({}, origAsyncDirective, {
controller: null,
templateUrl: null,
transclude: null,
scope: null
});
$compileNode.html('');
$http.get(origAsyncDirective.templateUrl, {
cache: $templateCache
}).
success(function(content) {
var compileNode, tempTemplateAttrs, $template;
content = denormalizeTemplate(content);
if (replace) {
$template = jqLite('<div>' + trim(content) +
'</div>').contents();
compileNode = $template[0];
if ($template.length != 1 || compileNode.nodeType !==
1) {
throw new Error(MULTI_ROOT_TEMPLATE_ERROR +
content);
}
tempTemplateAttrs = {
$attr: {}
};
replaceWith($rootElement, $compileNode, compileNode);
collectDirectives(compileNode, directives,
tempTemplateAttrs);
mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
} else {
compileNode = beforeTemplateCompileNode;
$compileNode.html(content);
}
directives.unshift(derivedSyncDirective);
afterTemplateNodeLinkFn = applyDirectivesToNode(
directives, compileNode, tAttrs, childTranscludeFn);
afterTemplateChildLinkFn = compileNodes($compileNode[0]
.childNodes, childTranscludeFn);
while (linkQueue.length) {
var controller = linkQueue.pop(),
linkRootElement = linkQueue.pop(),
beforeTemplateLinkNode = linkQueue.pop(),
scope = linkQueue.pop(),
linkNode = compileNode;
if (beforeTemplateLinkNode !==
beforeTemplateCompileNode) {
// it was cloned therefore we have to clone as well.
linkNode = JQLiteClone(compileNode);
replaceWith(linkRootElement, jqLite(
beforeTemplateLinkNode), linkNode);
}
afterTemplateNodeLinkFn(function() {
beforeTemplateNodeLinkFn(
afterTemplateChildLinkFn, scope, linkNode,
$rootElement, controller);
}, scope, linkNode, $rootElement, controller);
}
linkQueue = null;
}).
error(function(response, code, headers, config) {
throw Error('Failed to load template: ' + config.url);
});
return function delayedNodeLinkFn(ignoreChildLinkFn, scope,
node, rootElement, controller) {
if (linkQueue) {
linkQueue.push(scope);
linkQueue.push(node);
linkQueue.push(rootElement);
linkQueue.push(controller);
} else {
afterTemplateNodeLinkFn(function() {
beforeTemplateNodeLinkFn(
afterTemplateChildLinkFn, scope, node,
rootElement, controller);
}, scope, node, rootElement, controller);
}
};
}
/**
* Sorting function for bound directives.
*/
function byPriority(a, b) {
return b.priority - a.priority;
}
function assertNoDuplicate(what, previousDirective, directive,
element) {
if (previousDirective) {
throw Error('Multiple directives [' + previousDirective
.name + ', ' +
directive.name + '] asking for ' + what + ' on: ' +
startingTag(element));
}
}
function addTextInterpolateDirective(directives, text) {
var interpolateFn = $interpolate(text, true);
if (interpolateFn) {
directives.push({
priority: 0,
compile: valueFn(function textInterpolateLinkFn(
scope, node) {
var parent = node.parent(),
bindings = parent.data('$binding') || [];
bindings.push(interpolateFn);
safeAddClass(parent.data('$binding', bindings),
'ng-binding');
scope.$watch(interpolateFn, function interpolateFnWatchAction(
value) {
node[0].nodeValue = value;
});
})
});
}
}
function addAttrInterpolateDirective(node, directives, value,
name) {
var interpolateFn = $interpolate(value, true);
// no interpolation found -> ignore
if (!interpolateFn) return;
directives.push({
priority: 100,
compile: valueFn(function attrInterpolateLinkFn(scope,
element, attr) {
var $$observers = (attr.$$observers || (attr.$$observers = {}));
if (name === 'class') {
// we need to interpolate classes again, in the case the element was replaced
// and therefore the two class attrs got merged - we want to interpolate the result
interpolateFn = $interpolate(attr[name], true);
}
attr[name] = undefined;
($$observers[name] || ($$observers[name] = [])).$$inter =
true;
(attr.$$observers && attr.$$observers[name].$$scope ||
scope).
$watch(interpolateFn, function interpolateFnWatchAction(
value) {
attr.$set(name, value);
});
})
});
}
/**
* This is a special jqLite.replaceWith, which can replace items which
* have no parents, provided that the containing jqLite collection is provided.
*
* @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
* in the root of the tree.
* @param {JqLite} $element The jqLite element which we are going to replace. We keep the shell,
* but replace its DOM node reference.
* @param {Node} newNode The new DOM node.
*/
function replaceWith($rootElement, $element, newNode) {
var oldNode = $element[0],
parent = oldNode.parentNode,
i, ii;
if ($rootElement) {
for (i = 0, ii = $rootElement.length; i < ii; i++) {
if ($rootElement[i] == oldNode) {
$rootElement[i] = newNode;
break;
}
}
}
if (parent) {
parent.replaceChild(newNode, oldNode);
}
newNode[jqLite.expando] = oldNode[jqLite.expando];
$element[0] = newNode;
}
}
];
}
var PREFIX_REGEXP = /^(x[\:\-_]|data[\:\-_])/i;
/**
* Converts all accepted directives format into proper directive name.
* All of these will become 'myDirective':
* my:DiRective
* my-directive
* x-my-directive
* data-my:directive
*
* Also there is special case for Moz prefix starting with upper case letter.
* @param name Name to normalize
*/
function directiveNormalize(name) {
return camelCase(name.replace(PREFIX_REGEXP, ''));
}
/**
* @ngdoc object
* @name ng.$compile.directive.Attributes
* @description
*
* A shared object between directive compile / linking functions which contains normalized DOM element
* attributes. The the values reflect current binding state `{{ }}`. The normalization is needed
* since all of these are treated as equivalent in Angular:
*
* <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
*/
/**
* @ngdoc property
* @name ng.$compile.directive.Attributes#$attr
* @propertyOf ng.$compile.directive.Attributes
* @returns {object} A map of DOM element attribute names to the normalized name. This is
* needed to do reverse lookup from normalized name back to actual name.
*/
/**
* @ngdoc function
* @name ng.$compile.directive.Attributes#$set
* @methodOf ng.$compile.directive.Attributes
* @function
*
* @description
* Set DOM element attribute value.
*
*
* @param {string} name Normalized element attribute name of the property to modify. The name is
* revers translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
* property to the original name.
* @param {string} value Value to set the attribute to.
*/
/**
* Closure compiler type information
*/
function nodesetLinkingFn(
/* angular.Scope */scope,
/* NodeList */nodeList,
/* Element */rootElement,
/* function(Function) */boundTranscludeFn) {}
function directiveLinkingFn(
/* nodesetLinkingFn */nodesetLinkingFn,
/* angular.Scope */scope,
/* Node */node,
/* Element */rootElement,
/* function(Function) */boundTranscludeFn) {}
/**
* @ngdoc object
* @name ng.$controllerProvider
* @description
* The {@link ng.$controller $controller service} is used by Angular to create new
* controllers.
*
* This provider allows controller registration via the
* {@link ng.$controllerProvider#register register} method.
*/
function $ControllerProvider() {
var controllers = {};
/**
* @ngdoc function
* @name ng.$controllerProvider#register
* @methodOf ng.$controllerProvider
* @param {string} name Controller name
* @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
* annotations in the array notation).
*/
this.register = function(name, constructor) {
if (isObject(name)) {
extend(controllers, name)
} else {
controllers[name] = constructor;
}
};
this.$get = ['$injector', '$window',
function($injector, $window) {
/**
* @ngdoc function
* @name ng.$controller
* @requires $injector
*
* @param {Function|string} constructor If called with a function then it's considered to be the
* controller constructor function. Otherwise it's considered to be a string which is used
* to retrieve the controller constructor using the following steps:
*
* * check if a controller with given name is registered via `$controllerProvider`
* * check if evaluating the string on the current scope returns a constructor
* * check `window[constructor]` on the global `window` object
*
* @param {Object} locals Injection locals for Controller.
* @return {Object} Instance of given controller.
*
* @description
* `$controller` service is responsible for instantiating controllers.
*
* It's just a simple call to {@link AUTO.$injector $injector}, but extracted into
* a service, so that one can override this service with {@link https://gist.github.com/1649788
* BC version}.
*/
return function(constructor, locals) {
if (isString(constructor)) {
var name = constructor;
constructor = controllers.hasOwnProperty(name) ?
controllers[name] : getter(locals.$scope, name,
true) || getter($window, name, true);
assertArgFn(constructor, name, true);
}
return $injector.instantiate(constructor, locals);
};
}
];
}
/**
* @ngdoc object
* @name ng.$document
* @requires $window
*
* @description
* A {@link angular.element jQuery (lite)}-wrapped reference to the browser's `window.document`
* element.
*/
function $DocumentProvider() {
this.$get = ['$window',
function(window) {
return jqLite(window.document);
}
];
}
/**
* @ngdoc function
* @name ng.$exceptionHandler
* @requires $log
*
* @description
* Any uncaught exception in angular expressions is delegated to this service.
* The default implementation simply delegates to `$log.error` which logs it into
* the browser console.
*
* In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
* {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
*
* @param {Error} exception Exception associated with the error.
* @param {string=} cause optional information about the context in which
* the error was thrown.
*
*/
function $ExceptionHandlerProvider() {
this.$get = ['$log',
function($log) {
return function(exception, cause) {
$log.error.apply($log, arguments);
};
}
];
}
/**
* @ngdoc object
* @name ng.$interpolateProvider
* @function
*
* @description
*
* Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
*/
function $InterpolateProvider() {
var startSymbol = '{{';
var endSymbol = '}}';
/**
* @ngdoc method
* @name ng.$interpolateProvider#startSymbol
* @methodOf ng.$interpolateProvider
* @description
* Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
*
* @param {string=} value new value to set the starting symbol to.
* @returns {string|self} Returns the symbol when used as getter and self if used as setter.
*/
this.startSymbol = function(value) {
if (value) {
startSymbol = value;
return this;
} else {
return startSymbol;
}
};
/**
* @ngdoc method
* @name ng.$interpolateProvider#endSymbol
* @methodOf ng.$interpolateProvider
* @description
* Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
*
* @param {string=} value new value to set the ending symbol to.
* @returns {string|self} Returns the symbol when used as getter and self if used as setter.
*/
this.endSymbol = function(value) {
if (value) {
endSymbol = value;
return this;
} else {
return endSymbol;
}
};
this.$get = ['$parse',
function($parse) {
var startSymbolLength = startSymbol.length,
endSymbolLength = endSymbol.length;
/**
* @ngdoc function
* @name ng.$interpolate
* @function
*
* @requires $parse
*
* @description
*
* Compiles a string with markup into an interpolation function. This service is used by the
* HTML {@link ng.$compile $compile} service for data binding. See
* {@link ng.$interpolateProvider $interpolateProvider} for configuring the
* interpolation markup.
*
*
<pre>
var $interpolate = ...; // injected
var exp = $interpolate('Hello {{name}}!');
expect(exp({name:'Angular'}).toEqual('Hello Angular!');
</pre>
*
*
* @param {string} text The text with markup to interpolate.
* @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
* embedded expression in order to return an interpolation function. Strings with no
* embedded expression will return null for the interpolation function.
* @returns {function(context)} an interpolation function which is used to compute the interpolated
* string. The function has these parameters:
*
* * `context`: an object against which any expressions embedded in the strings are evaluated
* against.
*
*/
function $interpolate(text, mustHaveExpression) {
var startIndex,
endIndex,
index = 0,
parts = [],
length = text.length,
hasInterpolation = false,
fn,
exp,
concat = [];
while (index < length) {
if (((startIndex = text.indexOf(startSymbol, index)) != -
1) &&
((endIndex = text.indexOf(endSymbol, startIndex +
startSymbolLength)) != -1)) {
(index != startIndex) && parts.push(text.substring(
index, startIndex));
parts.push(fn = $parse(exp = text.substring(
startIndex + startSymbolLength, endIndex)));
fn.exp = exp;
index = endIndex + endSymbolLength;
hasInterpolation = true;
} else {
// we did not find anything, so we have to add the remainder to the parts array
(index != length) && parts.push(text.substring(
index));
index = length;
}
}
if (!(length = parts.length)) {
// we added, nothing, must have been an empty string.
parts.push('');
length = 1;
}
if (!mustHaveExpression || hasInterpolation) {
concat.length = length;
fn = function(context) {
for (var i = 0, ii = length, part; i < ii; i++) {
if (typeof(part = parts[i]) == 'function') {
part = part(context);
if (part == null || part == undefined) {
part = '';
} else if (typeof part != 'string') {
part = toJson(part);
}
}
concat[i] = part;
}
return concat.join('');
};
fn.exp = text;
fn.parts = parts;
return fn;
}
}
/**
* @ngdoc method
* @name ng.$interpolate#startSymbol
* @methodOf ng.$interpolate
* @description
* Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
*
* Use {@link ng.$interpolateProvider#startSymbol $interpolateProvider#startSymbol} to change
* the symbol.
*
* @returns {string} start symbol.
*/
$interpolate.startSymbol = function() {
return startSymbol;
}
/**
* @ngdoc method
* @name ng.$interpolate#endSymbol
* @methodOf ng.$interpolate
* @description
* Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
*
* Use {@link ng.$interpolateProvider#endSymbol $interpolateProvider#endSymbol} to change
* the symbol.
*
* @returns {string} start symbol.
*/
$interpolate.endSymbol = function() {
return endSymbol;
}
return $interpolate;
}
];
}
var URL_MATCH =
/^([^:]+):\/\/(\w+:{0,1}\w*@)?(\{?[\w\.-]*\}?)(:([0-9]+))?(\/[^\?#]*)?(\?([^#]*))?(#(.*))?$/,
PATH_MATCH = /^([^\?#]*)?(\?([^#]*))?(#(.*))?$/,
HASH_MATCH = PATH_MATCH,
DEFAULT_PORTS = {
'http': 80,
'https': 443,
'ftp': 21
};
/**
* Encode path using encodeUriSegment, ignoring forward slashes
*
* @param {string} path Path to encode
* @returns {string}
*/
function encodePath(path) {
var segments = path.split('/'),
i = segments.length;
while (i--) {
segments[i] = encodeUriSegment(segments[i]);
}
return segments.join('/');
}
function stripHash(url) {
return url.split('#')[0];
}
function matchUrl(url, obj) {
var match = URL_MATCH.exec(url);
match = {
protocol: match[1],
host: match[3],
port: int(match[5]) || DEFAULT_PORTS[match[1]] || null,
path: match[6] || '/',
search: match[8],
hash: match[10]
};
if (obj) {
obj.$$protocol = match.protocol;
obj.$$host = match.host;
obj.$$port = match.port;
}
return match;
}
function composeProtocolHostPort(protocol, host, port) {
return protocol + '://' + host + (port == DEFAULT_PORTS[protocol] ? '' :
':' + port);
}
function pathPrefixFromBase(basePath) {
return basePath.substr(0, basePath.lastIndexOf('/'));
}
function convertToHtml5Url(url, basePath, hashPrefix) {
var match = matchUrl(url);
// already html5 url
if (decodeURIComponent(match.path) != basePath || isUndefined(match.hash) ||
match.hash.indexOf(hashPrefix) !== 0) {
return url;
// convert hashbang url -> html5 url
} else {
return composeProtocolHostPort(match.protocol, match.host, match.port) +
pathPrefixFromBase(basePath) + match.hash.substr(hashPrefix.length);
}
}
function convertToHashbangUrl(url, basePath, hashPrefix) {
var match = matchUrl(url);
// already hashbang url
if (decodeURIComponent(match.path) == basePath && !isUndefined(match.hash) &&
match.hash.indexOf(hashPrefix) === 0) {
return url;
// convert html5 url -> hashbang url
} else {
var search = match.search && '?' + match.search || '',
hash = match.hash && '#' + match.hash || '',
pathPrefix = pathPrefixFromBase(basePath),
path = match.path.substr(pathPrefix.length);
if (match.path.indexOf(pathPrefix) !== 0) {
throw Error('Invalid url "' + url + '", missing path prefix "' +
pathPrefix + '" !');
}
return composeProtocolHostPort(match.protocol, match.host, match.port) +
basePath +
'#' + hashPrefix + path + search + hash;
}
}
/**
* LocationUrl represents an url
* This object is exposed as $location service when HTML5 mode is enabled and supported
*
* @constructor
* @param {string} url HTML5 url
* @param {string} pathPrefix
*/
function LocationUrl(url, pathPrefix, appBaseUrl) {
pathPrefix = pathPrefix || '';
/**
* Parse given html5 (regular) url string into properties
* @param {string} newAbsoluteUrl HTML5 url
* @private
*/
this.$$parse = function(newAbsoluteUrl) {
var match = matchUrl(newAbsoluteUrl, this);
if (match.path.indexOf(pathPrefix) !== 0) {
throw Error('Invalid url "' + newAbsoluteUrl +
'", missing path prefix "' + pathPrefix + '" !');
}
this.$$path = decodeURIComponent(match.path.substr(pathPrefix.length));
this.$$search = parseKeyValue(match.search);
this.$$hash = match.hash && decodeURIComponent(match.hash) || '';
this.$$compose();
};
/**
* Compose url and update `absUrl` property
* @private
*/
this.$$compose = function() {
var search = toKeyValue(this.$$search),
hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') +
hash;
this.$$absUrl = composeProtocolHostPort(this.$$protocol, this.$$host,
this.$$port) +
pathPrefix + this.$$url;
};
this.$$rewriteAppUrl = function(absoluteLinkUrl) {
if (absoluteLinkUrl.indexOf(appBaseUrl) == 0) {
return absoluteLinkUrl;
}
}
this.$$parse(url);
}
/**
* LocationHashbangUrl represents url
* This object is exposed as $location service when html5 history api is disabled or not supported
*
* @constructor
* @param {string} url Legacy url
* @param {string} hashPrefix Prefix for hash part (containing path and search)
*/
function LocationHashbangUrl(url, hashPrefix, appBaseUrl) {
var basePath;
/**
* Parse given hashbang url into properties
* @param {string} url Hashbang url
* @private
*/
this.$$parse = function(url) {
var match = matchUrl(url, this);
if (match.hash && match.hash.indexOf(hashPrefix) !== 0) {
throw Error('Invalid url "' + url + '", missing hash prefix "' +
hashPrefix + '" !');
}
basePath = match.path + (match.search ? '?' + match.search : '');
match = HASH_MATCH.exec((match.hash || '').substr(hashPrefix.length));
if (match[1]) {
this.$$path = (match[1].charAt(0) == '/' ? '' : '/') +
decodeURIComponent(match[1]);
} else {
this.$$path = '';
}
this.$$search = parseKeyValue(match[3]);
this.$$hash = match[5] && decodeURIComponent(match[5]) || '';
this.$$compose();
};
/**
* Compose hashbang url and update `absUrl` property
* @private
*/
this.$$compose = function() {
var search = toKeyValue(this.$$search),
hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') +
hash;
this.$$absUrl = composeProtocolHostPort(this.$$protocol, this.$$host,
this.$$port) +
basePath + (this.$$url ? '#' + hashPrefix + this.$$url : '');
};
this.$$rewriteAppUrl = function(absoluteLinkUrl) {
if (absoluteLinkUrl.indexOf(appBaseUrl) == 0) {
return absoluteLinkUrl;
}
}
this.$$parse(url);
}
LocationUrl.prototype = {
/**
* Has any change been replacing ?
* @private
*/
$$replace: false,
/**
* @ngdoc method
* @name ng.$location#absUrl
* @methodOf ng.$location
*
* @description
* This method is getter only.
*
* Return full url representation with all segments encoded according to rules specified in
* {@link http://www.ietf.org/rfc/rfc3986.txt RFC 3986}.
*
* @return {string} full url
*/
absUrl: locationGetter('$$absUrl'),
/**
* @ngdoc method
* @name ng.$location#url
* @methodOf ng.$location
*
* @description
* This method is getter / setter.
*
* Return url (e.g. `/path?a=b#hash`) when called without any parameter.
*
* Change path, search and hash, when called with parameter and return `$location`.
*
* @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
* @return {string} url
*/
url: function(url, replace) {
if (isUndefined(url))
return this.$$url;
var match = PATH_MATCH.exec(url);
if (match[1]) this.path(decodeURIComponent(match[1]));
if (match[2] || match[1]) this.search(match[3] || '');
this.hash(match[5] || '', replace);
return this;
},
/**
* @ngdoc method
* @name ng.$location#protocol
* @methodOf ng.$location
*
* @description
* This method is getter only.
*
* Return protocol of current url.
*
* @return {string} protocol of current url
*/
protocol: locationGetter('$$protocol'),
/**
* @ngdoc method
* @name ng.$location#host
* @methodOf ng.$location
*
* @description
* This method is getter only.
*
* Return host of current url.
*
* @return {string} host of current url.
*/
host: locationGetter('$$host'),
/**
* @ngdoc method
* @name ng.$location#port
* @methodOf ng.$location
*
* @description
* This method is getter only.
*
* Return port of current url.
*
* @return {Number} port
*/
port: locationGetter('$$port'),
/**
* @ngdoc method
* @name ng.$location#path
* @methodOf ng.$location
*
* @description
* This method is getter / setter.
*
* Return path of current url when called without any parameter.
*
* Change path when called with parameter and return `$location`.
*
* Note: Path should always begin with forward slash (/), this method will add the forward slash
* if it is missing.
*
* @param {string=} path New path
* @return {string} path
*/
path: locationGetterSetter('$$path', function(path) {
return path.charAt(0) == '/' ? path : '/' + path;
}),
/**
* @ngdoc method
* @name ng.$location#search
* @methodOf ng.$location
*
* @description
* This method is getter / setter.
*
* Return search part (as object) of current url when called without any parameter.
*
* Change search part when called with parameter and return `$location`.
*
* @param {string|object<string,string>=} search New search params - string or hash object
* @param {string=} paramValue If `search` is a string, then `paramValue` will override only a
* single search parameter. If the value is `null`, the parameter will be deleted.
*
* @return {string} search
*/
search: function(search, paramValue) {
if (isUndefined(search))
return this.$$search;
if (isDefined(paramValue)) {
if (paramValue === null) {
delete this.$$search[search];
} else {
this.$$search[search] = paramValue;
}
} else {
this.$$search = isString(search) ? parseKeyValue(search) :
search;
}
this.$$compose();
return this;
},
/**
* @ngdoc method
* @name ng.$location#hash
* @methodOf ng.$location
*
* @description
* This method is getter / setter.
*
* Return hash fragment when called without any parameter.
*
* Change hash fragment when called with parameter and return `$location`.
*
* @param {string=} hash New hash fragment
* @return {string} hash
*/
hash: locationGetterSetter('$$hash', identity),
/**
* @ngdoc method
* @name ng.$location#replace
* @methodOf ng.$location
*
* @description
* If called, all changes to $location during current `$digest` will be replacing current history
* record, instead of adding new one.
*/
replace: function() {
this.$$replace = true;
return this;
}
};
LocationHashbangUrl.prototype = inherit(LocationUrl.prototype);
function LocationHashbangInHtml5Url(url, hashPrefix, appBaseUrl, baseExtra) {
LocationHashbangUrl.apply(this, arguments);
this.$$rewriteAppUrl = function(absoluteLinkUrl) {
if (absoluteLinkUrl.indexOf(appBaseUrl) == 0) {
return appBaseUrl + baseExtra + '#' + hashPrefix +
absoluteLinkUrl.substr(appBaseUrl.length);
}
}
}
LocationHashbangInHtml5Url.prototype = inherit(LocationHashbangUrl.prototype);
function locationGetter(property) {
return function() {
return this[property];
};
}
function locationGetterSetter(property, preprocess) {
return function(value) {
if (isUndefined(value))
return this[property];
this[property] = preprocess(value);
this.$$compose();
return this;
};
}
/**
* @ngdoc object
* @name ng.$location
*
* @requires $browser
* @requires $sniffer
* @requires $rootElement
*
* @description
* The $location service parses the URL in the browser address bar (based on the
* {@link https://developer.mozilla.org/en/window.location window.location}) and makes the URL
* available to your application. Changes to the URL in the address bar are reflected into
* $location service and changes to $location are reflected into the browser address bar.
*
* **The $location service:**
*
* - Exposes the current URL in the browser address bar, so you can
* - Watch and observe the URL.
* - Change the URL.
* - Synchronizes the URL with the browser when the user
* - Changes the address bar.
* - Clicks the back or forward button (or clicks a History link).
* - Clicks on a link.
* - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
*
* For more information see {@link guide/dev_guide.services.$location Developer Guide: Angular
* Services: Using $location}
*/
/**
* @ngdoc object
* @name ng.$locationProvider
* @description
* Use the `$locationProvider` to configure how the application deep linking paths are stored.
*/
function $LocationProvider() {
var hashPrefix = '',
html5Mode = false;
/**
* @ngdoc property
* @name ng.$locationProvider#hashPrefix
* @methodOf ng.$locationProvider
* @description
* @param {string=} prefix Prefix for hash part (containing path and search)
* @returns {*} current value if used as getter or itself (chaining) if used as setter
*/
this.hashPrefix = function(prefix) {
if (isDefined(prefix)) {
hashPrefix = prefix;
return this;
} else {
return hashPrefix;
}
};
/**
* @ngdoc property
* @name ng.$locationProvider#html5Mode
* @methodOf ng.$locationProvider
* @description
* @param {string=} mode Use HTML5 strategy if available.
* @returns {*} current value if used as getter or itself (chaining) if used as setter
*/
this.html5Mode = function(mode) {
if (isDefined(mode)) {
html5Mode = mode;
return this;
} else {
return html5Mode;
}
};
this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement',
function($rootScope, $browser, $sniffer, $rootElement) {
var $location,
basePath,
pathPrefix,
initUrl = $browser.url(),
initUrlParts = matchUrl(initUrl),
appBaseUrl;
if (html5Mode) {
basePath = $browser.baseHref() || '/';
pathPrefix = pathPrefixFromBase(basePath);
appBaseUrl =
composeProtocolHostPort(initUrlParts.protocol,
initUrlParts.host, initUrlParts.port) +
pathPrefix + '/';
if ($sniffer.history) {
$location = new LocationUrl(
convertToHtml5Url(initUrl, basePath, hashPrefix),
pathPrefix, appBaseUrl);
} else {
$location = new LocationHashbangInHtml5Url(
convertToHashbangUrl(initUrl, basePath, hashPrefix),
hashPrefix, appBaseUrl, basePath.substr(pathPrefix.length +
1));
}
} else {
appBaseUrl =
composeProtocolHostPort(initUrlParts.protocol,
initUrlParts.host, initUrlParts.port) +
(initUrlParts.path || '') +
(initUrlParts.search ? ('?' + initUrlParts.search) : '') +
'#' + hashPrefix + '/';
$location = new LocationHashbangUrl(initUrl, hashPrefix,
appBaseUrl);
}
$rootElement.bind('click', function(event) {
// TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
// currently we open nice url link and redirect then
if (event.ctrlKey || event.metaKey || event.which == 2)
return;
var elm = jqLite(event.target);
// traverse the DOM up to find first A tag
while (lowercase(elm[0].nodeName) !== 'a') {
// ignore rewriting if no A tag (reached root element, or no parent - removed from document)
if (elm[0] === $rootElement[0] || !(elm = elm.parent())[
0]) return;
}
var absHref = elm.prop('href'),
rewrittenUrl = $location.$$rewriteAppUrl(absHref);
if (absHref && !elm.attr('target') && rewrittenUrl) {
// update location manually
$location.$$parse(rewrittenUrl);
$rootScope.$apply();
event.preventDefault();
// hack to work around FF6 bug 684208 when scenario runner clicks on links
window.angular['ff-684208-preventDefault'] = true;
}
});
// rewrite hashbang url <> html5 url
if ($location.absUrl() != initUrl) {
$browser.url($location.absUrl(), true);
}
// update $location when $browser url changes
$browser.onUrlChange(function(newUrl) {
if ($location.absUrl() != newUrl) {
$rootScope.$evalAsync(function() {
var oldUrl = $location.absUrl();
$location.$$parse(newUrl);
afterLocationChange(oldUrl);
});
if (!$rootScope.$$phase) $rootScope.$digest();
}
});
// update browser
var changeCounter = 0;
$rootScope.$watch(function $locationWatch() {
var oldUrl = $browser.url();
var currentReplace = $location.$$replace;
if (!changeCounter || oldUrl != $location.absUrl()) {
changeCounter++;
$rootScope.$evalAsync(function() {
if ($rootScope.$broadcast('$locationChangeStart',
$location.absUrl(), oldUrl).defaultPrevented) {
$location.$$parse(oldUrl);
} else {
$browser.url($location.absUrl(), currentReplace);
afterLocationChange(oldUrl);
}
});
}
$location.$$replace = false;
return changeCounter;
});
return $location;
function afterLocationChange(oldUrl) {
$rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(),
oldUrl);
}
}
];
}
/**
* @ngdoc object
* @name ng.$log
* @requires $window
*
* @description
* Simple service for logging. Default implementation writes the message
* into the browser's console (if present).
*
* The main purpose of this service is to simplify debugging and troubleshooting.
*
* @example
<example>
<file name="script.js">
function LogCtrl($scope, $log) {
$scope.$log = $log;
$scope.message = 'Hello World!';
}
</file>
<file name="index.html">
<div ng-controller="LogCtrl">
<p>Reload this page with open console, enter text and hit the log button...</p>
Message:
<input type="text" ng-model="message"/>
<button ng-click="$log.log(message)">log</button>
<button ng-click="$log.warn(message)">warn</button>
<button ng-click="$log.info(message)">info</button>
<button ng-click="$log.error(message)">error</button>
</div>
</file>
</example>
*/
function $LogProvider() {
this.$get = ['$window',
function($window) {
return {
/**
* @ngdoc method
* @name ng.$log#log
* @methodOf ng.$log
*
* @description
* Write a log message
*/
log: consoleLog('log'),
/**
* @ngdoc method
* @name ng.$log#warn
* @methodOf ng.$log
*
* @description
* Write a warning message
*/
warn: consoleLog('warn'),
/**
* @ngdoc method
* @name ng.$log#info
* @methodOf ng.$log
*
* @description
* Write an information message
*/
info: consoleLog('info'),
/**
* @ngdoc method
* @name ng.$log#error
* @methodOf ng.$log
*
* @description
* Write an error message
*/
error: consoleLog('error')
};
function formatError(arg) {
if (arg instanceof Error) {
if (arg.stack) {
arg = (arg.message && arg.stack.indexOf(arg.message) === -
1) ? 'Error: ' + arg.message + '\n' + arg.stack :
arg.stack;
} else if (arg.sourceURL) {
arg = arg.message + '\n' + arg.sourceURL + ':' +
arg.line;
}
}
return arg;
}
function consoleLog(type) {
var console = $window.console || {},
logFn = console[type] || console.log || noop;
if (logFn.apply) {
return function() {
var args = [];
forEach(arguments, function(arg) {
args.push(formatError(arg));
});
return logFn.apply(console, args);
};
}
// we are IE which either doesn't have window.console => this is noop and we do nothing,
// or we are IE where console.log doesn't have apply so we log at least first 2 args
return function(arg1, arg2) {
logFn(arg1, arg2);
}
}
}
];
}
var OPERATORS = {
'null': function() {
return null;
},
'true': function() {
return true;
},
'false': function() {
return false;
},
undefined: noop,
'+': function(self, locals, a, b) {
a = a(self, locals);
b = b(self, locals);
if (isDefined(a)) {
if (isDefined(b)) {
return a + b;
}
return a;
}
return isDefined(b) ? b : undefined;
},
'-': function(self, locals, a, b) {
a = a(self, locals);
b = b(self, locals);
return (isDefined(a) ? a : 0) - (isDefined(b) ? b : 0);
},
'*': function(self, locals, a, b) {
return a(self, locals) * b(self, locals);
},
'/': function(self, locals, a, b) {
return a(self, locals) / b(self, locals);
},
'%': function(self, locals, a, b) {
return a(self, locals) % b(self, locals);
},
'^': function(self, locals, a, b) {
return a(self, locals) ^ b(self, locals);
},
'=': noop,
'==': function(self, locals, a, b) {
return a(self, locals) == b(self, locals);
},
'!=': function(self, locals, a, b) {
return a(self, locals) != b(self, locals);
},
'<': function(self, locals, a, b) {
return a(self, locals) < b(self, locals);
},
'>': function(self, locals, a, b) {
return a(self, locals) > b(self, locals);
},
'<=': function(self, locals, a, b) {
return a(self, locals) <= b(self, locals);
},
'>=': function(self, locals, a, b) {
return a(self, locals) >= b(self, locals);
},
'&&': function(self, locals, a, b) {
return a(self, locals) && b(self, locals);
},
'||': function(self, locals, a, b) {
return a(self, locals) || b(self, locals);
},
'&': function(self, locals, a, b) {
return a(self, locals) & b(self, locals);
},
// '|':function(self, locals, a,b){return a|b;},
'|': function(self, locals, a, b) {
return b(self, locals)(self, locals, a(self, locals));
},
'!': function(self, locals, a) {
return !a(self, locals);
}
};
var ESCAPE = {
"n": "\n",
"f": "\f",
"r": "\r",
"t": "\t",
"v": "\v",
"'": "'",
'"': '"'
};
function lex(text, csp) {
var tokens = [],
token,
index = 0,
json = [],
ch,
lastCh = ':'; // can start regexp
while (index < text.length) {
ch = text.charAt(index);
if (is('"\'')) {
readString(ch);
} else if (isNumber(ch) || is('.') && isNumber(peek())) {
readNumber();
} else if (isIdent(ch)) {
readIdent();
// identifiers can only be if the preceding char was a { or ,
if (was('{,') && json[0] == '{' &&
(token = tokens[tokens.length - 1])) {
token.json = token.text.indexOf('.') == -1;
}
} else if (is('(){}[].,;:')) {
tokens.push({
index: index,
text: ch,
json: (was(':[,') && is('{[')) || is('}]:,')
});
if (is('{[')) json.unshift(ch);
if (is('}]')) json.shift();
index++;
} else if (isWhitespace(ch)) {
index++;
continue;
} else {
var ch2 = ch + peek(),
fn = OPERATORS[ch],
fn2 = OPERATORS[ch2];
if (fn2) {
tokens.push({
index: index,
text: ch2,
fn: fn2
});
index += 2;
} else if (fn) {
tokens.push({
index: index,
text: ch,
fn: fn,
json: was('[,:') && is('+-')
});
index += 1;
} else {
throwError("Unexpected next character ", index, index + 1);
}
}
lastCh = ch;
}
return tokens;
function is(chars) {
return chars.indexOf(ch) != -1;
}
function was(chars) {
return chars.indexOf(lastCh) != -1;
}
function peek() {
return index + 1 < text.length ? text.charAt(index + 1) : false;
}
function isNumber(ch) {
return '0' <= ch && ch <= '9';
}
function isWhitespace(ch) {
return ch == ' ' || ch == '\r' || ch == '\t' ||
ch == '\n' || ch == '\v' || ch == '\u00A0'; // IE treats non-breaking space as \u00A0
}
function isIdent(ch) {
return 'a' <= ch && ch <= 'z' ||
'A' <= ch && ch <= 'Z' ||
'_' == ch || ch == '$';
}
function isExpOperator(ch) {
return ch == '-' || ch == '+' || isNumber(ch);
}
function throwError(error, start, end) {
end = end || index;
throw Error("Lexer Error: " + error + " at column" +
(isDefined(start) ? "s " + start + "-" + index + " [" + text.substring(
start, end) + "]" : " " + end) +
" in expression [" + text + "].");
}
function readNumber() {
var number = "";
var start = index;
while (index < text.length) {
var ch = lowercase(text.charAt(index));
if (ch == '.' || isNumber(ch)) {
number += ch;
} else {
var peekCh = peek();
if (ch == 'e' && isExpOperator(peekCh)) {
number += ch;
} else if (isExpOperator(ch) &&
peekCh && isNumber(peekCh) &&
number.charAt(number.length - 1) == 'e') {
number += ch;
} else if (isExpOperator(ch) &&
(!peekCh || !isNumber(peekCh)) &&
number.charAt(number.length - 1) == 'e') {
throwError('Invalid exponent');
} else {
break;
}
}
index++;
}
number = 1 * number;
tokens.push({
index: start,
text: number,
json: true,
fn: function() {
return number;
}
});
}
function readIdent() {
var ident = "",
start = index,
lastDot, peekIndex, methodName;
while (index < text.length) {
var ch = text.charAt(index);
if (ch == '.' || isIdent(ch) || isNumber(ch)) {
if (ch == '.') lastDot = index;
ident += ch;
} else {
break;
}
index++;
}
//check if this is not a method invocation and if it is back out to last dot
if (lastDot) {
peekIndex = index;
while (peekIndex < text.length) {
var ch = text.charAt(peekIndex);
if (ch == '(') {
methodName = ident.substr(lastDot - start + 1);
ident = ident.substr(0, lastDot - start);
index = peekIndex;
break;
}
if (isWhitespace(ch)) {
peekIndex++;
} else {
break;
}
}
}
var token = {
index: start,
text: ident
};
if (OPERATORS.hasOwnProperty(ident)) {
token.fn = token.json = OPERATORS[ident];
} else {
var getter = getterFn(ident, csp);
token.fn = extend(function(self, locals) {
return (getter(self, locals));
}, {
assign: function(self, value) {
return setter(self, ident, value);
}
});
}
tokens.push(token);
if (methodName) {
tokens.push({
index: lastDot,
text: '.',
json: false
});
tokens.push({
index: lastDot + 1,
text: methodName,
json: false
});
}
}
function readString(quote) {
var start = index;
index++;
var string = "";
var rawString = quote;
var escape = false;
while (index < text.length) {
var ch = text.charAt(index);
rawString += ch;
if (escape) {
if (ch == 'u') {
var hex = text.substring(index + 1, index + 5);
if (!hex.match(/[\da-f]{4}/i))
throwError("Invalid unicode escape [\\u" + hex +
"]");
index += 4;
string += String.fromCharCode(parseInt(hex, 16));
} else {
var rep = ESCAPE[ch];
if (rep) {
string += rep;
} else {
string += ch;
}
}
escape = false;
} else if (ch == '\\') {
escape = true;
} else if (ch == quote) {
index++;
tokens.push({
index: start,
text: rawString,
string: string,
json: true,
fn: function() {
return string;
}
});
return;
} else {
string += ch;
}
index++;
}
throwError("Unterminated quote", start);
}
}
/////////////////////////////////////////
function parser(text, json, $filter, csp) {
var ZERO = valueFn(0),
value,
tokens = lex(text, csp),
assignment = _assignment,
functionCall = _functionCall,
fieldAccess = _fieldAccess,
objectIndex = _objectIndex,
filterChain = _filterChain;
if (json) {
// The extra level of aliasing is here, just in case the lexer misses something, so that
// we prevent any accidental execution in JSON.
assignment = logicalOR;
functionCall =
fieldAccess =
objectIndex =
filterChain = function() {
throwError("is not valid json", {
text: text,
index: 0
});
};
value = primary();
} else {
value = statements();
}
if (tokens.length !== 0) {
throwError("is an unexpected token", tokens[0]);
}
return value;
///////////////////////////////////
function throwError(msg, token) {
throw Error("Syntax Error: Token '" + token.text +
"' " + msg + " at column " +
(token.index + 1) + " of the expression [" +
text + "] starting at [" + text.substring(token.index) + "].");
}
function peekToken() {
if (tokens.length === 0)
throw Error("Unexpected end of expression: " + text);
return tokens[0];
}
function peek(e1, e2, e3, e4) {
if (tokens.length > 0) {
var token = tokens[0];
var t = token.text;
if (t == e1 || t == e2 || t == e3 || t == e4 ||
(!e1 && !e2 && !e3 && !e4)) {
return token;
}
}
return false;
}
function expect(e1, e2, e3, e4) {
var token = peek(e1, e2, e3, e4);
if (token) {
if (json && !token.json) {
throwError("is not valid json", token);
}
tokens.shift();
return token;
}
return false;
}
function consume(e1) {
if (!expect(e1)) {
throwError("is unexpected, expecting [" + e1 + "]", peek());
}
}
function unaryFn(fn, right) {
return function(self, locals) {
return fn(self, locals, right);
};
}
function binaryFn(left, fn, right) {
return function(self, locals) {
return fn(self, locals, left, right);
};
}
function statements() {
var statements = [];
while (true) {
if (tokens.length > 0 && !peek('}', ')', ';', ']'))
statements.push(filterChain());
if (!expect(';')) {
// optimize for the common case where there is only one statement.
// TODO(size): maybe we should not support multiple statements?
return statements.length == 1 ? statements[0] : function(
self, locals) {
var value;
for (var i = 0; i < statements.length; i++) {
var statement = statements[i];
if (statement)
value = statement(self, locals);
}
return value;
};
}
}
}
function _filterChain() {
var left = expression();
var token;
while (true) {
if ((token = expect('|'))) {
left = binaryFn(left, token.fn, filter());
} else {
return left;
}
}
}
function filter() {
var token = expect();
var fn = $filter(token.text);
var argsFn = [];
while (true) {
if ((token = expect(':'))) {
argsFn.push(expression());
} else {
var fnInvoke = function(self, locals, input) {
var args = [input];
for (var i = 0; i < argsFn.length; i++) {
args.push(argsFn[i](self, locals));
}
return fn.apply(self, args);
};
return function() {
return fnInvoke;
};
}
}
}
function expression() {
return assignment();
}
function _assignment() {
var left = logicalOR();
var right;
var token;
if ((token = expect('='))) {
if (!left.assign) {
throwError("implies assignment but [" +
text.substring(0, token.index) +
"] can not be assigned to", token);
}
right = logicalOR();
return function(self, locals) {
return left.assign(self, right(self, locals), locals);
};
} else {
return left;
}
}
function logicalOR() {
var left = logicalAND();
var token;
while (true) {
if ((token = expect('||'))) {
left = binaryFn(left, token.fn, logicalAND());
} else {
return left;
}
}
}
function logicalAND() {
var left = equality();
var token;
if ((token = expect('&&'))) {
left = binaryFn(left, token.fn, logicalAND());
}
return left;
}
function equality() {
var left = relational();
var token;
if ((token = expect('==', '!='))) {
left = binaryFn(left, token.fn, equality());
}
return left;
}
function relational() {
var left = additive();
var token;
if ((token = expect('<', '>', '<=', '>='))) {
left = binaryFn(left, token.fn, relational());
}
return left;
}
function additive() {
var left = multiplicative();
var token;
while ((token = expect('+', '-'))) {
left = binaryFn(left, token.fn, multiplicative());
}
return left;
}
function multiplicative() {
var left = unary();
var token;
while ((token = expect('*', '/', '%'))) {
left = binaryFn(left, token.fn, unary());
}
return left;
}
function unary() {
var token;
if (expect('+')) {
return primary();
} else if ((token = expect('-'))) {
return binaryFn(ZERO, token.fn, unary());
} else if ((token = expect('!'))) {
return unaryFn(token.fn, unary());
} else {
return primary();
}
}
function primary() {
var primary;
if (expect('(')) {
primary = filterChain();
consume(')');
} else if (expect('[')) {
primary = arrayDeclaration();
} else if (expect('{')) {
primary = object();
} else {
var token = expect();
primary = token.fn;
if (!primary) {
throwError("not a primary expression", token);
}
}
var next, context;
while ((next = expect('(', '[', '.'))) {
if (next.text === '(') {
primary = functionCall(primary, context);
context = null;
} else if (next.text === '[') {
context = primary;
primary = objectIndex(primary);
} else if (next.text === '.') {
context = primary;
primary = fieldAccess(primary);
} else {
throwError("IMPOSSIBLE");
}
}
return primary;
}
function _fieldAccess(object) {
var field = expect().text;
var getter = getterFn(field, csp);
return extend(function(self, locals) {
return getter(object(self, locals), locals);
}, {
assign: function(self, value, locals) {
return setter(object(self, locals), field, value);
}
});
}
function _objectIndex(obj) {
var indexFn = expression();
consume(']');
return extend(function(self, locals) {
var o = obj(self, locals),
i = indexFn(self, locals),
v, p;
if (!o) return undefined;
v = o[i];
if (v && v.then) {
p = v;
if (!('$$v' in v)) {
p.$$v = undefined;
p.then(function(val) {
p.$$v = val;
});
}
v = v.$$v;
}
return v;
}, {
assign: function(self, value, locals) {
return obj(self, locals)[indexFn(self, locals)] = value;
}
});
}
function _functionCall(fn, contextGetter) {
var argsFn = [];
if (peekToken().text != ')') {
do {
argsFn.push(expression());
} while (expect(','));
}
consume(')');
return function(self, locals) {
var args = [],
context = contextGetter ? contextGetter(self, locals) :
self;
for (var i = 0; i < argsFn.length; i++) {
args.push(argsFn[i](self, locals));
}
var fnPtr = fn(self, locals) || noop;
// IE stupidity!
return fnPtr.apply ? fnPtr.apply(context, args) : fnPtr(args[0],
args[1], args[2], args[3], args[4]);
};
}
// This is used with json array declaration
function arrayDeclaration() {
var elementFns = [];
if (peekToken().text != ']') {
do {
elementFns.push(expression());
} while (expect(','));
}
consume(']');
return function(self, locals) {
var array = [];
for (var i = 0; i < elementFns.length; i++) {
array.push(elementFns[i](self, locals));
}
return array;
};
}
function object() {
var keyValues = [];
if (peekToken().text != '}') {
do {
var token = expect(),
key = token.string || token.text;
consume(":");
var value = expression();
keyValues.push({
key: key,
value: value
});
} while (expect(','));
}
consume('}');
return function(self, locals) {
var object = {};
for (var i = 0; i < keyValues.length; i++) {
var keyValue = keyValues[i];
var value = keyValue.value(self, locals);
object[keyValue.key] = value;
}
return object;
};
}
}
//////////////////////////////////////////////////
// Parser helper functions
//////////////////////////////////////////////////
function setter(obj, path, setValue) {
var element = path.split('.');
for (var i = 0; element.length > 1; i++) {
var key = element.shift();
var propertyObj = obj[key];
if (!propertyObj) {
propertyObj = {};
obj[key] = propertyObj;
}
obj = propertyObj;
}
obj[element.shift()] = setValue;
return setValue;
}
/**
* Return the value accesible from the object by path. Any undefined traversals are ignored
* @param {Object} obj starting object
* @param {string} path path to traverse
* @param {boolean=true} bindFnToScope
* @returns value as accesbile by path
*/
//TODO(misko): this function needs to be removed
function getter(obj, path, bindFnToScope) {
if (!path) return obj;
var keys = path.split('.');
var key;
var lastInstance = obj;
var len = keys.length;
for (var i = 0; i < len; i++) {
key = keys[i];
if (obj) {
obj = (lastInstance = obj)[key];
}
}
if (!bindFnToScope && isFunction(obj)) {
return bind(lastInstance, obj);
}
return obj;
}
var getterFnCache = {};
/**
* Implementation of the "Black Hole" variant from:
* - http://jsperf.com/angularjs-parse-getter/4
* - http://jsperf.com/path-evaluation-simplified/7
*/
function cspSafeGetterFn(key0, key1, key2, key3, key4) {
return function(scope, locals) {
var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals :
scope,
promise;
if (pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key0];
if (pathVal && pathVal.then) {
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) {
promise.$$v = val;
});
}
pathVal = pathVal.$$v;
}
if (!key1 || pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key1];
if (pathVal && pathVal.then) {
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) {
promise.$$v = val;
});
}
pathVal = pathVal.$$v;
}
if (!key2 || pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key2];
if (pathVal && pathVal.then) {
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) {
promise.$$v = val;
});
}
pathVal = pathVal.$$v;
}
if (!key3 || pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key3];
if (pathVal && pathVal.then) {
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) {
promise.$$v = val;
});
}
pathVal = pathVal.$$v;
}
if (!key4 || pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key4];
if (pathVal && pathVal.then) {
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) {
promise.$$v = val;
});
}
pathVal = pathVal.$$v;
}
return pathVal;
};
};
function getterFn(path, csp) {
if (getterFnCache.hasOwnProperty(path)) {
return getterFnCache[path];
}
var pathKeys = path.split('.'),
pathKeysLength = pathKeys.length,
fn;
if (csp) {
fn = (pathKeysLength < 6) ? cspSafeGetterFn(pathKeys[0], pathKeys[1],
pathKeys[2], pathKeys[3], pathKeys[4]) : function(scope, locals) {
var i = 0,
val
do {
val = cspSafeGetterFn(
pathKeys[i++], pathKeys[i++], pathKeys[i++],
pathKeys[i++], pathKeys[i++])(scope, locals);
locals = undefined; // clear after first iteration
scope = val;
} while (i < pathKeysLength);
return val;
}
} else {
var code = 'var l, fn, p;\n';
forEach(pathKeys, function(key, index) {
code += 'if(s === null || s === undefined) return s;\n' +
'l=s;\n' +
's=' + (index
// we simply dereference 's' on any .dot notation
? 's'
// but if we are first then we check locals first, and if so read it first
: '((k&&k.hasOwnProperty("' + key + '"))?k:s)') + '["' + key +
'"]' + ';\n' +
'if (s && s.then) {\n' +
' if (!("$$v" in s)) {\n' +
' p=s;\n' +
' p.$$v = undefined;\n' +
' p.then(function(v) {p.$$v=v;});\n' +
'}\n' +
' s=s.$$v\n' +
'}\n';
});
code += 'return s;';
fn = Function('s', 'k', code); // s=scope, k=locals
fn.toString = function() {
return code;
};
}
return getterFnCache[path] = fn;
}
///////////////////////////////////
/**
* @ngdoc function
* @name ng.$parse
* @function
*
* @description
*
* Converts Angular {@link guide/expression expression} into a function.
*
* <pre>
* var getter = $parse('user.name');
* var setter = getter.assign;
* var context = {user:{name:'angular'}};
* var locals = {user:{name:'local'}};
*
* expect(getter(context)).toEqual('angular');
* setter(context, 'newValue');
* expect(context.user.name).toEqual('newValue');
* expect(getter(context, locals)).toEqual('local');
* </pre>
*
*
* @param {string} expression String expression to compile.
* @returns {function(context, locals)} a function which represents the compiled expression:
*
* * `context` – `{object}` – an object against which any expressions embedded in the strings
* are evaluated against (tipically a scope object).
* * `locals` – `{object=}` – local variables context object, useful for overriding values in
* `context`.
*
* The return function also has an `assign` property, if the expression is assignable, which
* allows one to set values to expressions.
*
*/
function $ParseProvider() {
var cache = {};
this.$get = ['$filter', '$sniffer',
function($filter, $sniffer) {
return function(exp) {
switch (typeof exp) {
case 'string':
return cache.hasOwnProperty(exp) ? cache[exp] :
cache[exp] = parser(exp, false, $filter,
$sniffer.csp);
case 'function':
return exp;
default:
return noop;
}
};
}
];
}
/**
* @ngdoc service
* @name ng.$q
* @requires $rootScope
*
* @description
* A promise/deferred implementation inspired by [Kris Kowal's Q](https://github.com/kriskowal/q).
*
* [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
* interface for interacting with an object that represents the result of an action that is
* performed asynchronously, and may or may not be finished at any given point in time.
*
* From the perspective of dealing with error handling, deferred and promise APIs are to
* asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
*
* <pre>
* // for the purpose of this example let's assume that variables `$q` and `scope` are
* // available in the current lexical scope (they could have been injected or passed in).
*
* function asyncGreet(name) {
* var deferred = $q.defer();
*
* setTimeout(function() {
* // since this fn executes async in a future turn of the event loop, we need to wrap
* // our code into an $apply call so that the model changes are properly observed.
* scope.$apply(function() {
* if (okToGreet(name)) {
* deferred.resolve('Hello, ' + name + '!');
* } else {
* deferred.reject('Greeting ' + name + ' is not allowed.');
* }
* });
* }, 1000);
*
* return deferred.promise;
* }
*
* var promise = asyncGreet('Robin Hood');
* promise.then(function(greeting) {
* alert('Success: ' + greeting);
* }, function(reason) {
* alert('Failed: ' + reason);
* });
* </pre>
*
* At first it might not be obvious why this extra complexity is worth the trouble. The payoff
* comes in the way of
* [guarantees that promise and deferred APIs make](https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md).
*
* Additionally the promise api allows for composition that is very hard to do with the
* traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
* For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
* section on serial or parallel joining of promises.
*
*
* # The Deferred API
*
* A new instance of deferred is constructed by calling `$q.defer()`.
*
* The purpose of the deferred object is to expose the associated Promise instance as well as APIs
* that can be used for signaling the successful or unsuccessful completion of the task.
*
* **Methods**
*
* - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
* constructed via `$q.reject`, the promise will be rejected instead.
* - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
* resolving it with a rejection constructed via `$q.reject`.
*
* **Properties**
*
* - promise – `{Promise}` – promise object associated with this deferred.
*
*
* # The Promise API
*
* A new promise instance is created when a deferred instance is created and can be retrieved by
* calling `deferred.promise`.
*
* The purpose of the promise object is to allow for interested parties to get access to the result
* of the deferred task when it completes.
*
* **Methods**
*
* - `then(successCallback, errorCallback)` – regardless of when the promise was or will be resolved
* or rejected calls one of the success or error callbacks asynchronously as soon as the result
* is available. The callbacks are called with a single argument the result or rejection reason.
*
* This method *returns a new promise* which is resolved or rejected via the return value of the
* `successCallback` or `errorCallback`.
*
*
* # Chaining promises
*
* Because calling `then` api of a promise returns a new derived promise, it is easily possible
* to create a chain of promises:
*
* <pre>
* promiseB = promiseA.then(function(result) {
* return result + 1;
* });
*
* // promiseB will be resolved immediately after promiseA is resolved and its value will be
* // the result of promiseA incremented by 1
* </pre>
*
* It is possible to create chains of any length and since a promise can be resolved with another
* promise (which will defer its resolution further), it is possible to pause/defer resolution of
* the promises at any point in the chain. This makes it possible to implement powerful apis like
* $http's response interceptors.
*
*
* # Differences between Kris Kowal's Q and $q
*
* There are three main differences:
*
* - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
* mechanism in angular, which means faster propagation of resolution or rejection into your
* models and avoiding unnecessary browser repaints, which would result in flickering UI.
* - $q promises are recognized by the templating engine in angular, which means that in templates
* you can treat promises attached to a scope as if they were the resulting values.
* - Q has many more features that $q, but that comes at a cost of bytes. $q is tiny, but contains
* all the important functionality needed for common async tasks.
*
* # Testing
*
* <pre>
* it('should simulate promise', inject(function($q, $rootScope) {
* var deferred = $q.defer();
* var promise = deferred.promise;
* var resolvedValue;
*
* promise.then(function(value) { resolvedValue = value; });
* expect(resolvedValue).toBeUndefined();
*
* // Simulate resolving of promise
* deferred.resolve(123);
* // Note that the 'then' function does not get called synchronously.
* // This is because we want the promise API to always be async, whether or not
* // it got called synchronously or asynchronously.
* expect(resolvedValue).toBeUndefined();
*
* // Propagate promise resolution to 'then' functions using $apply().
* $rootScope.$apply();
* expect(resolvedValue).toEqual(123);
* });
* </pre>
*/
function $QProvider() {
this.$get = ['$rootScope', '$exceptionHandler',
function($rootScope, $exceptionHandler) {
return qFactory(function(callback) {
$rootScope.$evalAsync(callback);
}, $exceptionHandler);
}
];
}
/**
* Constructs a promise manager.
*
* @param {function(function)} nextTick Function for executing functions in the next turn.
* @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
* debugging purposes.
* @returns {object} Promise manager.
*/
function qFactory(nextTick, exceptionHandler) {
/**
* @ngdoc
* @name ng.$q#defer
* @methodOf ng.$q
* @description
* Creates a `Deferred` object which represents a task which will finish in the future.
*
* @returns {Deferred} Returns a new instance of deferred.
*/
var defer = function() {
var pending = [],
value, deferred;
deferred = {
resolve: function(val) {
if (pending) {
var callbacks = pending;
pending = undefined;
value = ref(val);
if (callbacks.length) {
nextTick(function() {
var callback;
for (var i = 0, ii = callbacks.length; i < ii; i++) {
callback = callbacks[i];
value.then(callback[0], callback[1]);
}
});
}
}
},
reject: function(reason) {
deferred.resolve(reject(reason));
},
promise: {
then: function(callback, errback) {
var result = defer();
var wrappedCallback = function(value) {
try {
result.resolve((callback || defaultCallback)(
value));
} catch (e) {
exceptionHandler(e);
result.reject(e);
}
};
var wrappedErrback = function(reason) {
try {
result.resolve((errback || defaultErrback)(
reason));
} catch (e) {
exceptionHandler(e);
result.reject(e);
}
};
if (pending) {
pending.push([wrappedCallback, wrappedErrback]);
} else {
value.then(wrappedCallback, wrappedErrback);
}
return result.promise;
}
}
};
return deferred;
};
var ref = function(value) {
if (value && value.then) return value;
return {
then: function(callback) {
var result = defer();
nextTick(function() {
result.resolve(callback(value));
});
return result.promise;
}
};
};
/**
* @ngdoc
* @name ng.$q#reject
* @methodOf ng.$q
* @description
* Creates a promise that is resolved as rejected with the specified `reason`. This api should be
* used to forward rejection in a chain of promises. If you are dealing with the last promise in
* a promise chain, you don't need to worry about it.
*
* When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
* `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
* a promise error callback and you want to forward the error to the promise derived from the
* current promise, you have to "rethrow" the error by returning a rejection constructed via
* `reject`.
*
* <pre>
* promiseB = promiseA.then(function(result) {
* // success: do something and resolve promiseB
* // with the old or a new result
* return result;
* }, function(reason) {
* // error: handle the error if possible and
* // resolve promiseB with newPromiseOrValue,
* // otherwise forward the rejection to promiseB
* if (canHandle(reason)) {
* // handle the error and recover
* return newPromiseOrValue;
* }
* return $q.reject(reason);
* });
* </pre>
*
* @param {*} reason Constant, message, exception or an object representing the rejection reason.
* @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
*/
var reject = function(reason) {
return {
then: function(callback, errback) {
var result = defer();
nextTick(function() {
result.resolve((errback || defaultErrback)(reason));
});
return result.promise;
}
};
};
/**
* @ngdoc
* @name ng.$q#when
* @methodOf ng.$q
* @description
* Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
* This is useful when you are dealing with an object that might or might not be a promise, or if
* the promise comes from a source that can't be trusted.
*
* @param {*} value Value or a promise
* @returns {Promise} Returns a single promise that will be resolved with an array of values,
* each value corresponding to the promise at the same index in the `promises` array. If any of
* the promises is resolved with a rejection, this resulting promise will be resolved with the
* same rejection.
*/
var when = function(value, callback, errback) {
var result = defer(),
done;
var wrappedCallback = function(value) {
try {
return (callback || defaultCallback)(value);
} catch (e) {
exceptionHandler(e);
return reject(e);
}
};
var wrappedErrback = function(reason) {
try {
return (errback || defaultErrback)(reason);
} catch (e) {
exceptionHandler(e);
return reject(e);
}
};
nextTick(function() {
ref(value).then(function(value) {
if (done) return;
done = true;
result.resolve(ref(value).then(wrappedCallback,
wrappedErrback));
}, function(reason) {
if (done) return;
done = true;
result.resolve(wrappedErrback(reason));
});
});
return result.promise;
};
function defaultCallback(value) {
return value;
}
function defaultErrback(reason) {
return reject(reason);
}
/**
* @ngdoc
* @name ng.$q#all
* @methodOf ng.$q
* @description
* Combines multiple promises into a single promise that is resolved when all of the input
* promises are resolved.
*
* @param {Array.<Promise>} promises An array of promises.
* @returns {Promise} Returns a single promise that will be resolved with an array of values,
* each value corresponding to the promise at the same index in the `promises` array. If any of
* the promises is resolved with a rejection, this resulting promise will be resolved with the
* same rejection.
*/
function all(promises) {
var deferred = defer(),
counter = promises.length,
results = [];
if (counter) {
forEach(promises, function(promise, index) {
ref(promise).then(function(value) {
if (index in results) return;
results[index] = value;
if (!(--counter)) deferred.resolve(results);
}, function(reason) {
if (index in results) return;
deferred.reject(reason);
});
});
} else {
deferred.resolve(results);
}
return deferred.promise;
}
return {
defer: defer,
reject: reject,
when: when,
all: all
};
}
/**
* @ngdoc object
* @name ng.$routeProvider
* @function
*
* @description
*
* Used for configuring routes. See {@link ng.$route $route} for an example.
*/
function $RouteProvider() {
var routes = {};
/**
* @ngdoc method
* @name ng.$routeProvider#when
* @methodOf ng.$routeProvider
*
* @param {string} path Route path (matched against `$location.path`). If `$location.path`
* contains redundant trailing slash or is missing one, the route will still match and the
* `$location.path` will be updated to add or drop the trailing slash to exactly match the
* route definition.
*
* `path` can contain named groups starting with a colon (`:name`). All characters up to the
* next slash are matched and stored in `$routeParams` under the given `name` when the route
* matches.
*
* @param {Object} route Mapping information to be assigned to `$route.current` on route
* match.
*
* Object properties:
*
* - `controller` – `{(string|function()=}` – Controller fn that should be associated with newly
* created scope or the name of a {@link angular.Module#controller registered controller}
* if passed as a string.
* - `template` – `{string=}` – html template as a string that should be used by
* {@link ng.directive:ngView ngView} or
* {@link ng.directive:ngInclude ngInclude} directives.
* this property takes precedence over `templateUrl`.
* - `templateUrl` – `{string=}` – path to an html template that should be used by
* {@link ng.directive:ngView ngView}.
* - `resolve` - `{Object.<string, function>=}` - An optional map of dependencies which should
* be injected into the controller. If any of these dependencies are promises, they will be
* resolved and converted to a value before the controller is instantiated and the
* `$routeChangeSuccess` event is fired. The map object is:
*
* - `key` – `{string}`: a name of a dependency to be injected into the controller.
* - `factory` - `{string|function}`: If `string` then it is an alias for a service.
* Otherwise if function, then it is {@link api/AUTO.$injector#invoke injected}
* and the return value is treated as the dependency. If the result is a promise, it is resolved
* before its value is injected into the controller.
*
* - `redirectTo` – {(string|function())=} – value to update
* {@link ng.$location $location} path with and trigger route redirection.
*
* If `redirectTo` is a function, it will be called with the following parameters:
*
* - `{Object.<string>}` - route parameters extracted from the current
* `$location.path()` by applying the current route templateUrl.
* - `{string}` - current `$location.path()`
* - `{Object}` - current `$location.search()`
*
* The custom `redirectTo` function is expected to return a string which will be used
* to update `$location.path()` and `$location.search()`.
*
* - `[reloadOnSearch=true]` - {boolean=} - reload route when only $location.search()
* changes.
*
* If the option is set to `false` and url in the browser changes, then
* `$routeUpdate` event is broadcasted on the root scope.
*
* @returns {Object} self
*
* @description
* Adds a new route definition to the `$route` service.
*/
this.when = function(path, route) {
routes[path] = extend({
reloadOnSearch: true
}, route);
// create redirection for trailing slashes
if (path) {
var redirectPath = (path[path.length - 1] == '/') ? path.substr(
0, path.length - 1) : path + '/';
routes[redirectPath] = {
redirectTo: path
};
}
return this;
};
/**
* @ngdoc method
* @name ng.$routeProvider#otherwise
* @methodOf ng.$routeProvider
*
* @description
* Sets route definition that will be used on route change when no other route definition
* is matched.
*
* @param {Object} params Mapping information to be assigned to `$route.current`.
* @returns {Object} self
*/
this.otherwise = function(params) {
this.when(null, params);
return this;
};
this.$get = ['$rootScope', '$location', '$routeParams', '$q',
'$injector', '$http', '$templateCache',
function($rootScope, $location, $routeParams, $q, $injector, $http,
$templateCache) {
/**
* @ngdoc object
* @name ng.$route
* @requires $location
* @requires $routeParams
*
* @property {Object} current Reference to the current route definition.
* The route definition contains:
*
* - `controller`: The controller constructor as define in route definition.
* - `locals`: A map of locals which is used by {@link ng.$controller $controller} service for
* controller instantiation. The `locals` contain
* the resolved values of the `resolve` map. Additionally the `locals` also contain:
*
* - `$scope` - The current route scope.
* - `$template` - The current route template HTML.
*
* @property {Array.<Object>} routes Array of all configured routes.
*
* @description
* Is used for deep-linking URLs to controllers and views (HTML partials).
* It watches `$location.url()` and tries to map the path to an existing route definition.
*
* You can define routes through {@link ng.$routeProvider $routeProvider}'s API.
*
* The `$route` service is typically used in conjunction with {@link ng.directive:ngView ngView}
* directive and the {@link ng.$routeParams $routeParams} service.
*
* @example
This example shows how changing the URL hash causes the `$route` to match a route against the
URL, and the `ngView` pulls in the partial.
Note that this example is using {@link ng.directive:script inlined templates}
to get it working on jsfiddle as well.
<example module="ngView">
<file name="index.html">
<div ng-controller="MainCntl">
Choose:
<a href="Book/Moby">Moby</a> |
<a href="Book/Moby/ch/1">Moby: Ch1</a> |
<a href="Book/Gatsby">Gatsby</a> |
<a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
<a href="Book/Scarlet">Scarlet Letter</a><br/>
<div ng-view></div>
<hr />
<pre>$location.path() = {{$location.path()}}</pre>
<pre>$route.current.templateUrl = {{$route.current.templateUrl}}</pre>
<pre>$route.current.params = {{$route.current.params}}</pre>
<pre>$route.current.scope.name = {{$route.current.scope.name}}</pre>
<pre>$routeParams = {{$routeParams}}</pre>
</div>
</file>
<file name="book.html">
controller: {{name}}<br />
Book Id: {{params.bookId}}<br />
</file>
<file name="chapter.html">
controller: {{name}}<br />
Book Id: {{params.bookId}}<br />
Chapter Id: {{params.chapterId}}
</file>
<file name="script.js">
angular.module('ngView', [], function($routeProvider, $locationProvider) {
$routeProvider.when('/Book/:bookId', {
templateUrl: 'book.html',
controller: BookCntl,
resolve: {
// I will cause a 1 second delay
delay: function($q, $timeout) {
var delay = $q.defer();
$timeout(delay.resolve, 1000);
return delay.promise;
}
}
});
$routeProvider.when('/Book/:bookId/ch/:chapterId', {
templateUrl: 'chapter.html',
controller: ChapterCntl
});
// configure html5 to get links working on jsfiddle
$locationProvider.html5Mode(true);
});
function MainCntl($scope, $route, $routeParams, $location) {
$scope.$route = $route;
$scope.$location = $location;
$scope.$routeParams = $routeParams;
}
function BookCntl($scope, $routeParams) {
$scope.name = "BookCntl";
$scope.params = $routeParams;
}
function ChapterCntl($scope, $routeParams) {
$scope.name = "ChapterCntl";
$scope.params = $routeParams;
}
</file>
<file name="scenario.js">
it('should load and compile correct template', function() {
element('a:contains("Moby: Ch1")').click();
var content = element('.doc-example-live [ng-view]').text();
expect(content).toMatch(/controller\: ChapterCntl/);
expect(content).toMatch(/Book Id\: Moby/);
expect(content).toMatch(/Chapter Id\: 1/);
element('a:contains("Scarlet")').click();
sleep(2); // promises are not part of scenario waiting
content = element('.doc-example-live [ng-view]').text();
expect(content).toMatch(/controller\: BookCntl/);
expect(content).toMatch(/Book Id\: Scarlet/);
});
</file>
</example>
*/
/**
* @ngdoc event
* @name ng.$route#$routeChangeStart
* @eventOf ng.$route
* @eventType broadcast on root scope
* @description
* Broadcasted before a route change. At this point the route services starts
* resolving all of the dependencies needed for the route change to occurs.
* Typically this involves fetching the view template as well as any dependencies
* defined in `resolve` route property. Once all of the dependencies are resolved
* `$routeChangeSuccess` is fired.
*
* @param {Route} next Future route information.
* @param {Route} current Current route information.
*/
/**
* @ngdoc event
* @name ng.$route#$routeChangeSuccess
* @eventOf ng.$route
* @eventType broadcast on root scope
* @description
* Broadcasted after a route dependencies are resolved.
* {@link ng.directive:ngView ngView} listens for the directive
* to instantiate the controller and render the view.
*
* @param {Object} angularEvent Synthetic event object.
* @param {Route} current Current route information.
* @param {Route|Undefined} previous Previous route information, or undefined if current is first route entered.
*/
/**
* @ngdoc event
* @name ng.$route#$routeChangeError
* @eventOf ng.$route
* @eventType broadcast on root scope
* @description
* Broadcasted if any of the resolve promises are rejected.
*
* @param {Route} current Current route information.
* @param {Route} previous Previous route information.
* @param {Route} rejection Rejection of the promise. Usually the error of the failed promise.
*/
/**
* @ngdoc event
* @name ng.$route#$routeUpdate
* @eventOf ng.$route
* @eventType broadcast on root scope
* @description
*
* The `reloadOnSearch` property has been set to false, and we are reusing the same
* instance of the Controller.
*/
var forceReload = false,
$route = {
routes: routes,
/**
* @ngdoc method
* @name ng.$route#reload
* @methodOf ng.$route
*
* @description
* Causes `$route` service to reload the current route even if
* {@link ng.$location $location} hasn't changed.
*
* As a result of that, {@link ng.directive:ngView ngView}
* creates new scope, reinstantiates the controller.
*/
reload: function() {
forceReload = true;
$rootScope.$evalAsync(updateRoute);
}
};
$rootScope.$on('$locationChangeSuccess', updateRoute);
return $route;
/////////////////////////////////////////////////////
/**
* @param on {string} current url
* @param when {string} route when template to match the url against
* @return {?Object}
*/
function switchRouteMatcher(on, when) {
// TODO(i): this code is convoluted and inefficient, we should construct the route matching
// regex only once and then reuse it
// Escape regexp special characters.
when = '^' + when.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&") +
'$';
var regex = '',
params = [],
dst = {};
var re = /:(\w+)/g,
paramMatch,
lastMatchedIndex = 0;
while ((paramMatch = re.exec(when)) !== null) {
// Find each :param in `when` and replace it with a capturing group.
// Append all other sections of when unchanged.
regex += when.slice(lastMatchedIndex, paramMatch.index);
regex += '([^\\/]*)';
params.push(paramMatch[1]);
lastMatchedIndex = re.lastIndex;
}
// Append trailing path part.
regex += when.substr(lastMatchedIndex);
var match = on.match(new RegExp(regex));
if (match) {
forEach(params, function(name, index) {
dst[name] = match[index + 1];
});
}
return match ? dst : null;
}
function updateRoute() {
var next = parseRoute(),
last = $route.current;
if (next && last && next.$$route === last.$$route && equals(
next.pathParams, last.pathParams) && !next.reloadOnSearch && !
forceReload) {
last.params = next.params;
copy(last.params, $routeParams);
$rootScope.$broadcast('$routeUpdate', last);
} else if (next || last) {
forceReload = false;
$rootScope.$broadcast('$routeChangeStart', next, last);
$route.current = next;
if (next) {
if (next.redirectTo) {
if (isString(next.redirectTo)) {
$location.path(interpolate(next.redirectTo,
next.params)).search(next.params)
.replace();
} else {
$location.url(next.redirectTo(next.pathParams,
$location.path(), $location.search()))
.replace();
}
}
}
$q.when(next).
then(function() {
if (next) {
var keys = [],
values = [],
template;
forEach(next.resolve || {}, function(value, key) {
keys.push(key);
values.push(isString(value) ? $injector.get(
value) : $injector.invoke(value));
});
if (isDefined(template = next.template)) {} else if (
isDefined(template = next.templateUrl)) {
template = $http.get(template, {
cache: $templateCache
}).
then(function(response) {
return response.data;
});
}
if (isDefined(template)) {
keys.push('$template');
values.push(template);
}
return $q.all(values).then(function(values) {
var locals = {};
forEach(values, function(value, index) {
locals[keys[index]] = value;
});
return locals;
});
}
}).
// after route change
then(function(locals) {
if (next == $route.current) {
if (next) {
next.locals = locals;
copy(next.params, $routeParams);
}
$rootScope.$broadcast('$routeChangeSuccess',
next, last);
}
}, function(error) {
if (next == $route.current) {
$rootScope.$broadcast('$routeChangeError', next,
last, error);
}
});
}
}
/**
* @returns the current active route, by matching it against the URL
*/
function parseRoute() {
// Match a route
var params, match;
forEach(routes, function(route, path) {
if (!match && (params = switchRouteMatcher($location.path(),
path))) {
match = inherit(route, {
params: extend({}, $location.search(), params),
pathParams: params
});
match.$$route = route;
}
});
// No route matched; fallback to "otherwise" route
return match || routes[null] && inherit(routes[null], {
params: {},
pathParams: {}
});
}
/**
* @returns interpolation of the redirect path with the parametrs
*/
function interpolate(string, params) {
var result = [];
forEach((string || '').split(':'), function(segment, i) {
if (i == 0) {
result.push(segment);
} else {
var segmentMatch = segment.match(/(\w+)(.*)/);
var key = segmentMatch[1];
result.push(params[key]);
result.push(segmentMatch[2] || '');
delete params[key];
}
});
return result.join('');
}
}
];
}
/**
* @ngdoc object
* @name ng.$routeParams
* @requires $route
*
* @description
* Current set of route parameters. The route parameters are a combination of the
* {@link ng.$location $location} `search()`, and `path()`. The `path` parameters
* are extracted when the {@link ng.$route $route} path is matched.
*
* In case of parameter name collision, `path` params take precedence over `search` params.
*
* The service guarantees that the identity of the `$routeParams` object will remain unchanged
* (but its properties will likely change) even when a route change occurs.
*
* @example
* <pre>
* // Given:
* // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
* // Route: /Chapter/:chapterId/Section/:sectionId
* //
* // Then
* $routeParams ==> {chapterId:1, sectionId:2, search:'moby'}
* </pre>
*/
function $RouteParamsProvider() {
this.$get = valueFn({});
}
/**
* DESIGN NOTES
*
* The design decisions behind the scope ware heavily favored for speed and memory consumption.
*
* The typical use of scope is to watch the expressions, which most of the time return the same
* value as last time so we optimize the operation.
*
* Closures construction is expensive from speed as well as memory:
* - no closures, instead ups prototypical inheritance for API
* - Internal state needs to be stored on scope directly, which means that private state is
* exposed as $$____ properties
*
* Loop operations are optimized by using while(count--) { ... }
* - this means that in order to keep the same order of execution as addition we have to add
* items to the array at the begging (shift) instead of at the end (push)
*
* Child scopes are created and removed often
* - Using array would be slow since inserts in meddle are expensive so we use linked list
*
* There are few watches then a lot of observers. This is why you don't want the observer to be
* implemented in the same way as watch. Watch requires return of initialization function which
* are expensive to construct.
*/
/**
* @ngdoc object
* @name ng.$rootScopeProvider
* @description
*
* Provider for the $rootScope service.
*/
/**
* @ngdoc function
* @name ng.$rootScopeProvider#digestTtl
* @methodOf ng.$rootScopeProvider
* @description
*
* Sets the number of digest iteration the scope should attempt to execute before giving up and
* assuming that the model is unstable.
*
* The current default is 10 iterations.
*
* @param {number} limit The number of digest iterations.
*/
/**
* @ngdoc object
* @name ng.$rootScope
* @description
*
* Every application has a single root {@link ng.$rootScope.Scope scope}.
* All other scopes are child scopes of the root scope. Scopes provide mechanism for watching the model and provide
* event processing life-cycle. See {@link guide/scope developer guide on scopes}.
*/
function $RootScopeProvider() {
var TTL = 10;
this.digestTtl = function(value) {
if (arguments.length) {
TTL = value;
}
return TTL;
};
this.$get = ['$injector', '$exceptionHandler', '$parse',
function($injector, $exceptionHandler, $parse) {
/**
* @ngdoc function
* @name ng.$rootScope.Scope
*
* @description
* A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
* {@link AUTO.$injector $injector}. Child scopes are created using the
* {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
* compiled HTML template is executed.)
*
* Here is a simple scope snippet to show how you can interact with the scope.
* <pre>
angular.injector(['ng']).invoke(function($rootScope) {
var scope = $rootScope.$new();
scope.salutation = 'Hello';
scope.name = 'World';
expect(scope.greeting).toEqual(undefined);
scope.$watch('name', function() {
scope.greeting = scope.salutation + ' ' + scope.name + '!';
}); // initialize the watch
expect(scope.greeting).toEqual(undefined);
scope.name = 'Misko';
// still old value, since watches have not been called yet
expect(scope.greeting).toEqual(undefined);
scope.$digest(); // fire all the watches
expect(scope.greeting).toEqual('Hello Misko!');
});
* </pre>
*
* # Inheritance
* A scope can inherit from a parent scope, as in this example:
* <pre>
var parent = $rootScope;
var child = parent.$new();
parent.salutation = "Hello";
child.name = "World";
expect(child.salutation).toEqual('Hello');
child.salutation = "Welcome";
expect(child.salutation).toEqual('Welcome');
expect(parent.salutation).toEqual('Hello');
* </pre>
*
*
* @param {Object.<string, function()>=} providers Map of service factory which need to be provided
* for the current scope. Defaults to {@link ng}.
* @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
* append/override services provided by `providers`. This is handy when unit-testing and having
* the need to override a default service.
* @returns {Object} Newly created scope.
*
*/
function Scope() {
this.$id = nextUid();
this.$$phase = this.$parent = this.$$watchers =
this.$$nextSibling = this.$$prevSibling =
this.$$childHead = this.$$childTail = null;
this['this'] = this.$root = this;
this.$$destroyed = false;
this.$$asyncQueue = [];
this.$$listeners = {};
this.$$isolateBindings = {};
}
/**
* @ngdoc property
* @name ng.$rootScope.Scope#$id
* @propertyOf ng.$rootScope.Scope
* @returns {number} Unique scope ID (monotonically increasing alphanumeric sequence) useful for
* debugging.
*/
Scope.prototype = {
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$new
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Creates a new child {@link ng.$rootScope.Scope scope}.
*
* The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} and
* {@link ng.$rootScope.Scope#$digest $digest()} events. The scope can be removed from the scope
* hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
*
* {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is desired for
* the scope and its child scopes to be permanently detached from the parent and thus stop
* participating in model change detection and listener notification by invoking.
*
* @param {boolean} isolate if true then the scope does not prototypically inherit from the
* parent scope. The scope is isolated, as it can not see parent scope properties.
* When creating widgets it is useful for the widget to not accidentally read parent
* state.
*
* @returns {Object} The newly created child scope.
*
*/
$new: function(isolate) {
var Child,
child;
if (isFunction(isolate)) {
// TODO: remove at some point
throw Error(
'API-CHANGE: Use $controller to instantiate controllers.');
}
if (isolate) {
child = new Scope();
child.$root = this.$root;
} else {
Child = function() {}; // should be anonymous; This is so that when the minifier munges
// the name it does not become random set of chars. These will then show up as class
// name in the debugger.
Child.prototype = this;
child = new Child();
child.$id = nextUid();
}
child['this'] = child;
child.$$listeners = {};
child.$parent = this;
child.$$asyncQueue = [];
child.$$watchers = child.$$nextSibling = child.$$childHead =
child.$$childTail = null;
child.$$prevSibling = this.$$childTail;
if (this.$$childHead) {
this.$$childTail.$$nextSibling = child;
this.$$childTail = child;
} else {
this.$$childHead = this.$$childTail = child;
}
return child;
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$watch
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Registers a `listener` callback to be executed whenever the `watchExpression` changes.
*
* - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest $digest()} and
* should return the value which will be watched. (Since {@link ng.$rootScope.Scope#$digest $digest()}
* reruns when it detects changes the `watchExpression` can execute multiple times per
* {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.)
* - The `listener` is called only when the value from the current `watchExpression` and the
* previous call to `watchExpression` are not equal (with the exception of the initial run,
* see below). The inequality is determined according to
* {@link angular.equals} function. To save the value of the object for later comparison, the
* {@link angular.copy} function is used. It also means that watching complex options will
* have adverse memory and performance implications.
* - The watch `listener` may change the model, which may trigger other `listener`s to fire. This
* is achieved by rerunning the watchers until no changes are detected. The rerun iteration
* limit is 10 to prevent an infinite loop deadlock.
*
*
* If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
* you can register a `watchExpression` function with no `listener`. (Since `watchExpression`
* can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a change is
* detected, be prepared for multiple calls to your listener.)
*
* After a watcher is registered with the scope, the `listener` fn is called asynchronously
* (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
* watcher. In rare cases, this is undesirable because the listener is called when the result
* of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
* can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
* listener was called due to initialization.
*
*
* # Example
* <pre>
// let's assume that scope was dependency injected as the $rootScope
var scope = $rootScope;
scope.name = 'misko';
scope.counter = 0;
expect(scope.counter).toEqual(0);
scope.$watch('name', function(newValue, oldValue) { scope.counter = scope.counter + 1; });
expect(scope.counter).toEqual(0);
scope.$digest();
// no variable change
expect(scope.counter).toEqual(0);
scope.name = 'adam';
scope.$digest();
expect(scope.counter).toEqual(1);
* </pre>
*
*
*
* @param {(function()|string)} watchExpression Expression that is evaluated on each
* {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers a
* call to the `listener`.
*
* - `string`: Evaluated as {@link guide/expression expression}
* - `function(scope)`: called with current `scope` as a parameter.
* @param {(function()|string)=} listener Callback called whenever the return value of
* the `watchExpression` changes.
*
* - `string`: Evaluated as {@link guide/expression expression}
* - `function(newValue, oldValue, scope)`: called with current and previous values as parameters.
*
* @param {boolean=} objectEquality Compare object for equality rather than for reference.
* @returns {function()} Returns a deregistration function for this listener.
*/
$watch: function(watchExp, listener, objectEquality) {
var scope = this,
get = compileToFn(watchExp, 'watch'),
array = scope.$$watchers,
watcher = {
fn: listener,
last: initWatchVal,
get: get,
exp: watchExp,
eq: !! objectEquality
};
// in the case user pass string, we need to compile it, do we really need this ?
if (!isFunction(listener)) {
var listenFn = compileToFn(listener || noop,
'listener');
watcher.fn = function(newVal, oldVal, scope) {
listenFn(scope);
};
}
if (!array) {
array = scope.$$watchers = [];
}
// we use unshift since we use a while loop in $digest for speed.
// the while loop reads in reverse order.
array.unshift(watcher);
return function() {
arrayRemove(array, watcher);
};
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$digest
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Process all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and its children.
* Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change the model, the
* `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers} until no more listeners are
* firing. This means that it is possible to get into an infinite loop. This function will throw
* `'Maximum iteration limit exceeded.'` if the number of iterations exceeds 10.
*
* Usually you don't call `$digest()` directly in
* {@link ng.directive:ngController controllers} or in
* {@link ng.$compileProvider#directive directives}.
* Instead a call to {@link ng.$rootScope.Scope#$apply $apply()} (typically from within a
* {@link ng.$compileProvider#directive directives}) will force a `$digest()`.
*
* If you want to be notified whenever `$digest()` is called,
* you can register a `watchExpression` function with {@link ng.$rootScope.Scope#$watch $watch()}
* with no `listener`.
*
* You may have a need to call `$digest()` from within unit-tests, to simulate the scope
* life-cycle.
*
* # Example
* <pre>
var scope = ...;
scope.name = 'misko';
scope.counter = 0;
expect(scope.counter).toEqual(0);
scope.$watch('name', function(newValue, oldValue) {
scope.counter = scope.counter + 1;
});
expect(scope.counter).toEqual(0);
scope.$digest();
// no variable change
expect(scope.counter).toEqual(0);
scope.name = 'adam';
scope.$digest();
expect(scope.counter).toEqual(1);
* </pre>
*
*/
$digest: function() {
var watch, value, last,
watchers,
asyncQueue,
length,
dirty, ttl = TTL,
next, current, target = this,
watchLog = [],
logIdx, logMsg;
beginPhase('$digest');
do {
dirty = false;
current = target;
do {
asyncQueue = current.$$asyncQueue;
while (asyncQueue.length) {
try {
current.$eval(asyncQueue.shift());
} catch (e) {
$exceptionHandler(e);
}
}
if ((watchers = current.$$watchers)) {
// process our watches
length = watchers.length;
while (length--) {
try {
watch = watchers[length];
// Most common watches are on primitives, in which case we can short
// circuit it with === operator, only when === fails do we use .equals
if ((value = watch.get(current)) !==
(last = watch.last) && !(watch.eq ?
equals(value, last) : (typeof value ==
'number' && typeof last ==
'number' && isNaN(value) &&
isNaN(last)))) {
dirty = true;
watch.last = watch.eq ? copy(
value) : value;
watch.fn(value, ((last ===
initWatchVal) ? value :
last), current);
if (ttl < 5) {
logIdx = 4 - ttl;
if (!watchLog[logIdx])
watchLog[logIdx] = [];
logMsg = (isFunction(watch.exp)) ?
'fn: ' + (watch.exp.name ||
watch.exp.toString()) :
watch.exp;
logMsg += '; newVal: ' +
toJson(value) +
'; oldVal: ' + toJson(
last);
watchLog[logIdx].push(
logMsg);
}
}
} catch (e) {
$exceptionHandler(e);
}
}
}
// Insanity Warning: scope depth-first traversal
// yes, this code is a bit crazy, but it works and we have tests to prove it!
// this piece should be kept in sync with the traversal in $broadcast
if (!(next = (current.$$childHead || (current !==
target && current.$$nextSibling)))) {
while (current !== target && !(next =
current.$$nextSibling)) {
current = current.$parent;
}
}
} while ((current = next));
if (dirty && !(ttl--)) {
clearPhase();
throw Error(TTL +
' $digest() iterations reached. Aborting!\n' +
'Watchers fired in the last 5 iterations: ' +
toJson(watchLog));
}
} while (dirty || asyncQueue.length);
clearPhase();
},
/**
* @ngdoc event
* @name ng.$rootScope.Scope#$destroy
* @eventOf ng.$rootScope.Scope
* @eventType broadcast on scope being destroyed
*
* @description
* Broadcasted when a scope and its children are being destroyed.
*/
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$destroy
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Removes the current scope (and all of its children) from the parent scope. Removal implies
* that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
* propagate to the current scope and its children. Removal also implies that the current
* scope is eligible for garbage collection.
*
* The `$destroy()` is usually used by directives such as
* {@link ng.directive:ngRepeat ngRepeat} for managing the
* unrolling of the loop.
*
* Just before a scope is destroyed a `$destroy` event is broadcasted on this scope.
* Application code can register a `$destroy` event handler that will give it chance to
* perform any necessary cleanup.
*/
$destroy: function() {
// we can't destroy the root scope or a scope that has been already destroyed
if ($rootScope == this || this.$$destroyed) return;
var parent = this.$parent;
this.$broadcast('$destroy');
this.$$destroyed = true;
if (parent.$$childHead == this) parent.$$childHead =
this.$$nextSibling;
if (parent.$$childTail == this) parent.$$childTail =
this.$$prevSibling;
if (this.$$prevSibling) this.$$prevSibling.$$nextSibling =
this.$$nextSibling;
if (this.$$nextSibling) this.$$nextSibling.$$prevSibling =
this.$$prevSibling;
// This is bogus code that works around Chrome's GC leak
// see: https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
this.$parent = this.$$nextSibling = this.$$prevSibling =
this.$$childHead =
this.$$childTail = null;
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$eval
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Executes the `expression` on the current scope returning the result. Any exceptions in the
* expression are propagated (uncaught). This is useful when evaluating Angular expressions.
*
* # Example
* <pre>
var scope = ng.$rootScope.Scope();
scope.a = 1;
scope.b = 2;
expect(scope.$eval('a+b')).toEqual(3);
expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
* </pre>
*
* @param {(string|function())=} expression An angular expression to be executed.
*
* - `string`: execute using the rules as defined in {@link guide/expression expression}.
* - `function(scope)`: execute the function with the current `scope` parameter.
*
* @returns {*} The result of evaluating the expression.
*/
$eval: function(expr, locals) {
return $parse(expr)(this, locals);
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$evalAsync
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Executes the expression on the current scope at a later point in time.
*
* The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only that:
*
* - it will execute in the current script execution context (before any DOM rendering).
* - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
* `expression` execution.
*
* Any exceptions from the execution of the expression are forwarded to the
* {@link ng.$exceptionHandler $exceptionHandler} service.
*
* @param {(string|function())=} expression An angular expression to be executed.
*
* - `string`: execute using the rules as defined in {@link guide/expression expression}.
* - `function(scope)`: execute the function with the current `scope` parameter.
*
*/
$evalAsync: function(expr) {
this.$$asyncQueue.push(expr);
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$apply
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* `$apply()` is used to execute an expression in angular from outside of the angular framework.
* (For example from browser DOM events, setTimeout, XHR or third party libraries).
* Because we are calling into the angular framework we need to perform proper scope life-cycle
* of {@link ng.$exceptionHandler exception handling},
* {@link ng.$rootScope.Scope#$digest executing watches}.
*
* ## Life cycle
*
* # Pseudo-Code of `$apply()`
* <pre>
function $apply(expr) {
try {
return $eval(expr);
} catch (e) {
$exceptionHandler(e);
} finally {
$root.$digest();
}
}
* </pre>
*
*
* Scope's `$apply()` method transitions through the following stages:
*
* 1. The {@link guide/expression expression} is executed using the
* {@link ng.$rootScope.Scope#$eval $eval()} method.
* 2. Any exceptions from the execution of the expression are forwarded to the
* {@link ng.$exceptionHandler $exceptionHandler} service.
* 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the expression
* was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
*
*
* @param {(string|function())=} exp An angular expression to be executed.
*
* - `string`: execute using the rules as defined in {@link guide/expression expression}.
* - `function(scope)`: execute the function with current `scope` parameter.
*
* @returns {*} The result of evaluating the expression.
*/
$apply: function(expr) {
try {
beginPhase('$apply');
return this.$eval(expr);
} catch (e) {
$exceptionHandler(e);
} finally {
clearPhase();
try {
$rootScope.$digest();
} catch (e) {
$exceptionHandler(e);
throw e;
}
}
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$on
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for discussion of
* event life cycle.
*
* The event listener function format is: `function(event, args...)`. The `event` object
* passed into the listener has the following attributes:
*
* - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or `$broadcast`-ed.
* - `currentScope` - `{Scope}`: the current scope which is handling the event.
* - `name` - `{string}`: Name of the event.
* - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel further event
* propagation (available only for events that were `$emit`-ed).
* - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag to true.
* - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
*
* @param {string} name Event name to listen on.
* @param {function(event, args...)} listener Function to call when the event is emitted.
* @returns {function()} Returns a deregistration function for this listener.
*/
$on: function(name, listener) {
var namedListeners = this.$$listeners[name];
if (!namedListeners) {
this.$$listeners[name] = namedListeners = [];
}
namedListeners.push(listener);
return function() {
namedListeners[indexOf(namedListeners, listener)] =
null;
};
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$emit
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Dispatches an event `name` upwards through the scope hierarchy notifying the
* registered {@link ng.$rootScope.Scope#$on} listeners.
*
* The event life cycle starts at the scope on which `$emit` was called. All
* {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get notified.
* Afterwards, the event traverses upwards toward the root scope and calls all registered
* listeners along the way. The event will stop propagating if one of the listeners cancels it.
*
* Any exception emmited from the {@link ng.$rootScope.Scope#$on listeners} will be passed
* onto the {@link ng.$exceptionHandler $exceptionHandler} service.
*
* @param {string} name Event name to emit.
* @param {...*} args Optional set of arguments which will be passed onto the event listeners.
* @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
*/
$emit: function(name, args) {
var empty = [],
namedListeners,
scope = this,
stopPropagation = false,
event = {
name: name,
targetScope: scope,
stopPropagation: function() {
stopPropagation = true;
},
preventDefault: function() {
event.defaultPrevented = true;
},
defaultPrevented: false
},
listenerArgs = concat([event], arguments, 1),
i, length;
do {
namedListeners = scope.$$listeners[name] || empty;
event.currentScope = scope;
for (i = 0, length = namedListeners.length; i <
length; i++) {
// if listeners were deregistered, defragment the array
if (!namedListeners[i]) {
namedListeners.splice(i, 1);
i--;
length--;
continue;
}
try {
namedListeners[i].apply(null, listenerArgs);
if (stopPropagation) return event;
} catch (e) {
$exceptionHandler(e);
}
}
//traverse upwards
scope = scope.$parent;
} while (scope);
return event;
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$broadcast
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Dispatches an event `name` downwards to all child scopes (and their children) notifying the
* registered {@link ng.$rootScope.Scope#$on} listeners.
*
* The event life cycle starts at the scope on which `$broadcast` was called. All
* {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get notified.
* Afterwards, the event propagates to all direct and indirect scopes of the current scope and
* calls all registered listeners along the way. The event cannot be canceled.
*
* Any exception emmited from the {@link ng.$rootScope.Scope#$on listeners} will be passed
* onto the {@link ng.$exceptionHandler $exceptionHandler} service.
*
* @param {string} name Event name to emit.
* @param {...*} args Optional set of arguments which will be passed onto the event listeners.
* @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
*/
$broadcast: function(name, args) {
var target = this,
current = target,
next = target,
event = {
name: name,
targetScope: target,
preventDefault: function() {
event.defaultPrevented = true;
},
defaultPrevented: false
},
listenerArgs = concat([event], arguments, 1),
listeners, i, length;
//down while you can, then up and next sibling or up and next sibling until back at root
do {
current = next;
event.currentScope = current;
listeners = current.$$listeners[name] || [];
for (i = 0, length = listeners.length; i < length; i++) {
// if listeners were deregistered, defragment the array
if (!listeners[i]) {
listeners.splice(i, 1);
i--;
length--;
continue;
}
try {
listeners[i].apply(null, listenerArgs);
} catch (e) {
$exceptionHandler(e);
}
}
// Insanity Warning: scope depth-first traversal
// yes, this code is a bit crazy, but it works and we have tests to prove it!
// this piece should be kept in sync with the traversal in $digest
if (!(next = (current.$$childHead || (current !==
target && current.$$nextSibling)))) {
while (current !== target && !(next = current.$$nextSibling)) {
current = current.$parent;
}
}
} while ((current = next));
return event;
}
};
var $rootScope = new Scope();
return $rootScope;
function beginPhase(phase) {
if ($rootScope.$$phase) {
throw Error($rootScope.$$phase + ' already in progress');
}
$rootScope.$$phase = phase;
}
function clearPhase() {
$rootScope.$$phase = null;
}
function compileToFn(exp, name) {
var fn = $parse(exp);
assertArgFn(fn, name);
return fn;
}
/**
* function used as an initial value for watchers.
* because it's unique we can easily tell it apart from other values
*/
function initWatchVal() {}
}
];
}
/**
* !!! This is an undocumented "private" service !!!
*
* @name ng.$sniffer
* @requires $window
*
* @property {boolean} history Does the browser support html5 history api ?
* @property {boolean} hashchange Does the browser support hashchange event ?
*
* @description
* This is very simple implementation of testing browser's features.
*/
function $SnifferProvider() {
this.$get = ['$window',
function($window) {
var eventSupport = {},
android = int((/android (\d+)/.exec(lowercase($window.navigator
.userAgent)) || [])[1]);
return {
// Android has history.pushState, but it does not update location correctly
// so let's not use the history API at all.
// http://code.google.com/p/android/issues/detail?id=17471
// https://github.com/angular/angular.js/issues/904
history: !! ($window.history && $window.history.pushState && !
(android < 4)),
hashchange: 'onhashchange' in $window &&
// IE8 compatible mode lies
(!$window.document.documentMode || $window.document.documentMode >
7),
hasEvent: function(event) {
// IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
// it. In particular the event is not fired when backspace or delete key are pressed or
// when cut operation is performed.
if (event == 'input' && msie == 9) return false;
if (isUndefined(eventSupport[event])) {
var divElm = $window.document.createElement('div');
eventSupport[event] = 'on' + event in divElm;
}
return eventSupport[event];
},
// TODO(i): currently there is no way to feature detect CSP without triggering alerts
csp: false
};
}
];
}
/**
* @ngdoc object
* @name ng.$window
*
* @description
* A reference to the browser's `window` object. While `window`
* is globally available in JavaScript, it causes testability problems, because
* it is a global variable. In angular we always refer to it through the
* `$window` service, so it may be overriden, removed or mocked for testing.
*
* All expressions are evaluated with respect to current scope so they don't
* suffer from window globality.
*
* @example
<doc:example>
<doc:source>
<input ng-init="$window = $service('$window'); greeting='Hello World!'" type="text" ng-model="greeting" />
<button ng-click="$window.alert(greeting)">ALERT</button>
</doc:source>
<doc:scenario>
</doc:scenario>
</doc:example>
*/
function $WindowProvider() {
this.$get = valueFn(window);
}
/**
* Parse headers into key value object
*
* @param {string} headers Raw headers as a string
* @returns {Object} Parsed headers as key value object
*/
function parseHeaders(headers) {
var parsed = {}, key, val, i;
if (!headers) return parsed;
forEach(headers.split('\n'), function(line) {
i = line.indexOf(':');
key = lowercase(trim(line.substr(0, i)));
val = trim(line.substr(i + 1));
if (key) {
if (parsed[key]) {
parsed[key] += ', ' + val;
} else {
parsed[key] = val;
}
}
});
return parsed;
}
/**
* Returns a function that provides access to parsed headers.
*
* Headers are lazy parsed when first requested.
* @see parseHeaders
*
* @param {(string|Object)} headers Headers to provide access to.
* @returns {function(string=)} Returns a getter function which if called with:
*
* - if called with single an argument returns a single header value or null
* - if called with no arguments returns an object containing all headers.
*/
function headersGetter(headers) {
var headersObj = isObject(headers) ? headers : undefined;
return function(name) {
if (!headersObj) headersObj = parseHeaders(headers);
if (name) {
return headersObj[lowercase(name)] || null;
}
return headersObj;
};
}
/**
* Chain all given functions
*
* This function is used for both request and response transforming
*
* @param {*} data Data to transform.
* @param {function(string=)} headers Http headers getter fn.
* @param {(function|Array.<function>)} fns Function or an array of functions.
* @returns {*} Transformed data.
*/
function transformData(data, headers, fns) {
if (isFunction(fns))
return fns(data, headers);
forEach(fns, function(fn) {
data = fn(data, headers);
});
return data;
}
function isSuccess(status) {
return 200 <= status && status < 300;
}
function $HttpProvider() {
var JSON_START = /^\s*(\[|\{[^\{])/,
JSON_END = /[\}\]]\s*$/,
PROTECTION_PREFIX = /^\)\]\}',?\n/;
var $config = this.defaults = {
// transform incoming response data
transformResponse: [
function(data) {
if (isString(data)) {
// strip json vulnerability protection prefix
data = data.replace(PROTECTION_PREFIX, '');
if (JSON_START.test(data) && JSON_END.test(data))
data = fromJson(data, true);
}
return data;
}
],
// transform outgoing request data
transformRequest: [
function(d) {
return isObject(d) && !isFile(d) ? toJson(d) : d;
}
],
// default headers
headers: {
common: {
'Accept': 'application/json, text/plain, */*',
'X-Requested-With': 'XMLHttpRequest'
},
post: {
'Content-Type': 'application/json;charset=utf-8'
},
put: {
'Content-Type': 'application/json;charset=utf-8'
}
}
};
var providerResponseInterceptors = this.responseInterceptors = [];
this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope',
'$q', '$injector',
function($httpBackend, $browser, $cacheFactory, $rootScope, $q,
$injector) {
var defaultCache = $cacheFactory('$http'),
responseInterceptors = [];
forEach(providerResponseInterceptors, function(interceptor) {
responseInterceptors.push(
isString(interceptor) ? $injector.get(interceptor) :
$injector.invoke(interceptor));
});
/**
* @ngdoc function
* @name ng.$http
* @requires $httpBackend
* @requires $browser
* @requires $cacheFactory
* @requires $rootScope
* @requires $q
* @requires $injector
*
* @description
* The `$http` service is a core Angular service that facilitates communication with the remote
* HTTP servers via browser's {@link https://developer.mozilla.org/en/xmlhttprequest
* XMLHttpRequest} object or via {@link http://en.wikipedia.org/wiki/JSONP JSONP}.
*
* For unit testing applications that use `$http` service, see
* {@link ngMock.$httpBackend $httpBackend mock}.
*
* For a higher level of abstraction, please check out the {@link ngResource.$resource
* $resource} service.
*
* The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
* the $q service. While for simple usage patters this doesn't matter much, for advanced usage,
* it is important to familiarize yourself with these apis and guarantees they provide.
*
*
* # General usage
* The `$http` service is a function which takes a single argument — a configuration object —
* that is used to generate an http request and returns a {@link ng.$q promise}
* with two $http specific methods: `success` and `error`.
*
* <pre>
* $http({method: 'GET', url: '/someUrl'}).
* success(function(data, status, headers, config) {
* // this callback will be called asynchronously
* // when the response is available
* }).
* error(function(data, status, headers, config) {
* // called asynchronously if an error occurs
* // or server returns response with an error status.
* });
* </pre>
*
* Since the returned value of calling the $http function is a Promise object, you can also use
* the `then` method to register callbacks, and these callbacks will receive a single argument –
* an object representing the response. See the api signature and type info below for more
* details.
*
* A response status code that falls in the [200, 300) range is considered a success status and
* will result in the success callback being called. Note that if the response is a redirect,
* XMLHttpRequest will transparently follow it, meaning that the error callback will not be
* called for such responses.
*
* # Shortcut methods
*
* Since all invocation of the $http service require definition of the http method and url and
* POST and PUT requests require response body/data to be provided as well, shortcut methods
* were created to simplify using the api:
*
* <pre>
* $http.get('/someUrl').success(successCallback);
* $http.post('/someUrl', data).success(successCallback);
* </pre>
*
* Complete list of shortcut methods:
*
* - {@link ng.$http#get $http.get}
* - {@link ng.$http#head $http.head}
* - {@link ng.$http#post $http.post}
* - {@link ng.$http#put $http.put}
* - {@link ng.$http#delete $http.delete}
* - {@link ng.$http#jsonp $http.jsonp}
*
*
* # Setting HTTP Headers
*
* The $http service will automatically add certain http headers to all requests. These defaults
* can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
* object, which currently contains this default configuration:
*
* - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
* - `Accept: application/json, text/plain, * / *`
* - `X-Requested-With: XMLHttpRequest`
* - `$httpProvider.defaults.headers.post`: (header defaults for HTTP POST requests)
* - `Content-Type: application/json`
* - `$httpProvider.defaults.headers.put` (header defaults for HTTP PUT requests)
* - `Content-Type: application/json`
*
* To add or overwrite these defaults, simply add or remove a property from this configuration
* objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
* with name equal to the lower-cased http method name, e.g.
* `$httpProvider.defaults.headers.get['My-Header']='value'`.
*
* Additionally, the defaults can be set at runtime via the `$http.defaults` object in a similar
* fassion as described above.
*
*
* # Transforming Requests and Responses
*
* Both requests and responses can be transformed using transform functions. By default, Angular
* applies these transformations:
*
* Request transformations:
*
* - if the `data` property of the request config object contains an object, serialize it into
* JSON format.
*
* Response transformations:
*
* - if XSRF prefix is detected, strip it (see Security Considerations section below)
* - if json response is detected, deserialize it using a JSON parser
*
* To globally augment or override the default transforms, modify the `$httpProvider.defaults.transformRequest` and
* `$httpProvider.defaults.transformResponse` properties of the `$httpProvider`. These properties are by default an
* array of transform functions, which allows you to `push` or `unshift` a new transformation function into the
* transformation chain. You can also decide to completely override any default transformations by assigning your
* transformation functions to these properties directly without the array wrapper.
*
* Similarly, to locally override the request/response transforms, augment the `transformRequest` and/or
* `transformResponse` properties of the config object passed into `$http`.
*
*
* # Caching
*
* To enable caching set the configuration property `cache` to `true`. When the cache is
* enabled, `$http` stores the response from the server in local cache. Next time the
* response is served from the cache without sending a request to the server.
*
* Note that even if the response is served from cache, delivery of the data is asynchronous in
* the same way that real requests are.
*
* If there are multiple GET requests for the same url that should be cached using the same
* cache, but the cache is not populated yet, only one request to the server will be made and
* the remaining requests will be fulfilled using the response for the first request.
*
*
* # Response interceptors
*
* Before you start creating interceptors, be sure to understand the
* {@link ng.$q $q and deferred/promise APIs}.
*
* For purposes of global error handling, authentication or any kind of synchronous or
* asynchronous preprocessing of received responses, it is desirable to be able to intercept
* responses for http requests before they are handed over to the application code that
* initiated these requests. The response interceptors leverage the {@link ng.$q
* promise apis} to fulfil this need for both synchronous and asynchronous preprocessing.
*
* The interceptors are service factories that are registered with the $httpProvider by
* adding them to the `$httpProvider.responseInterceptors` array. The factory is called and
* injected with dependencies (if specified) and returns the interceptor — a function that
* takes a {@link ng.$q promise} and returns the original or a new promise.
*
* <pre>
* // register the interceptor as a service
* $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
* return function(promise) {
* return promise.then(function(response) {
* // do something on success
* }, function(response) {
* // do something on error
* if (canRecover(response)) {
* return responseOrNewPromise
* }
* return $q.reject(response);
* });
* }
* });
*
* $httpProvider.responseInterceptors.push('myHttpInterceptor');
*
*
* // register the interceptor via an anonymous factory
* $httpProvider.responseInterceptors.push(function($q, dependency1, dependency2) {
* return function(promise) {
* // same as above
* }
* });
* </pre>
*
*
* # Security Considerations
*
* When designing web applications, consider security threats from:
*
* - {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx
* JSON Vulnerability}
* - {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF}
*
* Both server and the client must cooperate in order to eliminate these threats. Angular comes
* pre-configured with strategies that address these issues, but for this to work backend server
* cooperation is required.
*
* ## JSON Vulnerability Protection
*
* A {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx
* JSON Vulnerability} allows third party web-site to turn your JSON resource URL into
* {@link http://en.wikipedia.org/wiki/JSON#JSONP JSONP} request under some conditions. To
* counter this your server can prefix all JSON requests with following string `")]}',\n"`.
* Angular will automatically strip the prefix before processing it as JSON.
*
* For example if your server needs to return:
* <pre>
* ['one','two']
* </pre>
*
* which is vulnerable to attack, your server can return:
* <pre>
* )]}',
* ['one','two']
* </pre>
*
* Angular will strip the prefix, before processing the JSON.
*
*
* ## Cross Site Request Forgery (XSRF) Protection
*
* {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF} is a technique by which
* an unauthorized site can gain your user's private data. Angular provides following mechanism
* to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie
* called `XSRF-TOKEN` and sets it as the HTTP header `X-XSRF-TOKEN`. Since only JavaScript that
* runs on your domain could read the cookie, your server can be assured that the XHR came from
* JavaScript running on your domain.
*
* To take advantage of this, your server needs to set a token in a JavaScript readable session
* cookie called `XSRF-TOKEN` on first HTTP GET request. On subsequent non-GET requests the
* server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
* that only JavaScript running on your domain could have read the token. The token must be
* unique for each user and must be verifiable by the server (to prevent the JavaScript making
* up its own tokens). We recommend that the token is a digest of your site's authentication
* cookie with {@link http://en.wikipedia.org/wiki/Rainbow_table salt for added security}.
*
*
* @param {object} config Object describing the request to be made and how it should be
* processed. The object has following properties:
*
* - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
* - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
* - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be turned to
* `?key1=value1&key2=value2` after the url. If the value is not a string, it will be JSONified.
* - **data** – `{string|Object}` – Data to be sent as the request message data.
* - **headers** – `{Object}` – Map of strings representing HTTP headers to send to the server.
* - **transformRequest** – `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
* transform function or an array of such functions. The transform function takes the http
* request body and headers and returns its transformed (typically serialized) version.
* - **transformResponse** – `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
* transform function or an array of such functions. The transform function takes the http
* response body and headers and returns its transformed (typically deserialized) version.
* - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
* GET request, otherwise if a cache instance built with
* {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
* caching.
* - **timeout** – `{number}` – timeout in milliseconds.
* - **withCredentials** - `{boolean}` - whether to to set the `withCredentials` flag on the
* XHR object. See {@link https://developer.mozilla.org/en/http_access_control#section_5
* requests with credentials} for more information.
*
* @returns {HttpPromise} Returns a {@link ng.$q promise} object with the
* standard `then` method and two http specific methods: `success` and `error`. The `then`
* method takes two arguments a success and an error callback which will be called with a
* response object. The `success` and `error` methods take a single argument - a function that
* will be called when the request succeeds or fails respectively. The arguments passed into
* these functions are destructured representation of the response object passed into the
* `then` method. The response object has these properties:
*
* - **data** – `{string|Object}` – The response body transformed with the transform functions.
* - **status** – `{number}` – HTTP status code of the response.
* - **headers** – `{function([headerName])}` – Header getter function.
* - **config** – `{Object}` – The configuration object that was used to generate the request.
*
* @property {Array.<Object>} pendingRequests Array of config objects for currently pending
* requests. This is primarily meant to be used for debugging purposes.
*
*
* @example
<example>
<file name="index.html">
<div ng-controller="FetchCtrl">
<select ng-model="method">
<option>GET</option>
<option>JSONP</option>
</select>
<input type="text" ng-model="url" size="80"/>
<button ng-click="fetch()">fetch</button><br>
<button ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
<button ng-click="updateModel('JSONP', 'http://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">Sample JSONP</button>
<button ng-click="updateModel('JSONP', 'http://angularjs.org/doesntexist&callback=JSON_CALLBACK')">Invalid JSONP</button>
<pre>http status code: {{status}}</pre>
<pre>http response data: {{data}}</pre>
</div>
</file>
<file name="script.js">
function FetchCtrl($scope, $http, $templateCache) {
$scope.method = 'GET';
$scope.url = 'http-hello.html';
$scope.fetch = function() {
$scope.code = null;
$scope.response = null;
$http({method: $scope.method, url: $scope.url, cache: $templateCache}).
success(function(data, status) {
$scope.status = status;
$scope.data = data;
}).
error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
$scope.updateModel = function(method, url) {
$scope.method = method;
$scope.url = url;
};
}
</file>
<file name="http-hello.html">
Hello, $http!
</file>
<file name="scenario.js">
it('should make an xhr GET request', function() {
element(':button:contains("Sample GET")').click();
element(':button:contains("fetch")').click();
expect(binding('status')).toBe('200');
expect(binding('data')).toMatch(/Hello, \$http!/);
});
it('should make a JSONP request to angularjs.org', function() {
element(':button:contains("Sample JSONP")').click();
element(':button:contains("fetch")').click();
expect(binding('status')).toBe('200');
expect(binding('data')).toMatch(/Super Hero!/);
});
it('should make JSONP request to invalid URL and invoke the error handler',
function() {
element(':button:contains("Invalid JSONP")').click();
element(':button:contains("fetch")').click();
expect(binding('status')).toBe('0');
expect(binding('data')).toBe('Request failed');
});
</file>
</example>
*/
function $http(config) {
config.method = uppercase(config.method);
var reqTransformFn = config.transformRequest || $config.transformRequest,
respTransformFn = config.transformResponse || $config.transformResponse,
defHeaders = $config.headers,
reqHeaders = extend({
'X-XSRF-TOKEN': $browser.cookies()['XSRF-TOKEN']
},
defHeaders.common, defHeaders[lowercase(config.method)],
config.headers),
reqData = transformData(config.data, headersGetter(
reqHeaders), reqTransformFn),
promise;
// strip content-type if data is undefined
if (isUndefined(config.data)) {
delete reqHeaders['Content-Type'];
}
// send request
promise = sendReq(config, reqData, reqHeaders);
// transform future response
promise = promise.then(transformResponse, transformResponse);
// apply interceptors
forEach(responseInterceptors, function(interceptor) {
promise = interceptor(promise);
});
promise.success = function(fn) {
promise.then(function(response) {
fn(response.data, response.status, response.headers,
config);
});
return promise;
};
promise.error = function(fn) {
promise.then(null, function(response) {
fn(response.data, response.status, response.headers,
config);
});
return promise;
};
return promise;
function transformResponse(response) {
// make a copy since the response must be cacheable
var resp = extend({}, response, {
data: transformData(response.data, response.headers,
respTransformFn)
});
return (isSuccess(response.status)) ? resp : $q.reject(
resp);
}
}
$http.pendingRequests = [];
/**
* @ngdoc method
* @name ng.$http#get
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `GET` request
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name ng.$http#delete
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `DELETE` request
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name ng.$http#head
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `HEAD` request
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name ng.$http#jsonp
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `JSONP` request
*
* @param {string} url Relative or absolute URL specifying the destination of the request.
* Should contain `JSON_CALLBACK` string.
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
createShortMethods('get', 'delete', 'head', 'jsonp');
/**
* @ngdoc method
* @name ng.$http#post
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `POST` request
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {*} data Request content
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name ng.$http#put
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `PUT` request
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {*} data Request content
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
createShortMethodsWithData('post', 'put');
/**
* @ngdoc property
* @name ng.$http#defaults
* @propertyOf ng.$http
*
* @description
* Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
* default headers as well as request and response transformations.
*
* See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
*/
$http.defaults = $config;
return $http;
function createShortMethods(names) {
forEach(arguments, function(name) {
$http[name] = function(url, config) {
return $http(extend(config || {}, {
method: name,
url: url
}));
};
});
}
function createShortMethodsWithData(name) {
forEach(arguments, function(name) {
$http[name] = function(url, data, config) {
return $http(extend(config || {}, {
method: name,
url: url,
data: data
}));
};
});
}
/**
* Makes the request
*
* !!! ACCESSES CLOSURE VARS:
* $httpBackend, $config, $log, $rootScope, defaultCache, $http.pendingRequests
*/
function sendReq(config, reqData, reqHeaders) {
var deferred = $q.defer(),
promise = deferred.promise,
cache,
cachedResp,
url = buildUrl(config.url, config.params);
$http.pendingRequests.push(config);
promise.then(removePendingReq, removePendingReq);
if (config.cache && config.method == 'GET') {
cache = isObject(config.cache) ? config.cache :
defaultCache;
}
if (cache) {
cachedResp = cache.get(url);
if (cachedResp) {
if (cachedResp.then) {
// cached request has already been sent, but there is no response yet
cachedResp.then(removePendingReq,
removePendingReq);
return cachedResp;
} else {
// serving from cache
if (isArray(cachedResp)) {
resolvePromise(cachedResp[1], cachedResp[0],
copy(cachedResp[2]));
} else {
resolvePromise(cachedResp, 200, {});
}
}
} else {
// put the promise for the non-transformed response into cache as a placeholder
cache.put(url, promise);
}
}
// if we won't have the response in cache, send the request to the backend
if (!cachedResp) {
$httpBackend(config.method, url, reqData, done,
reqHeaders, config.timeout,
config.withCredentials);
}
return promise;
/**
* Callback registered to $httpBackend():
* - caches the response if desired
* - resolves the raw $http promise
* - calls $apply
*/
function done(status, response, headersString) {
if (cache) {
if (isSuccess(status)) {
cache.put(url, [status, response, parseHeaders(
headersString)]);
} else {
// remove promise from the cache
cache.remove(url);
}
}
resolvePromise(response, status, headersString);
$rootScope.$apply();
}
/**
* Resolves the raw $http promise.
*/
function resolvePromise(response, status, headers) {
// normalize internal statuses to 0
status = Math.max(status, 0);
(isSuccess(status) ? deferred.resolve : deferred.reject)({
data: response,
status: status,
headers: headersGetter(headers),
config: config
});
}
function removePendingReq() {
var idx = indexOf($http.pendingRequests, config);
if (idx !== -1) $http.pendingRequests.splice(idx, 1);
}
}
function buildUrl(url, params) {
if (!params) return url;
var parts = [];
forEachSorted(params, function(value, key) {
if (value == null || value == undefined) return;
if (isObject(value)) {
value = toJson(value);
}
parts.push(encodeURIComponent(key) + '=' +
encodeURIComponent(value));
});
return url + ((url.indexOf('?') == -1) ? '?' : '&') + parts
.join('&');
}
}
];
}
var XHR = window.XMLHttpRequest || function() {
try {
return new ActiveXObject("Msxml2.XMLHTTP.6.0");
} catch (e1) {}
try {
return new ActiveXObject("Msxml2.XMLHTTP.3.0");
} catch (e2) {}
try {
return new ActiveXObject("Msxml2.XMLHTTP");
} catch (e3) {}
throw new Error("This browser does not support XMLHttpRequest.");
};
/**
* @ngdoc object
* @name ng.$httpBackend
* @requires $browser
* @requires $window
* @requires $document
*
* @description
* HTTP backend used by the {@link ng.$http service} that delegates to
* XMLHttpRequest object or JSONP and deals with browser incompatibilities.
*
* You should never need to use this service directly, instead use the higher-level abstractions:
* {@link ng.$http $http} or {@link ngResource.$resource $resource}.
*
* During testing this implementation is swapped with {@link ngMock.$httpBackend mock
* $httpBackend} which can be trained with responses.
*/
function $HttpBackendProvider() {
this.$get = ['$browser', '$window', '$document',
function($browser, $window, $document) {
return createHttpBackend($browser, XHR, $browser.defer, $window
.angular.callbacks,
$document[0], $window.location.protocol.replace(':', ''));
}
];
}
function createHttpBackend($browser, XHR, $browserDefer, callbacks,
rawDocument, locationProtocol) {
// TODO(vojta): fix the signature
return function(method, url, post, callback, headers, timeout,
withCredentials) {
$browser.$$incOutstandingRequestCount();
url = url || $browser.url();
if (lowercase(method) == 'jsonp') {
var callbackId = '_' + (callbacks.counter++).toString(36);
callbacks[callbackId] = function(data) {
callbacks[callbackId].data = data;
};
jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' +
callbackId), function() {
if (callbacks[callbackId].data) {
completeRequest(callback, 200, callbacks[callbackId].data);
} else {
completeRequest(callback, -2);
}
delete callbacks[callbackId];
});
} else {
var xhr = new XHR();
xhr.open(method, url, true);
forEach(headers, function(value, key) {
if (value) xhr.setRequestHeader(key, value);
});
var status;
// In IE6 and 7, this might be called synchronously when xhr.send below is called and the
// response is in the cache. the promise api will ensure that to the app code the api is
// always async
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var responseHeaders = xhr.getAllResponseHeaders();
// TODO(vojta): remove once Firefox 21 gets released.
// begin: workaround to overcome Firefox CORS http response headers bug
// https://bugzilla.mozilla.org/show_bug.cgi?id=608735
// Firefox already patched in nightly. Should land in Firefox 21.
// CORS "simple response headers" http://www.w3.org/TR/cors/
var value,
simpleHeaders = ["Cache-Control",
"Content-Language", "Content-Type",
"Expires", "Last-Modified", "Pragma"
];
if (!responseHeaders) {
responseHeaders = "";
forEach(simpleHeaders, function(header) {
var value = xhr.getResponseHeader(header);
if (value) {
responseHeaders += header + ": " + value +
"\n";
}
});
}
// end of the workaround.
completeRequest(callback, status || xhr.status, xhr.responseText,
responseHeaders);
}
};
if (withCredentials) {
xhr.withCredentials = true;
}
xhr.send(post || '');
if (timeout > 0) {
$browserDefer(function() {
status = -1;
xhr.abort();
}, timeout);
}
}
function completeRequest(callback, status, response, headersString) {
// URL_MATCH is defined in src/service/location.js
var protocol = (url.match(URL_MATCH) || ['', locationProtocol])[
1];
// fix status code for file protocol (it's always 0)
status = (protocol == 'file') ? (response ? 200 : 404) : status;
// normalize IE bug (http://bugs.jquery.com/ticket/1450)
status = status == 1223 ? 204 : status;
callback(status, response, headersString);
$browser.$$completeOutstandingRequest(noop);
}
};
function jsonpReq(url, done) {
// we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.:
// - fetches local scripts via XHR and evals them
// - adds and immediately removes script elements from the document
var script = rawDocument.createElement('script'),
doneWrapper = function() {
rawDocument.body.removeChild(script);
if (done) done();
};
script.type = 'text/javascript';
script.src = url;
if (msie) {
script.onreadystatechange = function() {
if (/loaded|complete/.test(script.readyState)) doneWrapper();
};
} else {
script.onload = script.onerror = doneWrapper;
}
rawDocument.body.appendChild(script);
}
}
/**
* @ngdoc object
* @name ng.$locale
*
* @description
* $locale service provides localization rules for various Angular components. As of right now the
* only public api is:
*
* * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
*/
function $LocaleProvider() {
this.$get = function() {
return {
id: 'en-us',
NUMBER_FORMATS: {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PATTERNS: [{ // Decimal Pattern
minInt: 1,
minFrac: 0,
maxFrac: 3,
posPre: '',
posSuf: '',
negPre: '-',
negSuf: '',
gSize: 3,
lgSize: 3
}, { //Currency Pattern
minInt: 1,
minFrac: 2,
maxFrac: 2,
posPre: '\u00A4',
posSuf: '',
negPre: '(\u00A4',
negSuf: ')',
gSize: 3,
lgSize: 3
}
],
CURRENCY_SYM: '$'
},
DATETIME_FORMATS: {
MONTH: 'January,February,March,April,May,June,July,August,September,October,November,December'
.split(','),
SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'
.split(','),
DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'
.split(','),
SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','),
AMPMS: ['AM', 'PM'],
medium: 'MMM d, y h:mm:ss a',
short: 'M/d/yy h:mm a',
fullDate: 'EEEE, MMMM d, y',
longDate: 'MMMM d, y',
mediumDate: 'MMM d, y',
shortDate: 'M/d/yy',
mediumTime: 'h:mm:ss a',
shortTime: 'h:mm a'
},
pluralCat: function(num) {
if (num === 1) {
return 'one';
}
return 'other';
}
};
};
}
function $TimeoutProvider() {
this.$get = ['$rootScope', '$browser', '$q', '$exceptionHandler',
function($rootScope, $browser, $q, $exceptionHandler) {
var deferreds = {};
/**
* @ngdoc function
* @name ng.$timeout
* @requires $browser
*
* @description
* Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
* block and delegates any exceptions to
* {@link ng.$exceptionHandler $exceptionHandler} service.
*
* The return value of registering a timeout function is a promise which will be resolved when
* the timeout is reached and the timeout function is executed.
*
* To cancel a the timeout request, call `$timeout.cancel(promise)`.
*
* In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
* synchronously flush the queue of deferred functions.
*
* @param {function()} fn A function, who's execution should be delayed.
* @param {number=} [delay=0] Delay in milliseconds.
* @param {boolean=} [invokeApply=true] If set to false skips model dirty checking, otherwise
* will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
* @returns {Promise} Promise that will be resolved when the timeout is reached. The value this
* promise will be resolved with is the return value of the `fn` function.
*/
function timeout(fn, delay, invokeApply) {
var deferred = $q.defer(),
promise = deferred.promise,
skipApply = (isDefined(invokeApply) && !invokeApply),
timeoutId, cleanup;
timeoutId = $browser.defer(function() {
try {
deferred.resolve(fn());
} catch (e) {
deferred.reject(e);
$exceptionHandler(e);
}
if (!skipApply) $rootScope.$apply();
}, delay);
cleanup = function() {
delete deferreds[promise.$$timeoutId];
};
promise.$$timeoutId = timeoutId;
deferreds[timeoutId] = deferred;
promise.then(cleanup, cleanup);
return promise;
}
/**
* @ngdoc function
* @name ng.$timeout#cancel
* @methodOf ng.$timeout
*
* @description
* Cancels a task associated with the `promise`. As a result of this the promise will be
* resolved with a rejection.
*
* @param {Promise=} promise Promise returned by the `$timeout` function.
* @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
* canceled.
*/
timeout.cancel = function(promise) {
if (promise && promise.$$timeoutId in deferreds) {
deferreds[promise.$$timeoutId].reject('canceled');
return $browser.defer.cancel(promise.$$timeoutId);
}
return false;
};
return timeout;
}
];
}
/**
* @ngdoc object
* @name ng.$filterProvider
* @description
*
* Filters are just functions which transform input to an output. However filters need to be Dependency Injected. To
* achieve this a filter definition consists of a factory function which is annotated with dependencies and is
* responsible for creating a filter function.
*
* <pre>
* // Filter registration
* function MyModule($provide, $filterProvider) {
* // create a service to demonstrate injection (not always needed)
* $provide.value('greet', function(name){
* return 'Hello ' + name + '!';
* });
*
* // register a filter factory which uses the
* // greet service to demonstrate DI.
* $filterProvider.register('greet', function(greet){
* // return the filter function which uses the greet service
* // to generate salutation
* return function(text) {
* // filters need to be forgiving so check input validity
* return text && greet(text) || text;
* };
* });
* }
* </pre>
*
* The filter function is registered with the `$injector` under the filter name suffixe with `Filter`.
* <pre>
* it('should be the same instance', inject(
* function($filterProvider) {
* $filterProvider.register('reverse', function(){
* return ...;
* });
* },
* function($filter, reverseFilter) {
* expect($filter('reverse')).toBe(reverseFilter);
* });
* </pre>
*
*
* For more information about how angular filters work, and how to create your own filters, see
* {@link guide/dev_guide.templates.filters Understanding Angular Filters} in the angular Developer
* Guide.
*/
/**
* @ngdoc method
* @name ng.$filterProvider#register
* @methodOf ng.$filterProvider
* @description
* Register filter factory function.
*
* @param {String} name Name of the filter.
* @param {function} fn The filter factory function which is injectable.
*/
/**
* @ngdoc function
* @name ng.$filter
* @function
* @description
* Filters are used for formatting data displayed to the user.
*
* The general syntax in templates is as follows:
*
* {{ expression | [ filter_name ] }}
*
* @param {String} name Name of the filter function to retrieve
* @return {Function} the filter function
*/
$FilterProvider.$inject = ['$provide'];
function $FilterProvider($provide) {
var suffix = 'Filter';
function register(name, factory) {
return $provide.factory(name + suffix, factory);
}
this.register = register;
this.$get = ['$injector',
function($injector) {
return function(name) {
return $injector.get(name + suffix);
}
}
];
////////////////////////////////////////
register('currency', currencyFilter);
register('date', dateFilter);
register('filter', filterFilter);
register('json', jsonFilter);
register('limitTo', limitToFilter);
register('lowercase', lowercaseFilter);
register('number', numberFilter);
register('orderBy', orderByFilter);
register('uppercase', uppercaseFilter);
}
/**
* @ngdoc filter
* @name ng.filter:filter
* @function
*
* @description
* Selects a subset of items from `array` and returns it as a new array.
*
* Note: This function is used to augment the `Array` type in Angular expressions. See
* {@link ng.$filter} for more information about Angular arrays.
*
* @param {Array} array The source array.
* @param {string|Object|function()} expression The predicate to be used for selecting items from
* `array`.
*
* Can be one of:
*
* - `string`: Predicate that results in a substring match using the value of `expression`
* string. All strings or objects with string properties in `array` that contain this string
* will be returned. The predicate can be negated by prefixing the string with `!`.
*
* - `Object`: A pattern object can be used to filter specific properties on objects contained
* by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
* which have property `name` containing "M" and property `phone` containing "1". A special
* property name `$` can be used (as in `{$:"text"}`) to accept a match against any
* property of the object. That's equivalent to the simple substring match with a `string`
* as described above.
*
* - `function`: A predicate function can be used to write arbitrary filters. The function is
* called for each element of `array`. The final result is an array of those elements that
* the predicate returned true for.
*
* @example
<doc:example>
<doc:source>
<div ng-init="friends = [{name:'John', phone:'555-1276'},
{name:'Mary', phone:'800-BIG-MARY'},
{name:'Mike', phone:'555-4321'},
{name:'Adam', phone:'555-5678'},
{name:'Julie', phone:'555-8765'}]"></div>
Search: <input ng-model="searchText">
<table id="searchTextResults">
<tr><th>Name</th><th>Phone</th></tr>
<tr ng-repeat="friend in friends | filter:searchText">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
</tr>
</table>
<hr>
Any: <input ng-model="search.$"> <br>
Name only <input ng-model="search.name"><br>
Phone only <input ng-model="search.phone"å><br>
<table id="searchObjResults">
<tr><th>Name</th><th>Phone</th></tr>
<tr ng-repeat="friend in friends | filter:search">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
</tr>
</table>
</doc:source>
<doc:scenario>
it('should search across all fields when filtering with a string', function() {
input('searchText').enter('m');
expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')).
toEqual(['Mary', 'Mike', 'Adam']);
input('searchText').enter('76');
expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')).
toEqual(['John', 'Julie']);
});
it('should search in specific fields when filtering with a predicate object', function() {
input('search.$').enter('i');
expect(repeater('#searchObjResults tr', 'friend in friends').column('friend.name')).
toEqual(['Mary', 'Mike', 'Julie']);
});
</doc:scenario>
</doc:example>
*/
function filterFilter() {
return function(array, expression) {
if (!isArray(array)) return array;
var predicates = [];
predicates.check = function(value) {
for (var j = 0; j < predicates.length; j++) {
if (!predicates[j](value)) {
return false;
}
}
return true;
};
var search = function(obj, text) {
if (text.charAt(0) === '!') {
return !search(obj, text.substr(1));
}
switch (typeof obj) {
case "boolean":
case "number":
case "string":
return ('' + obj).toLowerCase().indexOf(text) > -1;
case "object":
for (var objKey in obj) {
if (objKey.charAt(0) !== '$' && search(obj[objKey],
text)) {
return true;
}
}
return false;
case "array":
for (var i = 0; i < obj.length; i++) {
if (search(obj[i], text)) {
return true;
}
}
return false;
default:
return false;
}
};
switch (typeof expression) {
case "boolean":
case "number":
case "string":
expression = {
$: expression
};
case "object":
for (var key in expression) {
if (key == '$') {
(function() {
var text = ('' + expression[key]).toLowerCase();
if (!text) return;
predicates.push(function(value) {
return search(value, text);
});
})();
} else {
(function() {
var path = key;
var text = ('' + expression[key]).toLowerCase();
if (!text) return;
predicates.push(function(value) {
return search(getter(value, path), text);
});
})();
}
}
break;
case 'function':
predicates.push(expression);
break;
default:
return array;
}
var filtered = [];
for (var j = 0; j < array.length; j++) {
var value = array[j];
if (predicates.check(value)) {
filtered.push(value);
}
}
return filtered;
}
}
/**
* @ngdoc filter
* @name ng.filter:currency
* @function
*
* @description
* Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
* symbol for current locale is used.
*
* @param {number} amount Input to filter.
* @param {string=} symbol Currency symbol or identifier to be displayed.
* @returns {string} Formatted number.
*
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.amount = 1234.56;
}
</script>
<div ng-controller="Ctrl">
<input type="number" ng-model="amount"> <br>
default currency symbol ($): {{amount | currency}}<br>
custom currency identifier (USD$): {{amount | currency:"USD$"}}
</div>
</doc:source>
<doc:scenario>
it('should init with 1234.56', function() {
expect(binding('amount | currency')).toBe('$1,234.56');
expect(binding('amount | currency:"USD$"')).toBe('USD$1,234.56');
});
it('should update', function() {
input('amount').enter('-1234');
expect(binding('amount | currency')).toBe('($1,234.00)');
expect(binding('amount | currency:"USD$"')).toBe('(USD$1,234.00)');
});
</doc:scenario>
</doc:example>
*/
currencyFilter.$inject = ['$locale'];
function currencyFilter($locale) {
var formats = $locale.NUMBER_FORMATS;
return function(amount, currencySymbol) {
if (isUndefined(currencySymbol)) currencySymbol = formats.CURRENCY_SYM;
return formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP,
formats.DECIMAL_SEP, 2).
replace(/\u00A4/g, currencySymbol);
};
}
/**
* @ngdoc filter
* @name ng.filter:number
* @function
*
* @description
* Formats a number as text.
*
* If the input is not a number an empty string is returned.
*
* @param {number|string} number Number to format.
* @param {(number|string)=} [fractionSize=2] Number of decimal places to round the number to.
* @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.val = 1234.56789;
}
</script>
<div ng-controller="Ctrl">
Enter number: <input ng-model='val'><br>
Default formatting: {{val | number}}<br>
No fractions: {{val | number:0}}<br>
Negative number: {{-val | number:4}}
</div>
</doc:source>
<doc:scenario>
it('should format numbers', function() {
expect(binding('val | number')).toBe('1,234.568');
expect(binding('val | number:0')).toBe('1,235');
expect(binding('-val | number:4')).toBe('-1,234.5679');
});
it('should update', function() {
input('val').enter('3374.333');
expect(binding('val | number')).toBe('3,374.333');
expect(binding('val | number:0')).toBe('3,374');
expect(binding('-val | number:4')).toBe('-3,374.3330');
});
</doc:scenario>
</doc:example>
*/
numberFilter.$inject = ['$locale'];
function numberFilter($locale) {
var formats = $locale.NUMBER_FORMATS;
return function(number, fractionSize) {
return formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP,
formats.DECIMAL_SEP,
fractionSize);
};
}
var DECIMAL_SEP = '.';
function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
if (isNaN(number) || !isFinite(number)) return '';
var isNegative = number < 0;
number = Math.abs(number);
var numStr = number + '',
formatedText = '',
parts = [];
var hasExponent = false;
if (numStr.indexOf('e') !== -1) {
var match = numStr.match(/([\d\.]+)e(-?)(\d+)/);
if (match && match[2] == '-' && match[3] > fractionSize + 1) {
numStr = '0';
} else {
formatedText = numStr;
hasExponent = true;
}
}
if (!hasExponent) {
var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;
// determine fractionSize if it is not specified
if (isUndefined(fractionSize)) {
fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen),
pattern.maxFrac);
}
var pow = Math.pow(10, fractionSize);
number = Math.round(number * pow) / pow;
var fraction = ('' + number).split(DECIMAL_SEP);
var whole = fraction[0];
fraction = fraction[1] || '';
var pos = 0,
lgroup = pattern.lgSize,
group = pattern.gSize;
if (whole.length >= (lgroup + group)) {
pos = whole.length - lgroup;
for (var i = 0; i < pos; i++) {
if ((pos - i) % group === 0 && i !== 0) {
formatedText += groupSep;
}
formatedText += whole.charAt(i);
}
}
for (i = pos; i < whole.length; i++) {
if ((whole.length - i) % lgroup === 0 && i !== 0) {
formatedText += groupSep;
}
formatedText += whole.charAt(i);
}
// format fraction part.
while (fraction.length < fractionSize) {
fraction += '0';
}
if (fractionSize && fractionSize !== "0") formatedText +=
decimalSep + fraction.substr(0, fractionSize);
}
parts.push(isNegative ? pattern.negPre : pattern.posPre);
parts.push(formatedText);
parts.push(isNegative ? pattern.negSuf : pattern.posSuf);
return parts.join('');
}
function padNumber(num, digits, trim) {
var neg = '';
if (num < 0) {
neg = '-';
num = -num;
}
num = '' + num;
while (num.length < digits) num = '0' + num;
if (trim)
num = num.substr(num.length - digits);
return neg + num;
}
function dateGetter(name, size, offset, trim) {
return function(date) {
var value = date['get' + name]();
if (offset > 0 || value > -offset)
value += offset;
if (value === 0 && offset == -12) value = 12;
return padNumber(value, size, trim);
};
}
function dateStrGetter(name, shortForm) {
return function(date, formats) {
var value = date['get' + name]();
var get = uppercase(shortForm ? ('SHORT' + name) : name);
return formats[get][value];
};
}
function timeZoneGetter(date) {
var zone = -1 * date.getTimezoneOffset();
var paddedZone = (zone >= 0) ? "+" : "";
paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
padNumber(Math.abs(zone % 60), 2);
return paddedZone;
}
function ampmGetter(date, formats) {
return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
}
var DATE_FORMATS = {
yyyy: dateGetter('FullYear', 4),
yy: dateGetter('FullYear', 2, 0, true),
y: dateGetter('FullYear', 1),
MMMM: dateStrGetter('Month'),
MMM: dateStrGetter('Month', true),
MM: dateGetter('Month', 2, 1),
M: dateGetter('Month', 1, 1),
dd: dateGetter('Date', 2),
d: dateGetter('Date', 1),
HH: dateGetter('Hours', 2),
H: dateGetter('Hours', 1),
hh: dateGetter('Hours', 2, -12),
h: dateGetter('Hours', 1, -12),
mm: dateGetter('Minutes', 2),
m: dateGetter('Minutes', 1),
ss: dateGetter('Seconds', 2),
s: dateGetter('Seconds', 1),
EEEE: dateStrGetter('Day'),
EEE: dateStrGetter('Day', true),
a: ampmGetter,
Z: timeZoneGetter
};
var DATE_FORMATS_SPLIT =
/((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/,
NUMBER_STRING = /^\d+$/;
/**
* @ngdoc filter
* @name ng.filter:date
* @function
*
* @description
* Formats `date` to a string based on the requested `format`.
*
* `format` string can be composed of the following elements:
*
* * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
* * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
* * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
* * `'MMMM'`: Month in year (January-December)
* * `'MMM'`: Month in year (Jan-Dec)
* * `'MM'`: Month in year, padded (01-12)
* * `'M'`: Month in year (1-12)
* * `'dd'`: Day in month, padded (01-31)
* * `'d'`: Day in month (1-31)
* * `'EEEE'`: Day in Week,(Sunday-Saturday)
* * `'EEE'`: Day in Week, (Sun-Sat)
* * `'HH'`: Hour in day, padded (00-23)
* * `'H'`: Hour in day (0-23)
* * `'hh'`: Hour in am/pm, padded (01-12)
* * `'h'`: Hour in am/pm, (1-12)
* * `'mm'`: Minute in hour, padded (00-59)
* * `'m'`: Minute in hour (0-59)
* * `'ss'`: Second in minute, padded (00-59)
* * `'s'`: Second in minute (0-59)
* * `'a'`: am/pm marker
* * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
*
* `format` string can also be one of the following predefined
* {@link guide/i18n localizable formats}:
*
* * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
* (e.g. Sep 3, 2010 12:05:08 pm)
* * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 pm)
* * `'fullDate'`: equivalent to `'EEEE, MMMM d,y'` for en_US locale
* (e.g. Friday, September 3, 2010)
* * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010
* * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
* * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
* * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 pm)
* * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 pm)
*
* `format` string can contain literal values. These need to be quoted with single quotes (e.g.
* `"h 'in the morning'"`). In order to output single quote, use two single quotes in a sequence
* (e.g. `"h o''clock"`).
*
* @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
* number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.SSSZ and it's
* shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
* specified in the string input, the time is considered to be in the local timezone.
* @param {string=} format Formatting rules (see Description). If not specified,
* `mediumDate` is used.
* @returns {string} Formatted string or the input if input is not recognized as date/millis.
*
* @example
<doc:example>
<doc:source>
<span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
{{1288323623006 | date:'medium'}}<br>
<span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}<br>
<span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}<br>
</doc:source>
<doc:scenario>
it('should format date', function() {
expect(binding("1288323623006 | date:'medium'")).
toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
expect(binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).
toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
expect(binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).
toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
});
</doc:scenario>
</doc:example>
*/
dateFilter.$inject = ['$locale'];
function dateFilter($locale) {
var R_ISO8601_STR =
/^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
function jsonStringToDate(string) {
var match;
if (match = string.match(R_ISO8601_STR)) {
var date = new Date(0),
tzHour = 0,
tzMin = 0;
if (match[9]) {
tzHour = int(match[9] + match[10]);
tzMin = int(match[9] + match[11]);
}
date.setUTCFullYear(int(match[1]), int(match[2]) - 1, int(match[
3]));
date.setUTCHours(int(match[4] || 0) - tzHour, int(match[5] || 0) -
tzMin, int(match[6] || 0), int(match[7] || 0));
return date;
}
return string;
}
return function(date, format) {
var text = '',
parts = [],
fn, match;
format = format || 'mediumDate';
format = $locale.DATETIME_FORMATS[format] || format;
if (isString(date)) {
if (NUMBER_STRING.test(date)) {
date = int(date);
} else {
date = jsonStringToDate(date);
}
}
if (isNumber(date)) {
date = new Date(date);
}
if (!isDate(date)) {
return date;
}
while (format) {
match = DATE_FORMATS_SPLIT.exec(format);
if (match) {
parts = concat(parts, match, 1);
format = parts.pop();
} else {
parts.push(format);
format = null;
}
}
forEach(parts, function(value) {
fn = DATE_FORMATS[value];
text += fn ? fn(date, $locale.DATETIME_FORMATS) : value.replace(
/(^'|'$)/g, '').replace(/''/g, "'");
});
return text;
};
}
/**
* @ngdoc filter
* @name ng.filter:json
* @function
*
* @description
* Allows you to convert a JavaScript object into JSON string.
*
* This filter is mostly useful for debugging. When using the double curly {{value}} notation
* the binding is automatically converted to JSON.
*
* @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
* @returns {string} JSON string.
*
*
* @example:
<doc:example>
<doc:source>
<pre>{{ {'name':'value'} | json }}</pre>
</doc:source>
<doc:scenario>
it('should jsonify filtered objects', function() {
expect(binding("{'name':'value'}")).toMatch(/\{\n "name": ?"value"\n}/);
});
</doc:scenario>
</doc:example>
*
*/
function jsonFilter() {
return function(object) {
return toJson(object, true);
};
}
/**
* @ngdoc filter
* @name ng.filter:lowercase
* @function
* @description
* Converts string to lowercase.
* @see angular.lowercase
*/
var lowercaseFilter = valueFn(lowercase);
/**
* @ngdoc filter
* @name ng.filter:uppercase
* @function
* @description
* Converts string to uppercase.
* @see angular.uppercase
*/
var uppercaseFilter = valueFn(uppercase);
/**
* @ngdoc function
* @name ng.filter:limitTo
* @function
*
* @description
* Creates a new array containing only a specified number of elements in an array. The elements
* are taken from either the beginning or the end of the source array, as specified by the
* value and sign (positive or negative) of `limit`.
*
* Note: This function is used to augment the `Array` type in Angular expressions. See
* {@link ng.$filter} for more information about Angular arrays.
*
* @param {Array} array Source array to be limited.
* @param {string|Number} limit The length of the returned array. If the `limit` number is
* positive, `limit` number of items from the beginning of the source array are copied.
* If the number is negative, `limit` number of items from the end of the source array are
* copied. The `limit` will be trimmed if it exceeds `array.length`
* @returns {Array} A new sub-array of length `limit` or less if input array had less than `limit`
* elements.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.numbers = [1,2,3,4,5,6,7,8,9];
$scope.limit = 3;
}
</script>
<div ng-controller="Ctrl">
Limit {{numbers}} to: <input type="integer" ng-model="limit">
<p>Output: {{ numbers | limitTo:limit }}</p>
</div>
</doc:source>
<doc:scenario>
it('should limit the numer array to first three items', function() {
expect(element('.doc-example-live input[ng-model=limit]').val()).toBe('3');
expect(binding('numbers | limitTo:limit')).toEqual('[1,2,3]');
});
it('should update the output when -3 is entered', function() {
input('limit').enter(-3);
expect(binding('numbers | limitTo:limit')).toEqual('[7,8,9]');
});
it('should not exceed the maximum size of input array', function() {
input('limit').enter(100);
expect(binding('numbers | limitTo:limit')).toEqual('[1,2,3,4,5,6,7,8,9]');
});
</doc:scenario>
</doc:example>
*/
function limitToFilter() {
return function(array, limit) {
if (!(array instanceof Array)) return array;
limit = int(limit);
var out = [],
i, n;
// check that array is iterable
if (!array || !(array instanceof Array))
return out;
// if abs(limit) exceeds maximum length, trim it
if (limit > array.length)
limit = array.length;
else if (limit < -array.length)
limit = -array.length;
if (limit > 0) {
i = 0;
n = limit;
} else {
i = array.length + limit;
n = array.length;
}
for (; i < n; i++) {
out.push(array[i]);
}
return out;
}
}
/**
* @ngdoc function
* @name ng.filter:orderBy
* @function
*
* @description
* Orders a specified `array` by the `expression` predicate.
*
* Note: this function is used to augment the `Array` type in Angular expressions. See
* {@link ng.$filter} for more informaton about Angular arrays.
*
* @param {Array} array The array to sort.
* @param {function(*)|string|Array.<(function(*)|string)>} expression A predicate to be
* used by the comparator to determine the order of elements.
*
* Can be one of:
*
* - `function`: Getter function. The result of this function will be sorted using the
* `<`, `=`, `>` operator.
* - `string`: An Angular expression which evaluates to an object to order by, such as 'name'
* to sort by a property called 'name'. Optionally prefixed with `+` or `-` to control
* ascending or descending sort order (for example, +name or -name).
* - `Array`: An array of function or string predicates. The first predicate in the array
* is used for sorting, but when two items are equivalent, the next predicate is used.
*
* @param {boolean=} reverse Reverse the order the array.
* @returns {Array} Sorted copy of the source array.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.friends =
[{name:'John', phone:'555-1212', age:10},
{name:'Mary', phone:'555-9876', age:19},
{name:'Mike', phone:'555-4321', age:21},
{name:'Adam', phone:'555-5678', age:35},
{name:'Julie', phone:'555-8765', age:29}]
$scope.predicate = '-age';
}
</script>
<div ng-controller="Ctrl">
<pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
<hr/>
[ <a href="" ng-click="predicate=''">unsorted</a> ]
<table class="friend">
<tr>
<th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a>
(<a href ng-click="predicate = '-name'; reverse=false">^</a>)</th>
<th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th>
<th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th>
</tr>
<tr ng-repeat="friend in friends | orderBy:predicate:reverse">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<td>{{friend.age}}</td>
</tr>
</table>
</div>
</doc:source>
<doc:scenario>
it('should be reverse ordered by aged', function() {
expect(binding('predicate')).toBe('-age');
expect(repeater('table.friend', 'friend in friends').column('friend.age')).
toEqual(['35', '29', '21', '19', '10']);
expect(repeater('table.friend', 'friend in friends').column('friend.name')).
toEqual(['Adam', 'Julie', 'Mike', 'Mary', 'John']);
});
it('should reorder the table when user selects different predicate', function() {
element('.doc-example-live a:contains("Name")').click();
expect(repeater('table.friend', 'friend in friends').column('friend.name')).
toEqual(['Adam', 'John', 'Julie', 'Mary', 'Mike']);
expect(repeater('table.friend', 'friend in friends').column('friend.age')).
toEqual(['35', '10', '29', '19', '21']);
element('.doc-example-live a:contains("Phone")').click();
expect(repeater('table.friend', 'friend in friends').column('friend.phone')).
toEqual(['555-9876', '555-8765', '555-5678', '555-4321', '555-1212']);
expect(repeater('table.friend', 'friend in friends').column('friend.name')).
toEqual(['Mary', 'Julie', 'Adam', 'Mike', 'John']);
});
</doc:scenario>
</doc:example>
*/
orderByFilter.$inject = ['$parse'];
function orderByFilter($parse) {
return function(array, sortPredicate, reverseOrder) {
if (!isArray(array)) return array;
if (!sortPredicate) return array;
sortPredicate = isArray(sortPredicate) ? sortPredicate : [
sortPredicate
];
sortPredicate = map(sortPredicate, function(predicate) {
var descending = false,
get = predicate || identity;
if (isString(predicate)) {
if ((predicate.charAt(0) == '+' || predicate.charAt(0) ==
'-')) {
descending = predicate.charAt(0) == '-';
predicate = predicate.substring(1);
}
get = $parse(predicate);
}
return reverseComparator(function(a, b) {
return compare(get(a), get(b));
}, descending);
});
var arrayCopy = [];
for (var i = 0; i < array.length; i++) {
arrayCopy.push(array[i]);
}
return arrayCopy.sort(reverseComparator(comparator, reverseOrder));
function comparator(o1, o2) {
for (var i = 0; i < sortPredicate.length; i++) {
var comp = sortPredicate[i](o1, o2);
if (comp !== 0) return comp;
}
return 0;
}
function reverseComparator(comp, descending) {
return toBoolean(descending) ? function(a, b) {
return comp(b, a);
} : comp;
}
function compare(v1, v2) {
var t1 = typeof v1;
var t2 = typeof v2;
if (t1 == t2) {
if (t1 == "string") v1 = v1.toLowerCase();
if (t1 == "string") v2 = v2.toLowerCase();
if (v1 === v2) return 0;
return v1 < v2 ? -1 : 1;
} else {
return t1 < t2 ? -1 : 1;
}
}
}
}
function ngDirective(directive) {
if (isFunction(directive)) {
directive = {
link: directive
}
}
directive.restrict = directive.restrict || 'AC';
return valueFn(directive);
}
/**
* @ngdoc directive
* @name ng.directive:a
* @restrict E
*
* @description
* Modifies the default behavior of html A tag, so that the default action is prevented when href
* attribute is empty.
*
* The reasoning for this change is to allow easy creation of action links with `ngClick` directive
* without changing the location or causing page reloads, e.g.:
* `<a href="" ng-click="model.$save()">Save</a>`
*/
var htmlAnchorDirective = valueFn({
restrict: 'E',
compile: function(element, attr) {
if (msie <= 8) {
// turn <a href ng-click="..">link</a> into a stylable link in IE
// but only if it doesn't have name attribute, in which case it's an anchor
if (!attr.href && !attr.name) {
attr.$set('href', '');
}
// add a comment node to anchors to workaround IE bug that causes element content to be reset
// to new attribute content if attribute is updated with value containing @ and element also
// contains value with @
// see issue #1949
element.append(document.createComment('IE fix'));
}
return function(scope, element) {
element.bind('click', function(event) {
// if we have no href url, then don't navigate anywhere.
if (!element.attr('href')) {
event.preventDefault();
}
});
}
}
});
/**
* @ngdoc directive
* @name ng.directive:ngHref
* @restrict A
*
* @description
* Using Angular markup like {{hash}} in an href attribute makes
* the page open to a wrong URL, if the user clicks that link before
* angular has a chance to replace the {{hash}} with actual URL, the
* link will be broken and will most likely return a 404 error.
* The `ngHref` directive solves this problem.
*
* The buggy way to write it:
* <pre>
* <a href="http://www.gravatar.com/avatar/{{hash}}"/>
* </pre>
*
* The correct way to write it:
* <pre>
* <a ng-href="http://www.gravatar.com/avatar/{{hash}}"/>
* </pre>
*
* @element A
* @param {template} ngHref any string which can contain `{{}}` markup.
*
* @example
* This example uses `link` variable inside `href` attribute:
<doc:example>
<doc:source>
<input ng-model="value" /><br />
<a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
<a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
<a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
<a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
<a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
<a id="link-6" ng-href="{{value}}">link</a> (link, change location)
</doc:source>
<doc:scenario>
it('should execute ng-click but not reload when href without value', function() {
element('#link-1').click();
expect(input('value').val()).toEqual('1');
expect(element('#link-1').attr('href')).toBe("");
});
it('should execute ng-click but not reload when href empty string', function() {
element('#link-2').click();
expect(input('value').val()).toEqual('2');
expect(element('#link-2').attr('href')).toBe("");
});
it('should execute ng-click and change url when ng-href specified', function() {
expect(element('#link-3').attr('href')).toBe("/123");
element('#link-3').click();
expect(browser().window().path()).toEqual('/123');
});
it('should execute ng-click but not reload when href empty string and name specified', function() {
element('#link-4').click();
expect(input('value').val()).toEqual('4');
expect(element('#link-4').attr('href')).toBe('');
});
it('should execute ng-click but not reload when no href but name specified', function() {
element('#link-5').click();
expect(input('value').val()).toEqual('5');
expect(element('#link-5').attr('href')).toBe(undefined);
});
it('should only change url when only ng-href', function() {
input('value').enter('6');
expect(element('#link-6').attr('href')).toBe('6');
element('#link-6').click();
expect(browser().location().url()).toEqual('/6');
});
</doc:scenario>
</doc:example>
*/
/**
* @ngdoc directive
* @name ng.directive:ngSrc
* @restrict A
*
* @description
* Using Angular markup like `{{hash}}` in a `src` attribute doesn't
* work right: The browser will fetch from the URL with the literal
* text `{{hash}}` until Angular replaces the expression inside
* `{{hash}}`. The `ngSrc` directive solves this problem.
*
* The buggy way to write it:
* <pre>
* <img src="http://www.gravatar.com/avatar/{{hash}}"/>
* </pre>
*
* The correct way to write it:
* <pre>
* <img ng-src="http://www.gravatar.com/avatar/{{hash}}"/>
* </pre>
*
* @element IMG
* @param {template} ngSrc any string which can contain `{{}}` markup.
*/
/**
* @ngdoc directive
* @name ng.directive:ngDisabled
* @restrict A
*
* @description
*
* The following markup will make the button enabled on Chrome/Firefox but not on IE8 and older IEs:
* <pre>
* <div ng-init="scope = { isDisabled: false }">
* <button disabled="{{scope.isDisabled}}">Disabled</button>
* </div>
* </pre>
*
* The HTML specs do not require browsers to preserve the special attributes such as disabled.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding expression.
* To solve this problem, we introduce the `ngDisabled` directive.
*
* @example
<doc:example>
<doc:source>
Click me to toggle: <input type="checkbox" ng-model="checked"><br/>
<button ng-model="button" ng-disabled="checked">Button</button>
</doc:source>
<doc:scenario>
it('should toggle button', function() {
expect(element('.doc-example-live :button').prop('disabled')).toBeFalsy();
input('checked').check();
expect(element('.doc-example-live :button').prop('disabled')).toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element INPUT
* @param {expression} ngDisabled Angular expression that will be evaluated.
*/
/**
* @ngdoc directive
* @name ng.directive:ngChecked
* @restrict A
*
* @description
* The HTML specs do not require browsers to preserve the special attributes such as checked.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding expression.
* To solve this problem, we introduce the `ngChecked` directive.
* @example
<doc:example>
<doc:source>
Check me to check both: <input type="checkbox" ng-model="master"><br/>
<input id="checkSlave" type="checkbox" ng-checked="master">
</doc:source>
<doc:scenario>
it('should check both checkBoxes', function() {
expect(element('.doc-example-live #checkSlave').prop('checked')).toBeFalsy();
input('master').check();
expect(element('.doc-example-live #checkSlave').prop('checked')).toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element INPUT
* @param {expression} ngChecked Angular expression that will be evaluated.
*/
/**
* @ngdoc directive
* @name ng.directive:ngMultiple
* @restrict A
*
* @description
* The HTML specs do not require browsers to preserve the special attributes such as multiple.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding expression.
* To solve this problem, we introduce the `ngMultiple` directive.
*
* @example
<doc:example>
<doc:source>
Check me check multiple: <input type="checkbox" ng-model="checked"><br/>
<select id="select" ng-multiple="checked">
<option>Misko</option>
<option>Igor</option>
<option>Vojta</option>
<option>Di</option>
</select>
</doc:source>
<doc:scenario>
it('should toggle multiple', function() {
expect(element('.doc-example-live #select').prop('multiple')).toBeFalsy();
input('checked').check();
expect(element('.doc-example-live #select').prop('multiple')).toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element SELECT
* @param {expression} ngMultiple Angular expression that will be evaluated.
*/
/**
* @ngdoc directive
* @name ng.directive:ngReadonly
* @restrict A
*
* @description
* The HTML specs do not require browsers to preserve the special attributes such as readonly.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding expression.
* To solve this problem, we introduce the `ngReadonly` directive.
* @example
<doc:example>
<doc:source>
Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/>
<input type="text" ng-readonly="checked" value="I'm Angular"/>
</doc:source>
<doc:scenario>
it('should toggle readonly attr', function() {
expect(element('.doc-example-live :text').prop('readonly')).toBeFalsy();
input('checked').check();
expect(element('.doc-example-live :text').prop('readonly')).toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element INPUT
* @param {string} expression Angular expression that will be evaluated.
*/
/**
* @ngdoc directive
* @name ng.directive:ngSelected
* @restrict A
*
* @description
* The HTML specs do not require browsers to preserve the special attributes such as selected.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding expression.
* To solve this problem, we introduced the `ngSelected` directive.
* @example
<doc:example>
<doc:source>
Check me to select: <input type="checkbox" ng-model="selected"><br/>
<select>
<option>Hello!</option>
<option id="greet" ng-selected="selected">Greetings!</option>
</select>
</doc:source>
<doc:scenario>
it('should select Greetings!', function() {
expect(element('.doc-example-live #greet').prop('selected')).toBeFalsy();
input('selected').check();
expect(element('.doc-example-live #greet').prop('selected')).toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element OPTION
* @param {string} expression Angular expression that will be evaluated.
*/
var ngAttributeAliasDirectives = {};
// boolean attrs are evaluated
forEach(BOOLEAN_ATTR, function(propName, attrName) {
var normalized = directiveNormalize('ng-' + attrName);
ngAttributeAliasDirectives[normalized] = function() {
return {
priority: 100,
compile: function() {
return function(scope, element, attr) {
scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(
value) {
attr.$set(attrName, !! value);
});
};
}
};
};
});
// ng-src, ng-href are interpolated
forEach(['src', 'href'], function(attrName) {
var normalized = directiveNormalize('ng-' + attrName);
ngAttributeAliasDirectives[normalized] = function() {
return {
priority: 99, // it needs to run after the attributes are interpolated
link: function(scope, element, attr) {
attr.$observe(normalized, function(value) {
if (!value)
return;
attr.$set(attrName, value);
// on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
// then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
// to set the property as well to achieve the desired effect.
// we use attr[attrName] value since $set can sanitize the url.
if (msie) element.prop(attrName, attr[attrName]);
});
}
};
};
});
var nullFormCtrl = {
$addControl: noop,
$removeControl: noop,
$setValidity: noop,
$setDirty: noop
};
/**
* @ngdoc object
* @name ng.directive:form.FormController
*
* @property {boolean} $pristine True if user has not interacted with the form yet.
* @property {boolean} $dirty True if user has already interacted with the form.
* @property {boolean} $valid True if all of the containing forms and controls are valid.
* @property {boolean} $invalid True if at least one containing control or form is invalid.
*
* @property {Object} $error Is an object hash, containing references to all invalid controls or
* forms, where:
*
* - keys are validation tokens (error names) — such as `required`, `url` or `email`),
* - values are arrays of controls or forms that are invalid with given error.
*
* @description
* `FormController` keeps track of all its controls and nested forms as well as state of them,
* such as being valid/invalid or dirty/pristine.
*
* Each {@link ng.directive:form form} directive creates an instance
* of `FormController`.
*
*/
//asks for $scope to fool the BC controller module
FormController.$inject = ['$element', '$attrs', '$scope'];
function FormController(element, attrs) {
var form = this,
parentForm = element.parent().controller('form') || nullFormCtrl,
invalidCount = 0, // used to easily determine if we are valid
errors = form.$error = {};
// init state
form.$name = attrs.name;
form.$dirty = false;
form.$pristine = true;
form.$valid = true;
form.$invalid = false;
parentForm.$addControl(form);
// Setup initial state of the control
element.addClass(PRISTINE_CLASS);
toggleValidCss(true);
// convenience method for easy toggling of classes
function toggleValidCss(isValid, validationErrorKey) {
validationErrorKey = validationErrorKey ? '-' + snake_case(
validationErrorKey, '-') : '';
element.
removeClass((isValid ? INVALID_CLASS : VALID_CLASS) +
validationErrorKey).
addClass((isValid ? VALID_CLASS : INVALID_CLASS) +
validationErrorKey);
}
form.$addControl = function(control) {
if (control.$name && !form.hasOwnProperty(control.$name)) {
form[control.$name] = control;
}
};
form.$removeControl = function(control) {
if (control.$name && form[control.$name] === control) {
delete form[control.$name];
}
forEach(errors, function(queue, validationToken) {
form.$setValidity(validationToken, true, control);
});
};
form.$setValidity = function(validationToken, isValid, control) {
var queue = errors[validationToken];
if (isValid) {
if (queue) {
arrayRemove(queue, control);
if (!queue.length) {
invalidCount--;
if (!invalidCount) {
toggleValidCss(isValid);
form.$valid = true;
form.$invalid = false;
}
errors[validationToken] = false;
toggleValidCss(true, validationToken);
parentForm.$setValidity(validationToken, true, form);
}
}
} else {
if (!invalidCount) {
toggleValidCss(isValid);
}
if (queue) {
if (includes(queue, control)) return;
} else {
errors[validationToken] = queue = [];
invalidCount++;
toggleValidCss(false, validationToken);
parentForm.$setValidity(validationToken, false, form);
}
queue.push(control);
form.$valid = false;
form.$invalid = true;
}
};
form.$setDirty = function() {
element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS);
form.$dirty = true;
form.$pristine = false;
parentForm.$setDirty();
};
}
/**
* @ngdoc directive
* @name ng.directive:ngForm
* @restrict EAC
*
* @description
* Nestable alias of {@link ng.directive:form `form`} directive. HTML
* does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
* sub-group of controls needs to be determined.
*
* @param {string=} name|ngForm Name of the form. If specified, the form controller will be published into
* related scope, under this name.
*
*/
/**
* @ngdoc directive
* @name ng.directive:form
* @restrict E
*
* @description
* Directive that instantiates
* {@link ng.directive:form.FormController FormController}.
*
* If `name` attribute is specified, the form controller is published onto the current scope under
* this name.
*
* # Alias: {@link ng.directive:ngForm `ngForm`}
*
* In angular forms can be nested. This means that the outer form is valid when all of the child
* forms are valid as well. However browsers do not allow nesting of `<form>` elements, for this
* reason angular provides {@link ng.directive:ngForm `ngForm`} alias
* which behaves identical to `<form>` but allows form nesting.
*
*
* # CSS classes
* - `ng-valid` Is set if the form is valid.
* - `ng-invalid` Is set if the form is invalid.
* - `ng-pristine` Is set if the form is pristine.
* - `ng-dirty` Is set if the form is dirty.
*
*
* # Submitting a form and preventing default action
*
* Since the role of forms in client-side Angular applications is different than in classical
* roundtrip apps, it is desirable for the browser not to translate the form submission into a full
* page reload that sends the data to the server. Instead some javascript logic should be triggered
* to handle the form submission in application specific way.
*
* For this reason, Angular prevents the default action (form submission to the server) unless the
* `<form>` element has an `action` attribute specified.
*
* You can use one of the following two ways to specify what javascript method should be called when
* a form is submitted:
*
* - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
* - {@link ng.directive:ngClick ngClick} directive on the first
* button or input field of type submit (input[type=submit])
*
* To prevent double execution of the handler, use only one of ngSubmit or ngClick directives. This
* is because of the following form submission rules coming from the html spec:
*
* - If a form has only one input field then hitting enter in this field triggers form submit
* (`ngSubmit`)
* - if a form has has 2+ input fields and no buttons or input[type=submit] then hitting enter
* doesn't trigger submit
* - if a form has one or more input fields and one or more buttons or input[type=submit] then
* hitting enter in any of the input fields will trigger the click handler on the *first* button or
* input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
*
* @param {string=} name Name of the form. If specified, the form controller will be published into
* related scope, under this name.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.userType = 'guest';
}
</script>
<form name="myForm" ng-controller="Ctrl">
userType: <input name="input" ng-model="userType" required>
<span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
<tt>userType = {{userType}}</tt><br>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('userType')).toEqual('guest');
expect(binding('myForm.input.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('userType').enter('');
expect(binding('userType')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
var formDirectiveFactory = function(isNgForm) {
return ['$timeout', function($timeout) {
var formDirective = {
name: 'form',
restrict: 'E',
controller: FormController,
compile: function() {
return {
pre: function(scope, formElement, attr, controller) {
if (!attr.action) {
// we can't use jq events because if a form is destroyed during submission the default
// action is not prevented. see #1238
//
// IE 9 is not affected because it doesn't fire a submit event and try to do a full
// page reload if the form was destroyed by submission of the form via a click handler
// on a button in the form. Looks like an IE9 specific bug.
var preventDefaultListener = function(event) {
event.preventDefault ? event.preventDefault() :
event.returnValue = false; // IE
};
addEventListenerFn(formElement[0], 'submit',
preventDefaultListener);
// unregister the preventDefault listener so that we don't not leak memory but in a
// way that will achieve the prevention of the default action.
formElement.bind('$destroy', function() {
$timeout(function() {
removeEventListenerFn(formElement[0],
'submit', preventDefaultListener);
}, 0, false);
});
}
var parentFormCtrl = formElement.parent().controller(
'form'),
alias = attr.name || attr.ngForm;
if (alias) {
scope[alias] = controller;
}
if (parentFormCtrl) {
formElement.bind('$destroy', function() {
parentFormCtrl.$removeControl(controller);
if (alias) {
scope[alias] = undefined;
}
extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
});
}
}
};
}
};
return isNgForm ? extend(copy(formDirective), {
restrict: 'EAC'
}) : formDirective;
}];
};
var formDirective = formDirectiveFactory();
var ngFormDirective = formDirectiveFactory(true);
var URL_REGEXP =
/^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/;
var EMAIL_REGEXP = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/;
var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/;
var inputType = {
/**
* @ngdoc inputType
* @name ng.directive:input.text
*
* @description
* Standard HTML text input with angular data binding.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Adds `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.text = 'guest';
$scope.word = /^\w*$/;
}
</script>
<form name="myForm" ng-controller="Ctrl">
Single word: <input type="text" name="input" ng-model="text"
ng-pattern="word" required>
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.pattern">
Single word only!</span>
<tt>text = {{text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('text')).toEqual('guest');
expect(binding('myForm.input.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('text').enter('');
expect(binding('text')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
it('should be invalid if multi word', function() {
input('text').enter('hello world');
expect(binding('myForm.input.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
'text': textInputType,
/**
* @ngdoc inputType
* @name ng.directive:input.number
*
* @description
* Text input with number validation and transformation. Sets the `number` validation
* error if not a valid number.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} min Sets the `min` validation error key if the value entered is less then `min`.
* @param {string=} max Sets the `max` validation error key if the value entered is greater then `min`.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.value = 12;
}
</script>
<form name="myForm" ng-controller="Ctrl">
Number: <input type="number" name="input" ng-model="value"
min="0" max="99" required>
<span class="error" ng-show="myForm.list.$error.required">
Required!</span>
<span class="error" ng-show="myForm.list.$error.number">
Not valid number!</span>
<tt>value = {{value}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('value')).toEqual('12');
expect(binding('myForm.input.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('value').enter('');
expect(binding('value')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
it('should be invalid if over max', function() {
input('value').enter('123');
expect(binding('value')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
'number': numberInputType,
/**
* @ngdoc inputType
* @name ng.directive:input.url
*
* @description
* Text input with URL validation. Sets the `url` validation error key if the content is not a
* valid URL.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.text = 'http://google.com';
}
</script>
<form name="myForm" ng-controller="Ctrl">
URL: <input type="url" name="input" ng-model="text" required>
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.url">
Not valid url!</span>
<tt>text = {{text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('text')).toEqual('http://google.com');
expect(binding('myForm.input.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('text').enter('');
expect(binding('text')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
it('should be invalid if not url', function() {
input('text').enter('xxx');
expect(binding('myForm.input.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
'url': urlInputType,
/**
* @ngdoc inputType
* @name ng.directive:input.email
*
* @description
* Text input with email validation. Sets the `email` validation error key if not a valid email
* address.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.text = 'me@example.com';
}
</script>
<form name="myForm" ng-controller="Ctrl">
Email: <input type="email" name="input" ng-model="text" required>
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.email">
Not valid email!</span>
<tt>text = {{text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('text')).toEqual('me@example.com');
expect(binding('myForm.input.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('text').enter('');
expect(binding('text')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
it('should be invalid if not email', function() {
input('text').enter('xxx');
expect(binding('myForm.input.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
'email': emailInputType,
/**
* @ngdoc inputType
* @name ng.directive:input.radio
*
* @description
* HTML radio button.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string} value The value to which the expression should be set when selected.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.color = 'blue';
}
</script>
<form name="myForm" ng-controller="Ctrl">
<input type="radio" ng-model="color" value="red"> Red <br/>
<input type="radio" ng-model="color" value="green"> Green <br/>
<input type="radio" ng-model="color" value="blue"> Blue <br/>
<tt>color = {{color}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should change state', function() {
expect(binding('color')).toEqual('blue');
input('color').select('red');
expect(binding('color')).toEqual('red');
});
</doc:scenario>
</doc:example>
*/
'radio': radioInputType,
/**
* @ngdoc inputType
* @name ng.directive:input.checkbox
*
* @description
* HTML checkbox.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} ngTrueValue The value to which the expression should be set when selected.
* @param {string=} ngFalseValue The value to which the expression should be set when not selected.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.value1 = true;
$scope.value2 = 'YES'
}
</script>
<form name="myForm" ng-controller="Ctrl">
Value1: <input type="checkbox" ng-model="value1"> <br/>
Value2: <input type="checkbox" ng-model="value2"
ng-true-value="YES" ng-false-value="NO"> <br/>
<tt>value1 = {{value1}}</tt><br/>
<tt>value2 = {{value2}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should change state', function() {
expect(binding('value1')).toEqual('true');
expect(binding('value2')).toEqual('YES');
input('value1').check();
input('value2').check();
expect(binding('value1')).toEqual('false');
expect(binding('value2')).toEqual('NO');
});
</doc:scenario>
</doc:example>
*/
'checkbox': checkboxInputType,
'hidden': noop,
'button': noop,
'submit': noop,
'reset': noop
};
function isEmpty(value) {
return isUndefined(value) || value === '' || value === null || value !==
value;
}
function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
var listener = function() {
var value = trim(element.val());
if (ctrl.$viewValue !== value) {
scope.$apply(function() {
ctrl.$setViewValue(value);
});
}
};
// if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
// input event on backspace, delete or cut
if ($sniffer.hasEvent('input')) {
element.bind('input', listener);
} else {
var timeout;
element.bind('keydown', function(event) {
var key = event.keyCode;
// ignore
// command modifiers arrows
if (key === 91 || (15 < key && key < 19) || (37 <= key && key <=
40)) return;
if (!timeout) {
timeout = $browser.defer(function() {
listener();
timeout = null;
});
}
});
// if user paste into input using mouse, we need "change" event to catch it
element.bind('change', listener);
}
ctrl.$render = function() {
element.val(isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue);
};
// pattern validator
var pattern = attr.ngPattern,
patternValidator;
var validate = function(regexp, value) {
if (isEmpty(value) || regexp.test(value)) {
ctrl.$setValidity('pattern', true);
return value;
} else {
ctrl.$setValidity('pattern', false);
return undefined;
}
};
if (pattern) {
if (pattern.match(/^\/(.*)\/$/)) {
pattern = new RegExp(pattern.substr(1, pattern.length - 2));
patternValidator = function(value) {
return validate(pattern, value)
};
} else {
patternValidator = function(value) {
var patternObj = scope.$eval(pattern);
if (!patternObj || !patternObj.test) {
throw new Error('Expected ' + pattern +
' to be a RegExp but was ' + patternObj);
}
return validate(patternObj, value);
};
}
ctrl.$formatters.push(patternValidator);
ctrl.$parsers.push(patternValidator);
}
// min length validator
if (attr.ngMinlength) {
var minlength = int(attr.ngMinlength);
var minLengthValidator = function(value) {
if (!isEmpty(value) && value.length < minlength) {
ctrl.$setValidity('minlength', false);
return undefined;
} else {
ctrl.$setValidity('minlength', true);
return value;
}
};
ctrl.$parsers.push(minLengthValidator);
ctrl.$formatters.push(minLengthValidator);
}
// max length validator
if (attr.ngMaxlength) {
var maxlength = int(attr.ngMaxlength);
var maxLengthValidator = function(value) {
if (!isEmpty(value) && value.length > maxlength) {
ctrl.$setValidity('maxlength', false);
return undefined;
} else {
ctrl.$setValidity('maxlength', true);
return value;
}
};
ctrl.$parsers.push(maxLengthValidator);
ctrl.$formatters.push(maxLengthValidator);
}
}
function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
textInputType(scope, element, attr, ctrl, $sniffer, $browser);
ctrl.$parsers.push(function(value) {
var empty = isEmpty(value);
if (empty || NUMBER_REGEXP.test(value)) {
ctrl.$setValidity('number', true);
return value === '' ? null : (empty ? value : parseFloat(value));
} else {
ctrl.$setValidity('number', false);
return undefined;
}
});
ctrl.$formatters.push(function(value) {
return isEmpty(value) ? '' : '' + value;
});
if (attr.min) {
var min = parseFloat(attr.min);
var minValidator = function(value) {
if (!isEmpty(value) && value < min) {
ctrl.$setValidity('min', false);
return undefined;
} else {
ctrl.$setValidity('min', true);
return value;
}
};
ctrl.$parsers.push(minValidator);
ctrl.$formatters.push(minValidator);
}
if (attr.max) {
var max = parseFloat(attr.max);
var maxValidator = function(value) {
if (!isEmpty(value) && value > max) {
ctrl.$setValidity('max', false);
return undefined;
} else {
ctrl.$setValidity('max', true);
return value;
}
};
ctrl.$parsers.push(maxValidator);
ctrl.$formatters.push(maxValidator);
}
ctrl.$formatters.push(function(value) {
if (isEmpty(value) || isNumber(value)) {
ctrl.$setValidity('number', true);
return value;
} else {
ctrl.$setValidity('number', false);
return undefined;
}
});
}
function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
textInputType(scope, element, attr, ctrl, $sniffer, $browser);
var urlValidator = function(value) {
if (isEmpty(value) || URL_REGEXP.test(value)) {
ctrl.$setValidity('url', true);
return value;
} else {
ctrl.$setValidity('url', false);
return undefined;
}
};
ctrl.$formatters.push(urlValidator);
ctrl.$parsers.push(urlValidator);
}
function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
textInputType(scope, element, attr, ctrl, $sniffer, $browser);
var emailValidator = function(value) {
if (isEmpty(value) || EMAIL_REGEXP.test(value)) {
ctrl.$setValidity('email', true);
return value;
} else {
ctrl.$setValidity('email', false);
return undefined;
}
};
ctrl.$formatters.push(emailValidator);
ctrl.$parsers.push(emailValidator);
}
function radioInputType(scope, element, attr, ctrl) {
// make the name unique, if not defined
if (isUndefined(attr.name)) {
element.attr('name', nextUid());
}
element.bind('click', function() {
if (element[0].checked) {
scope.$apply(function() {
ctrl.$setViewValue(attr.value);
});
}
});
ctrl.$render = function() {
var value = attr.value;
element[0].checked = (value == ctrl.$viewValue);
};
attr.$observe('value', ctrl.$render);
}
function checkboxInputType(scope, element, attr, ctrl) {
var trueValue = attr.ngTrueValue,
falseValue = attr.ngFalseValue;
if (!isString(trueValue)) trueValue = true;
if (!isString(falseValue)) falseValue = false;
element.bind('click', function() {
scope.$apply(function() {
ctrl.$setViewValue(element[0].checked);
});
});
ctrl.$render = function() {
element[0].checked = ctrl.$viewValue;
};
ctrl.$formatters.push(function(value) {
return value === trueValue;
});
ctrl.$parsers.push(function(value) {
return value ? trueValue : falseValue;
});
}
/**
* @ngdoc directive
* @name ng.directive:textarea
* @restrict E
*
* @description
* HTML textarea element control with angular data-binding. The data-binding and validation
* properties of this element are exactly the same as those of the
* {@link ng.directive:input input element}.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*/
/**
* @ngdoc directive
* @name ng.directive:input
* @restrict E
*
* @description
* HTML input element control with angular data-binding. Input control follows HTML5 input types
* and polyfills the HTML5 validation behavior for older browsers.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {boolean=} ngRequired Sets `required` attribute if set to true
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.user = {name: 'guest', last: 'visitor'};
}
</script>
<div ng-controller="Ctrl">
<form name="myForm">
User name: <input type="text" name="userName" ng-model="user.name" required>
<span class="error" ng-show="myForm.userName.$error.required">
Required!</span><br>
Last name: <input type="text" name="lastName" ng-model="user.last"
ng-minlength="3" ng-maxlength="10">
<span class="error" ng-show="myForm.lastName.$error.minlength">
Too short!</span>
<span class="error" ng-show="myForm.lastName.$error.maxlength">
Too long!</span><br>
</form>
<hr>
<tt>user = {{user}}</tt><br/>
<tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br>
<tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br>
<tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br>
<tt>myForm.userName.$error = {{myForm.lastName.$error}}</tt><br>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
<tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br>
<tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br>
</div>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('user')).toEqual('{"name":"guest","last":"visitor"}');
expect(binding('myForm.userName.$valid')).toEqual('true');
expect(binding('myForm.$valid')).toEqual('true');
});
it('should be invalid if empty when required', function() {
input('user.name').enter('');
expect(binding('user')).toEqual('{"last":"visitor"}');
expect(binding('myForm.userName.$valid')).toEqual('false');
expect(binding('myForm.$valid')).toEqual('false');
});
it('should be valid if empty when min length is set', function() {
input('user.last').enter('');
expect(binding('user')).toEqual('{"name":"guest","last":""}');
expect(binding('myForm.lastName.$valid')).toEqual('true');
expect(binding('myForm.$valid')).toEqual('true');
});
it('should be invalid if less than required min length', function() {
input('user.last').enter('xx');
expect(binding('user')).toEqual('{"name":"guest"}');
expect(binding('myForm.lastName.$valid')).toEqual('false');
expect(binding('myForm.lastName.$error')).toMatch(/minlength/);
expect(binding('myForm.$valid')).toEqual('false');
});
it('should be invalid if longer than max length', function() {
input('user.last').enter('some ridiculously long name');
expect(binding('user'))
.toEqual('{"name":"guest"}');
expect(binding('myForm.lastName.$valid')).toEqual('false');
expect(binding('myForm.lastName.$error')).toMatch(/maxlength/);
expect(binding('myForm.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
var inputDirective = ['$browser', '$sniffer',
function($browser, $sniffer) {
return {
restrict: 'E',
require: '?ngModel',
link: function(scope, element, attr, ctrl) {
if (ctrl) {
(inputType[lowercase(attr.type)] || inputType.text)(
scope, element, attr, ctrl, $sniffer,
$browser);
}
}
};
}
];
var VALID_CLASS = 'ng-valid',
INVALID_CLASS = 'ng-invalid',
PRISTINE_CLASS = 'ng-pristine',
DIRTY_CLASS = 'ng-dirty';
/**
* @ngdoc object
* @name ng.directive:ngModel.NgModelController
*
* @property {string} $viewValue Actual string value in the view.
* @property {*} $modelValue The value in the model, that the control is bound to.
* @property {Array.<Function>} $parsers Whenever the control reads value from the DOM, it executes
* all of these functions to sanitize / convert the value as well as validate.
*
* @property {Array.<Function>} $formatters Whenever the model value changes, it executes all of
* these functions to convert the value as well as validate.
*
* @property {Object} $error An bject hash with all errors as keys.
*
* @property {boolean} $pristine True if user has not interacted with the control yet.
* @property {boolean} $dirty True if user has already interacted with the control.
* @property {boolean} $valid True if there is no error.
* @property {boolean} $invalid True if at least one error on the control.
*
* @description
*
* `NgModelController` provides API for the `ng-model` directive. The controller contains
* services for data-binding, validation, CSS update, value formatting and parsing. It
* specifically does not contain any logic which deals with DOM rendering or listening to
* DOM events. The `NgModelController` is meant to be extended by other directives where, the
* directive provides DOM manipulation and the `NgModelController` provides the data-binding.
*
* This example shows how to use `NgModelController` with a custom control to achieve
* data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
* collaborate together to achieve the desired result.
*
* <example module="customControl">
<file name="style.css">
[contenteditable] {
border: 1px solid black;
background-color: white;
min-height: 20px;
}
.ng-invalid {
border: 1px solid red;
}
</file>
<file name="script.js">
angular.module('customControl', []).
directive('contenteditable', function() {
return {
restrict: 'A', // only activate on element attribute
require: '?ngModel', // get a hold of NgModelController
link: function(scope, element, attrs, ngModel) {
if(!ngModel) return; // do nothing if no ng-model
// Specify how UI should be updated
ngModel.$render = function() {
element.html(ngModel.$viewValue || '');
};
// Listen for change events to enable binding
element.bind('blur keyup change', function() {
scope.$apply(read);
});
read(); // initialize
// Write data to the model
function read() {
ngModel.$setViewValue(element.html());
}
}
};
});
</file>
<file name="index.html">
<form name="myForm">
<div contenteditable
name="myWidget" ng-model="userContent"
required>Change me!</div>
<span ng-show="myForm.myWidget.$error.required">Required!</span>
<hr>
<textarea ng-model="userContent"></textarea>
</form>
</file>
<file name="scenario.js">
it('should data-bind and become invalid', function() {
var contentEditable = element('[contenteditable]');
expect(contentEditable.text()).toEqual('Change me!');
input('userContent').enter('');
expect(contentEditable.text()).toEqual('');
expect(contentEditable.prop('className')).toMatch(/ng-invalid-required/);
});
</file>
* </example>
*
*/
var NgModelController = ['$scope', '$exceptionHandler', '$attrs',
'$element', '$parse',
function($scope, $exceptionHandler, $attr, $element, $parse) {
this.$viewValue = Number.NaN;
this.$modelValue = Number.NaN;
this.$parsers = [];
this.$formatters = [];
this.$viewChangeListeners = [];
this.$pristine = true;
this.$dirty = false;
this.$valid = true;
this.$invalid = false;
this.$name = $attr.name;
var ngModelGet = $parse($attr.ngModel),
ngModelSet = ngModelGet.assign;
if (!ngModelSet) {
throw Error(NON_ASSIGNABLE_MODEL_EXPRESSION + $attr.ngModel +
' (' + startingTag($element) + ')');
}
/**
* @ngdoc function
* @name ng.directive:ngModel.NgModelController#$render
* @methodOf ng.directive:ngModel.NgModelController
*
* @description
* Called when the view needs to be updated. It is expected that the user of the ng-model
* directive will implement this method.
*/
this.$render = noop;
var parentForm = $element.inheritedData('$formController') ||
nullFormCtrl,
invalidCount = 0, // used to easily determine if we are valid
$error = this.$error = {}; // keep invalid keys here
// Setup initial state of the control
$element.addClass(PRISTINE_CLASS);
toggleValidCss(true);
// convenience method for easy toggling of classes
function toggleValidCss(isValid, validationErrorKey) {
validationErrorKey = validationErrorKey ? '-' + snake_case(
validationErrorKey, '-') : '';
$element.
removeClass((isValid ? INVALID_CLASS : VALID_CLASS) +
validationErrorKey).
addClass((isValid ? VALID_CLASS : INVALID_CLASS) +
validationErrorKey);
}
/**
* @ngdoc function
* @name ng.directive:ngModel.NgModelController#$setValidity
* @methodOf ng.directive:ngModel.NgModelController
*
* @description
* Change the validity state, and notifies the form when the control changes validity. (i.e. it
* does not notify form if given validator is already marked as invalid).
*
* This method should be called by validators - i.e. the parser or formatter functions.
*
* @param {string} validationErrorKey Name of the validator. the `validationErrorKey` will assign
* to `$error[validationErrorKey]=isValid` so that it is available for data-binding.
* The `validationErrorKey` should be in camelCase and will get converted into dash-case
* for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
* class and can be bound to as `{{someForm.someControl.$error.myError}}` .
* @param {boolean} isValid Whether the current state is valid (true) or invalid (false).
*/
this.$setValidity = function(validationErrorKey, isValid) {
if ($error[validationErrorKey] === !isValid) return;
if (isValid) {
if ($error[validationErrorKey]) invalidCount--;
if (!invalidCount) {
toggleValidCss(true);
this.$valid = true;
this.$invalid = false;
}
} else {
toggleValidCss(false);
this.$invalid = true;
this.$valid = false;
invalidCount++;
}
$error[validationErrorKey] = !isValid;
toggleValidCss(isValid, validationErrorKey);
parentForm.$setValidity(validationErrorKey, isValid, this);
};
/**
* @ngdoc function
* @name ng.directive:ngModel.NgModelController#$setViewValue
* @methodOf ng.directive:ngModel.NgModelController
*
* @description
* Read a value from view.
*
* This method should be called from within a DOM event handler.
* For example {@link ng.directive:input input} or
* {@link ng.directive:select select} directives call it.
*
* It internally calls all `formatters` and if resulted value is valid, updates the model and
* calls all registered change listeners.
*
* @param {string} value Value from the view.
*/
this.$setViewValue = function(value) {
this.$viewValue = value;
// change to dirty
if (this.$pristine) {
this.$dirty = true;
this.$pristine = false;
$element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS);
parentForm.$setDirty();
}
forEach(this.$parsers, function(fn) {
value = fn(value);
});
if (this.$modelValue !== value) {
this.$modelValue = value;
ngModelSet($scope, value);
forEach(this.$viewChangeListeners, function(listener) {
try {
listener();
} catch (e) {
$exceptionHandler(e);
}
})
}
};
// model -> value
var ctrl = this;
$scope.$watch(function ngModelWatch() {
var value = ngModelGet($scope);
// if scope model value and ngModel value are out of sync
if (ctrl.$modelValue !== value) {
var formatters = ctrl.$formatters,
idx = formatters.length;
ctrl.$modelValue = value;
while (idx--) {
value = formatters[idx](value);
}
if (ctrl.$viewValue !== value) {
ctrl.$viewValue = value;
ctrl.$render();
}
}
});
}
];
/**
* @ngdoc directive
* @name ng.directive:ngModel
*
* @element input
*
* @description
* Is directive that tells Angular to do two-way data binding. It works together with `input`,
* `select`, `textarea`. You can easily write your own directives to use `ngModel` as well.
*
* `ngModel` is responsible for:
*
* - binding the view into the model, which other directives such as `input`, `textarea` or `select`
* require,
* - providing validation behavior (i.e. required, number, email, url),
* - keeping state of the control (valid/invalid, dirty/pristine, validation errors),
* - setting related css class onto the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`),
* - register the control with parent {@link ng.directive:form form}.
*
* For basic examples, how to use `ngModel`, see:
*
* - {@link ng.directive:input input}
* - {@link ng.directive:input.text text}
* - {@link ng.directive:input.checkbox checkbox}
* - {@link ng.directive:input.radio radio}
* - {@link ng.directive:input.number number}
* - {@link ng.directive:input.email email}
* - {@link ng.directive:input.url url}
* - {@link ng.directive:select select}
* - {@link ng.directive:textarea textarea}
*
*/
var ngModelDirective = function() {
return {
require: ['ngModel', '^?form'],
controller: NgModelController,
link: function(scope, element, attr, ctrls) {
// notify others, especially parent forms
var modelCtrl = ctrls[0],
formCtrl = ctrls[1] || nullFormCtrl;
formCtrl.$addControl(modelCtrl);
element.bind('$destroy', function() {
formCtrl.$removeControl(modelCtrl);
});
}
};
};
/**
* @ngdoc directive
* @name ng.directive:ngChange
* @restrict E
*
* @description
* Evaluate given expression when user changes the input.
* The expression is not evaluated when the value change is coming from the model.
*
* Note, this directive requires `ngModel` to be present.
*
* @element input
*
* @example
* <doc:example>
* <doc:source>
* <script>
* function Controller($scope) {
* $scope.counter = 0;
* $scope.change = function() {
* $scope.counter++;
* };
* }
* </script>
* <div ng-controller="Controller">
* <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
* <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
* <label for="ng-change-example2">Confirmed</label><br />
* debug = {{confirmed}}<br />
* counter = {{counter}}
* </div>
* </doc:source>
* <doc:scenario>
* it('should evaluate the expression if changing from view', function() {
* expect(binding('counter')).toEqual('0');
* element('#ng-change-example1').click();
* expect(binding('counter')).toEqual('1');
* expect(binding('confirmed')).toEqual('true');
* });
*
* it('should not evaluate the expression if changing from model', function() {
* element('#ng-change-example2').click();
* expect(binding('counter')).toEqual('0');
* expect(binding('confirmed')).toEqual('true');
* });
* </doc:scenario>
* </doc:example>
*/
var ngChangeDirective = valueFn({
require: 'ngModel',
link: function(scope, element, attr, ctrl) {
ctrl.$viewChangeListeners.push(function() {
scope.$eval(attr.ngChange);
});
}
});
var requiredDirective = function() {
return {
require: '?ngModel',
link: function(scope, elm, attr, ctrl) {
if (!ctrl) return;
attr.required = true; // force truthy in case we are on non input element
var validator = function(value) {
if (attr.required && (isEmpty(value) || value === false)) {
ctrl.$setValidity('required', false);
return;
} else {
ctrl.$setValidity('required', true);
return value;
}
};
ctrl.$formatters.push(validator);
ctrl.$parsers.unshift(validator);
attr.$observe('required', function() {
validator(ctrl.$viewValue);
});
}
};
};
/**
* @ngdoc directive
* @name ng.directive:ngList
*
* @description
* Text input that converts between comma-separated string into an array of strings.
*
* @element input
* @param {string=} ngList optional delimiter that should be used to split the value. If
* specified in form `/something/` then the value will be converted into a regular expression.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.names = ['igor', 'misko', 'vojta'];
}
</script>
<form name="myForm" ng-controller="Ctrl">
List: <input name="namesInput" ng-model="names" ng-list required>
<span class="error" ng-show="myForm.list.$error.required">
Required!</span>
<tt>names = {{names}}</tt><br/>
<tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
<tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('names')).toEqual('["igor","misko","vojta"]');
expect(binding('myForm.namesInput.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('names').enter('');
expect(binding('names')).toEqual('[]');
expect(binding('myForm.namesInput.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
var ngListDirective = function() {
return {
require: 'ngModel',
link: function(scope, element, attr, ctrl) {
var match = /\/(.*)\//.exec(attr.ngList),
separator = match && new RegExp(match[1]) || attr.ngList ||
',';
var parse = function(viewValue) {
var list = [];
if (viewValue) {
forEach(viewValue.split(separator), function(value) {
if (value) list.push(trim(value));
});
}
return list;
};
ctrl.$parsers.push(parse);
ctrl.$formatters.push(function(value) {
if (isArray(value)) {
return value.join(', ');
}
return undefined;
});
}
};
};
var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
var ngValueDirective = function() {
return {
priority: 100,
compile: function(tpl, tplAttr) {
if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
return function(scope, elm, attr) {
attr.$set('value', scope.$eval(attr.ngValue));
};
} else {
return function(scope, elm, attr) {
scope.$watch(attr.ngValue, function valueWatchAction(
value) {
attr.$set('value', value, false);
});
};
}
}
};
};
/**
* @ngdoc directive
* @name ng.directive:ngBind
*
* @description
* The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
* with the value of a given expression, and to update the text content when the value of that
* expression changes.
*
* Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
* `{{ expression }}` which is similar but less verbose.
*
* Once scenario in which the use of `ngBind` is prefered over `{{ expression }}` binding is when
* it's desirable to put bindings into template that is momentarily displayed by the browser in its
* raw state before Angular compiles it. Since `ngBind` is an element attribute, it makes the
* bindings invisible to the user while the page is loading.
*
* An alternative solution to this problem would be using the
* {@link ng.directive:ngCloak ngCloak} directive.
*
*
* @element ANY
* @param {expression} ngBind {@link guide/expression Expression} to evaluate.
*
* @example
* Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.name = 'Whirled';
}
</script>
<div ng-controller="Ctrl">
Enter name: <input type="text" ng-model="name"><br>
Hello <span ng-bind="name"></span>!
</div>
</doc:source>
<doc:scenario>
it('should check ng-bind', function() {
expect(using('.doc-example-live').binding('name')).toBe('Whirled');
using('.doc-example-live').input('name').enter('world');
expect(using('.doc-example-live').binding('name')).toBe('world');
});
</doc:scenario>
</doc:example>
*/
var ngBindDirective = ngDirective(function(scope, element, attr) {
element.addClass('ng-binding').data('$binding', attr.ngBind);
scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
element.text(value == undefined ? '' : value);
});
});
/**
* @ngdoc directive
* @name ng.directive:ngBindTemplate
*
* @description
* The `ngBindTemplate` directive specifies that the element
* text should be replaced with the template in ngBindTemplate.
* Unlike ngBind the ngBindTemplate can contain multiple `{{` `}}`
* expressions. (This is required since some HTML elements
* can not have SPAN elements such as TITLE, or OPTION to name a few.)
*
* @element ANY
* @param {string} ngBindTemplate template of form
* <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
*
* @example
* Try it here: enter text in text box and watch the greeting change.
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.salutation = 'Hello';
$scope.name = 'World';
}
</script>
<div ng-controller="Ctrl">
Salutation: <input type="text" ng-model="salutation"><br>
Name: <input type="text" ng-model="name"><br>
<pre ng-bind-template="{{salutation}} {{name}}!"></pre>
</div>
</doc:source>
<doc:scenario>
it('should check ng-bind', function() {
expect(using('.doc-example-live').binding('salutation')).
toBe('Hello');
expect(using('.doc-example-live').binding('name')).
toBe('World');
using('.doc-example-live').input('salutation').enter('Greetings');
using('.doc-example-live').input('name').enter('user');
expect(using('.doc-example-live').binding('salutation')).
toBe('Greetings');
expect(using('.doc-example-live').binding('name')).
toBe('user');
});
</doc:scenario>
</doc:example>
*/
var ngBindTemplateDirective = ['$interpolate',
function($interpolate) {
return function(scope, element, attr) {
// TODO: move this to scenario runner
var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
element.addClass('ng-binding').data('$binding', interpolateFn);
attr.$observe('ngBindTemplate', function(value) {
element.text(value);
});
}
}
];
/**
* @ngdoc directive
* @name ng.directive:ngBindHtmlUnsafe
*
* @description
* Creates a binding that will innerHTML the result of evaluating the `expression` into the current
* element. *The innerHTML-ed content will not be sanitized!* You should use this directive only if
* {@link ngSanitize.directive:ngBindHtml ngBindHtml} directive is too
* restrictive and when you absolutely trust the source of the content you are binding to.
*
* See {@link ngSanitize.$sanitize $sanitize} docs for examples.
*
* @element ANY
* @param {expression} ngBindHtmlUnsafe {@link guide/expression Expression} to evaluate.
*/
var ngBindHtmlUnsafeDirective = [
function() {
return function(scope, element, attr) {
element.addClass('ng-binding').data('$binding', attr.ngBindHtmlUnsafe);
scope.$watch(attr.ngBindHtmlUnsafe, function ngBindHtmlUnsafeWatchAction(
value) {
element.html(value || '');
});
};
}
];
function classDirective(name, selector) {
name = 'ngClass' + name;
return ngDirective(function(scope, element, attr) {
var oldVal = undefined;
scope.$watch(attr[name], ngClassWatchAction, true);
attr.$observe('class', function(value) {
var ngClass = scope.$eval(attr[name]);
ngClassWatchAction(ngClass, ngClass);
});
if (name !== 'ngClass') {
scope.$watch('$index', function($index, old$index) {
var mod = $index % 2;
if (mod !== old$index % 2) {
if (mod == selector) {
addClass(scope.$eval(attr[name]));
} else {
removeClass(scope.$eval(attr[name]));
}
}
});
}
function ngClassWatchAction(newVal) {
if (selector === true || scope.$index % 2 === selector) {
if (oldVal && (newVal !== oldVal)) {
removeClass(oldVal);
}
addClass(newVal);
}
oldVal = newVal;
}
function removeClass(classVal) {
if (isObject(classVal) && !isArray(classVal)) {
classVal = map(classVal, function(v, k) {
if (v) return k
});
}
element.removeClass(isArray(classVal) ? classVal.join(' ') :
classVal);
}
function addClass(classVal) {
if (isObject(classVal) && !isArray(classVal)) {
classVal = map(classVal, function(v, k) {
if (v) return k
});
}
if (classVal) {
element.addClass(isArray(classVal) ? classVal.join(' ') :
classVal);
}
}
});
}
/**
* @ngdoc directive
* @name ng.directive:ngClass
*
* @description
* The `ngClass` allows you to set CSS class on HTML element dynamically by databinding an
* expression that represents all classes to be added.
*
* The directive won't add duplicate classes if a particular class was already set.
*
* When the expression changes, the previously added classes are removed and only then the
* new classes are added.
*
* @element ANY
* @param {expression} ngClass {@link guide/expression Expression} to eval. The result
* of the evaluation can be a string representing space delimited class
* names, an array, or a map of class names to boolean values.
*
* @example
<example>
<file name="index.html">
<input type="button" value="set" ng-click="myVar='my-class'">
<input type="button" value="clear" ng-click="myVar=''">
<br>
<span ng-class="myVar">Sample Text</span>
</file>
<file name="style.css">
.my-class {
color: red;
}
</file>
<file name="scenario.js">
it('should check ng-class', function() {
expect(element('.doc-example-live span').prop('className')).not().
toMatch(/my-class/);
using('.doc-example-live').element(':button:first').click();
expect(element('.doc-example-live span').prop('className')).
toMatch(/my-class/);
using('.doc-example-live').element(':button:last').click();
expect(element('.doc-example-live span').prop('className')).not().
toMatch(/my-class/);
});
</file>
</example>
*/
var ngClassDirective = classDirective('', true);
/**
* @ngdoc directive
* @name ng.directive:ngClassOdd
*
* @description
* The `ngClassOdd` and `ngClassEven` directives work exactly as
* {@link ng.directive:ngClass ngClass}, except it works in
* conjunction with `ngRepeat` and takes affect only on odd (even) rows.
*
* This directive can be applied only within a scope of an
* {@link ng.directive:ngRepeat ngRepeat}.
*
* @element ANY
* @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
* of the evaluation can be a string representing space delimited class names or an array.
*
* @example
<example>
<file name="index.html">
<ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
<li ng-repeat="name in names">
<span ng-class-odd="'odd'" ng-class-even="'even'">
{{name}}
</span>
</li>
</ol>
</file>
<file name="style.css">
.odd {
color: red;
}
.even {
color: blue;
}
</file>
<file name="scenario.js">
it('should check ng-class-odd and ng-class-even', function() {
expect(element('.doc-example-live li:first span').prop('className')).
toMatch(/odd/);
expect(element('.doc-example-live li:last span').prop('className')).
toMatch(/even/);
});
</file>
</example>
*/
var ngClassOddDirective = classDirective('Odd', 0);
/**
* @ngdoc directive
* @name ng.directive:ngClassEven
*
* @description
* The `ngClassOdd` and `ngClassEven` works exactly as
* {@link ng.directive:ngClass ngClass}, except it works in
* conjunction with `ngRepeat` and takes affect only on odd (even) rows.
*
* This directive can be applied only within a scope of an
* {@link ng.directive:ngRepeat ngRepeat}.
*
* @element ANY
* @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
* result of the evaluation can be a string representing space delimited class names or an array.
*
* @example
<example>
<file name="index.html">
<ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
<li ng-repeat="name in names">
<span ng-class-odd="'odd'" ng-class-even="'even'">
{{name}}
</span>
</li>
</ol>
</file>
<file name="style.css">
.odd {
color: red;
}
.even {
color: blue;
}
</file>
<file name="scenario.js">
it('should check ng-class-odd and ng-class-even', function() {
expect(element('.doc-example-live li:first span').prop('className')).
toMatch(/odd/);
expect(element('.doc-example-live li:last span').prop('className')).
toMatch(/even/);
});
</file>
</example>
*/
var ngClassEvenDirective = classDirective('Even', 1);
/**
* @ngdoc directive
* @name ng.directive:ngCloak
*
* @description
* The `ngCloak` directive is used to prevent the Angular html template from being briefly
* displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
* directive to avoid the undesirable flicker effect caused by the html template display.
*
* The directive can be applied to the `<body>` element, but typically a fine-grained application is
* prefered in order to benefit from progressive rendering of the browser view.
*
* `ngCloak` works in cooperation with a css rule that is embedded within `angular.js` and
* `angular.min.js` files. Following is the css rule:
*
* <pre>
* [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
* display: none;
* }
* </pre>
*
* When this css rule is loaded by the browser, all html elements (including their children) that
* are tagged with the `ng-cloak` directive are hidden. When Angular comes across this directive
* during the compilation of the template it deletes the `ngCloak` element attribute, which
* makes the compiled element visible.
*
* For the best result, `angular.js` script must be loaded in the head section of the html file;
* alternatively, the css rule (above) must be included in the external stylesheet of the
* application.
*
* Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they
* cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css
* class `ngCloak` in addition to `ngCloak` directive as shown in the example below.
*
* @element ANY
*
* @example
<doc:example>
<doc:source>
<div id="template1" ng-cloak>{{ 'hello' }}</div>
<div id="template2" ng-cloak class="ng-cloak">{{ 'hello IE7' }}</div>
</doc:source>
<doc:scenario>
it('should remove the template directive and css class', function() {
expect(element('.doc-example-live #template1').attr('ng-cloak')).
not().toBeDefined();
expect(element('.doc-example-live #template2').attr('ng-cloak')).
not().toBeDefined();
});
</doc:scenario>
</doc:example>
*
*/
var ngCloakDirective = ngDirective({
compile: function(element, attr) {
attr.$set('ngCloak', undefined);
element.removeClass('ng-cloak');
}
});
/**
* @ngdoc directive
* @name ng.directive:ngController
*
* @description
* The `ngController` directive assigns behavior to a scope. This is a key aspect of how angular
* supports the principles behind the Model-View-Controller design pattern.
*
* MVC components in angular:
*
* * Model — The Model is data in scope properties; scopes are attached to the DOM.
* * View — The template (HTML with data bindings) is rendered into the View.
* * Controller — The `ngController` directive specifies a Controller class; the class has
* methods that typically express the business logic behind the application.
*
* Note that an alternative way to define controllers is via the `{@link ng.$route}`
* service.
*
* @element ANY
* @scope
* @param {expression} ngController Name of a globally accessible constructor function or an
* {@link guide/expression expression} that on the current scope evaluates to a
* constructor function.
*
* @example
* Here is a simple form for editing user contact information. Adding, removing, clearing, and
* greeting are methods declared on the controller (see source tab). These methods can
* easily be called from the angular markup. Notice that the scope becomes the `this` for the
* controller's instance. This allows for easy access to the view data from the controller. Also
* notice that any changes to the data are automatically reflected in the View without the need
* for a manual update.
<doc:example>
<doc:source>
<script>
function SettingsController($scope) {
$scope.name = "John Smith";
$scope.contacts = [
{type:'phone', value:'408 555 1212'},
{type:'email', value:'john.smith@example.org'} ];
$scope.greet = function() {
alert(this.name);
};
$scope.addContact = function() {
this.contacts.push({type:'email', value:'yourname@example.org'});
};
$scope.removeContact = function(contactToRemove) {
var index = this.contacts.indexOf(contactToRemove);
this.contacts.splice(index, 1);
};
$scope.clearContact = function(contact) {
contact.type = 'phone';
contact.value = '';
};
}
</script>
<div ng-controller="SettingsController">
Name: <input type="text" ng-model="name"/>
[ <a href="" ng-click="greet()">greet</a> ]<br/>
Contact:
<ul>
<li ng-repeat="contact in contacts">
<select ng-model="contact.type">
<option>phone</option>
<option>email</option>
</select>
<input type="text" ng-model="contact.value"/>
[ <a href="" ng-click="clearContact(contact)">clear</a>
| <a href="" ng-click="removeContact(contact)">X</a> ]
</li>
<li>[ <a href="" ng-click="addContact()">add</a> ]</li>
</ul>
</div>
</doc:source>
<doc:scenario>
it('should check controller', function() {
expect(element('.doc-example-live div>:input').val()).toBe('John Smith');
expect(element('.doc-example-live li:nth-child(1) input').val())
.toBe('408 555 1212');
expect(element('.doc-example-live li:nth-child(2) input').val())
.toBe('john.smith@example.org');
element('.doc-example-live li:first a:contains("clear")').click();
expect(element('.doc-example-live li:first input').val()).toBe('');
element('.doc-example-live li:last a:contains("add")').click();
expect(element('.doc-example-live li:nth-child(3) input').val())
.toBe('yourname@example.org');
});
</doc:scenario>
</doc:example>
*/
var ngControllerDirective = [
function() {
return {
scope: true,
controller: '@'
};
}
];
/**
* @ngdoc directive
* @name ng.directive:ngCsp
* @priority 1000
*
* @description
* Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support.
* This directive should be used on the root element of the application (typically the `<html>`
* element or other element with the {@link ng.directive:ngApp ngApp}
* directive).
*
* If enabled the performance of template expression evaluator will suffer slightly, so don't enable
* this mode unless you need it.
*
* @element html
*/
var ngCspDirective = ['$sniffer',
function($sniffer) {
return {
priority: 1000,
compile: function() {
$sniffer.csp = true;
}
};
}
];
/**
* @ngdoc directive
* @name ng.directive:ngClick
*
* @description
* The ngClick allows you to specify custom behavior when
* element is clicked.
*
* @element ANY
* @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
* click. (Event object is available as `$event`)
*
* @example
<doc:example>
<doc:source>
<button ng-click="count = count + 1" ng-init="count=0">
Increment
</button>
count: {{count}}
</doc:source>
<doc:scenario>
it('should check ng-click', function() {
expect(binding('count')).toBe('0');
element('.doc-example-live :button').click();
expect(binding('count')).toBe('1');
});
</doc:scenario>
</doc:example>
*/
/*
* A directive that allows creation of custom onclick handlers that are defined as angular
* expressions and are compiled and executed within the current scope.
*
* Events that are handled via these handler are always configured not to propagate further.
*/
var ngEventDirectives = {};
forEach(
'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave'
.split(' '), function(name) {
var directiveName = directiveNormalize('ng-' + name);
ngEventDirectives[directiveName] = ['$parse',
function($parse) {
return function(scope, element, attr) {
var fn = $parse(attr[directiveName]);
element.bind(lowercase(name), function(event) {
scope.$apply(function() {
fn(scope, {
$event: event
});
});
});
};
}
];
});
/**
* @ngdoc directive
* @name ng.directive:ngDblclick
*
* @description
* The `ngDblclick` directive allows you to specify custom behavior on dblclick event.
*
* @element ANY
* @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
* dblclick. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMousedown
*
* @description
* The ngMousedown directive allows you to specify custom behavior on mousedown event.
*
* @element ANY
* @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
* mousedown. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMouseup
*
* @description
* Specify custom behavior on mouseup event.
*
* @element ANY
* @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
* mouseup. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMouseover
*
* @description
* Specify custom behavior on mouseover event.
*
* @element ANY
* @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
* mouseover. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMouseenter
*
* @description
* Specify custom behavior on mouseenter event.
*
* @element ANY
* @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
* mouseenter. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMouseleave
*
* @description
* Specify custom behavior on mouseleave event.
*
* @element ANY
* @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
* mouseleave. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMousemove
*
* @description
* Specify custom behavior on mousemove event.
*
* @element ANY
* @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
* mousemove. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngSubmit
*
* @description
* Enables binding angular expressions to onsubmit events.
*
* Additionally it prevents the default action (which for form means sending the request to the
* server and reloading the current page).
*
* @element form
* @param {expression} ngSubmit {@link guide/expression Expression} to eval.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.list = [];
$scope.text = 'hello';
$scope.submit = function() {
if (this.text) {
this.list.push(this.text);
this.text = '';
}
};
}
</script>
<form ng-submit="submit()" ng-controller="Ctrl">
Enter text and hit enter:
<input type="text" ng-model="text" name="text" />
<input type="submit" id="submit" value="Submit" />
<pre>list={{list}}</pre>
</form>
</doc:source>
<doc:scenario>
it('should check ng-submit', function() {
expect(binding('list')).toBe('[]');
element('.doc-example-live #submit').click();
expect(binding('list')).toBe('["hello"]');
expect(input('text').val()).toBe('');
});
it('should ignore empty strings', function() {
expect(binding('list')).toBe('[]');
element('.doc-example-live #submit').click();
element('.doc-example-live #submit').click();
expect(binding('list')).toBe('["hello"]');
});
</doc:scenario>
</doc:example>
*/
var ngSubmitDirective = ngDirective(function(scope, element, attrs) {
element.bind('submit', function() {
scope.$apply(attrs.ngSubmit);
});
});
/**
* @ngdoc directive
* @name ng.directive:ngInclude
* @restrict ECA
*
* @description
* Fetches, compiles and includes an external HTML fragment.
*
* Keep in mind that Same Origin Policy applies to included resources
* (e.g. ngInclude won't work for cross-domain requests on all browsers and for
* file:// access on some browsers).
*
* @scope
*
* @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
* make sure you wrap it in quotes, e.g. `src="'myPartialTemplate.html'"`.
* @param {string=} onload Expression to evaluate when a new partial is loaded.
*
* @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
* $anchorScroll} to scroll the viewport after the content is loaded.
*
* - If the attribute is not set, disable scrolling.
* - If the attribute is set without value, enable scrolling.
* - Otherwise enable scrolling only if the expression evaluates to truthy value.
*
* @example
<example>
<file name="index.html">
<div ng-controller="Ctrl">
<select ng-model="template" ng-options="t.name for t in templates">
<option value="">(blank)</option>
</select>
url of the template: <tt>{{template.url}}</tt>
<hr/>
<div ng-include src="template.url"></div>
</div>
</file>
<file name="script.js">
function Ctrl($scope) {
$scope.templates =
[ { name: 'template1.html', url: 'template1.html'}
, { name: 'template2.html', url: 'template2.html'} ];
$scope.template = $scope.templates[0];
}
</file>
<file name="template1.html">
Content of template1.html
</file>
<file name="template2.html">
Content of template2.html
</file>
<file name="scenario.js">
it('should load template1.html', function() {
expect(element('.doc-example-live [ng-include]').text()).
toMatch(/Content of template1.html/);
});
it('should load template2.html', function() {
select('template').option('1');
expect(element('.doc-example-live [ng-include]').text()).
toMatch(/Content of template2.html/);
});
it('should change to blank', function() {
select('template').option('');
expect(element('.doc-example-live [ng-include]').text()).toEqual('');
});
</file>
</example>
*/
/**
* @ngdoc event
* @name ng.directive:ngInclude#$includeContentLoaded
* @eventOf ng.directive:ngInclude
* @eventType emit on the current ngInclude scope
* @description
* Emitted every time the ngInclude content is reloaded.
*/
var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll',
'$compile',
function($http, $templateCache, $anchorScroll, $compile) {
return {
restrict: 'ECA',
terminal: true,
compile: function(element, attr) {
var srcExp = attr.ngInclude || attr.src,
onloadExp = attr.onload || '',
autoScrollExp = attr.autoscroll;
return function(scope, element) {
var changeCounter = 0,
childScope;
var clearContent = function() {
if (childScope) {
childScope.$destroy();
childScope = null;
}
element.html('');
};
scope.$watch(srcExp, function ngIncludeWatchAction(src) {
var thisChangeId = ++changeCounter;
if (src) {
$http.get(src, {
cache: $templateCache
}).success(function(response) {
if (thisChangeId !== changeCounter) return;
if (childScope) childScope.$destroy();
childScope = scope.$new();
element.html(response);
$compile(element.contents())(childScope);
if (isDefined(autoScrollExp) && (!
autoScrollExp || scope.$eval(
autoScrollExp))) {
$anchorScroll();
}
childScope.$emit('$includeContentLoaded');
scope.$eval(onloadExp);
}).error(function() {
if (thisChangeId === changeCounter)
clearContent();
});
} else clearContent();
});
};
}
};
}
];
/**
* @ngdoc directive
* @name ng.directive:ngInit
*
* @description
* The `ngInit` directive specifies initialization tasks to be executed
* before the template enters execution mode during bootstrap.
*
* @element ANY
* @param {expression} ngInit {@link guide/expression Expression} to eval.
*
* @example
<doc:example>
<doc:source>
<div ng-init="greeting='Hello'; person='World'">
{{greeting}} {{person}}!
</div>
</doc:source>
<doc:scenario>
it('should check greeting', function() {
expect(binding('greeting')).toBe('Hello');
expect(binding('person')).toBe('World');
});
</doc:scenario>
</doc:example>
*/
var ngInitDirective = ngDirective({
compile: function() {
return {
pre: function(scope, element, attrs) {
scope.$eval(attrs.ngInit);
}
}
}
});
/**
* @ngdoc directive
* @name ng.directive:ngNonBindable
* @priority 1000
*
* @description
* Sometimes it is necessary to write code which looks like bindings but which should be left alone
* by angular. Use `ngNonBindable` to make angular ignore a chunk of HTML.
*
* @element ANY
*
* @example
* In this example there are two location where a simple binding (`{{}}`) is present, but the one
* wrapped in `ngNonBindable` is left alone.
*
* @example
<doc:example>
<doc:source>
<div>Normal: {{1 + 2}}</div>
<div ng-non-bindable>Ignored: {{1 + 2}}</div>
</doc:source>
<doc:scenario>
it('should check ng-non-bindable', function() {
expect(using('.doc-example-live').binding('1 + 2')).toBe('3');
expect(using('.doc-example-live').element('div:last').text()).
toMatch(/1 \+ 2/);
});
</doc:scenario>
</doc:example>
*/
var ngNonBindableDirective = ngDirective({
terminal: true,
priority: 1000
});
/**
* @ngdoc directive
* @name ng.directive:ngPluralize
* @restrict EA
*
* @description
* # Overview
* `ngPluralize` is a directive that displays messages according to en-US localization rules.
* These rules are bundled with angular.js and the rules can be overridden
* (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
* by specifying the mappings between
* {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html
* plural categories} and the strings to be displayed.
*
* # Plural categories and explicit number rules
* There are two
* {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html
* plural categories} in Angular's default en-US locale: "one" and "other".
*
* While a pural category may match many numbers (for example, in en-US locale, "other" can match
* any number that is not 1), an explicit number rule can only match one number. For example, the
* explicit number rule for "3" matches the number 3. You will see the use of plural categories
* and explicit number rules throughout later parts of this documentation.
*
* # Configuring ngPluralize
* You configure ngPluralize by providing 2 attributes: `count` and `when`.
* You can also provide an optional attribute, `offset`.
*
* The value of the `count` attribute can be either a string or an {@link guide/expression
* Angular expression}; these are evaluated on the current scope for its bound value.
*
* The `when` attribute specifies the mappings between plural categories and the actual
* string to be displayed. The value of the attribute should be a JSON object so that Angular
* can interpret it correctly.
*
* The following example shows how to configure ngPluralize:
*
* <pre>
* <ng-pluralize count="personCount"
when="{'0': 'Nobody is viewing.',
* 'one': '1 person is viewing.',
* 'other': '{} people are viewing.'}">
* </ng-pluralize>
*</pre>
*
* In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
* specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
* would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
* other numbers, for example 12, so that instead of showing "12 people are viewing", you can
* show "a dozen people are viewing".
*
* You can use a set of closed braces(`{}`) as a placeholder for the number that you want substituted
* into pluralized strings. In the previous example, Angular will replace `{}` with
* <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
* for <span ng-non-bindable>{{numberExpression}}</span>.
*
* # Configuring ngPluralize with offset
* The `offset` attribute allows further customization of pluralized text, which can result in
* a better user experience. For example, instead of the message "4 people are viewing this document",
* you might display "John, Kate and 2 others are viewing this document".
* The offset attribute allows you to offset a number by any desired value.
* Let's take a look at an example:
*
* <pre>
* <ng-pluralize count="personCount" offset=2
* when="{'0': 'Nobody is viewing.',
* '1': '{{person1}} is viewing.',
* '2': '{{person1}} and {{person2}} are viewing.',
* 'one': '{{person1}}, {{person2}} and one other person are viewing.',
* 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
* </ng-pluralize>
* </pre>
*
* Notice that we are still using two plural categories(one, other), but we added
* three explicit number rules 0, 1 and 2.
* When one person, perhaps John, views the document, "John is viewing" will be shown.
* When three people view the document, no explicit number rule is found, so
* an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
* In this case, plural category 'one' is matched and "John, Marry and one other person are viewing"
* is shown.
*
* Note that when you specify offsets, you must provide explicit number rules for
* numbers from 0 up to and including the offset. If you use an offset of 3, for example,
* you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
* plural categories "one" and "other".
*
* @param {string|expression} count The variable to be bounded to.
* @param {string} when The mapping between plural category to its correspoding strings.
* @param {number=} offset Offset to deduct from the total number.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.person1 = 'Igor';
$scope.person2 = 'Misko';
$scope.personCount = 1;
}
</script>
<div ng-controller="Ctrl">
Person 1:<input type="text" ng-model="person1" value="Igor" /><br/>
Person 2:<input type="text" ng-model="person2" value="Misko" /><br/>
Number of People:<input type="text" ng-model="personCount" value="1" /><br/>
<!--- Example with simple pluralization rules for en locale --->
Without Offset:
<ng-pluralize count="personCount"
when="{'0': 'Nobody is viewing.',
'one': '1 person is viewing.',
'other': '{} people are viewing.'}">
</ng-pluralize><br>
<!--- Example with offset --->
With Offset(2):
<ng-pluralize count="personCount" offset=2
when="{'0': 'Nobody is viewing.',
'1': '{{person1}} is viewing.',
'2': '{{person1}} and {{person2}} are viewing.',
'one': '{{person1}}, {{person2}} and one other person are viewing.',
'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
</ng-pluralize>
</div>
</doc:source>
<doc:scenario>
it('should show correct pluralized string', function() {
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('1 person is viewing.');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor is viewing.');
using('.doc-example-live').input('personCount').enter('0');
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('Nobody is viewing.');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Nobody is viewing.');
using('.doc-example-live').input('personCount').enter('2');
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('2 people are viewing.');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor and Misko are viewing.');
using('.doc-example-live').input('personCount').enter('3');
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('3 people are viewing.');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor, Misko and one other person are viewing.');
using('.doc-example-live').input('personCount').enter('4');
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('4 people are viewing.');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor, Misko and 2 other people are viewing.');
});
it('should show data-binded names', function() {
using('.doc-example-live').input('personCount').enter('4');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor, Misko and 2 other people are viewing.');
using('.doc-example-live').input('person1').enter('Di');
using('.doc-example-live').input('person2').enter('Vojta');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Di, Vojta and 2 other people are viewing.');
});
</doc:scenario>
</doc:example>
*/
var ngPluralizeDirective = ['$locale', '$interpolate',
function($locale, $interpolate) {
var BRACE = /{}/g;
return {
restrict: 'EA',
link: function(scope, element, attr) {
var numberExp = attr.count,
whenExp = element.attr(attr.$attr.when), // this is because we have {{}} in attrs
offset = attr.offset || 0,
whens = scope.$eval(whenExp),
whensExpFns = {},
startSymbol = $interpolate.startSymbol(),
endSymbol = $interpolate.endSymbol();
forEach(whens, function(expression, key) {
whensExpFns[key] =
$interpolate(expression.replace(BRACE, startSymbol +
numberExp + '-' +
offset + endSymbol));
});
scope.$watch(function ngPluralizeWatch() {
var value = parseFloat(scope.$eval(numberExp));
if (!isNaN(value)) {
//if explicit number rule such as 1, 2, 3... is defined, just use it. Otherwise,
//check it against pluralization rules in $locale service
if (!whens[value]) value = $locale.pluralCat(value -
offset);
return whensExpFns[value](scope, element, true);
} else {
return '';
}
}, function ngPluralizeWatchAction(newVal) {
element.text(newVal);
});
}
};
}
];
/**
* @ngdoc directive
* @name ng.directive:ngRepeat
*
* @description
* The `ngRepeat` directive instantiates a template once per item from a collection. Each template
* instance gets its own scope, where the given loop variable is set to the current collection item,
* and `$index` is set to the item index or key.
*
* Special properties are exposed on the local scope of each template instance, including:
*
* * `$index` – `{number}` – iterator offset of the repeated element (0..length-1)
* * `$first` – `{boolean}` – true if the repeated element is first in the iterator.
* * `$middle` – `{boolean}` – true if the repeated element is between the first and last in the iterator.
* * `$last` – `{boolean}` – true if the repeated element is last in the iterator.
*
*
* @element ANY
* @scope
* @priority 1000
* @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. Two
* formats are currently supported:
*
* * `variable in expression` – where variable is the user defined loop variable and `expression`
* is a scope expression giving the collection to enumerate.
*
* For example: `track in cd.tracks`.
*
* * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
* and `expression` is the scope expression giving the collection to enumerate.
*
* For example: `(name, age) in {'adam':10, 'amalie':12}`.
*
* @example
* This example initializes the scope to a list of names and
* then uses `ngRepeat` to display every person:
<doc:example>
<doc:source>
<div ng-init="friends = [{name:'John', age:25}, {name:'Mary', age:28}]">
I have {{friends.length}} friends. They are:
<ul>
<li ng-repeat="friend in friends">
[{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
</li>
</ul>
</div>
</doc:source>
<doc:scenario>
it('should check ng-repeat', function() {
var r = using('.doc-example-live').repeater('ul li');
expect(r.count()).toBe(2);
expect(r.row(0)).toEqual(["1","John","25"]);
expect(r.row(1)).toEqual(["2","Mary","28"]);
});
</doc:scenario>
</doc:example>
*/
var ngRepeatDirective = ngDirective({
transclude: 'element',
priority: 1000,
terminal: true,
compile: function(element, attr, linker) {
return function(scope, iterStartElement, attr) {
var expression = attr.ngRepeat;
var match = expression.match(/^\s*(.+)\s+in\s+(.*)\s*$/),
lhs, rhs, valueIdent, keyIdent;
if (!match) {
throw Error(
"Expected ngRepeat in form of '_item_ in _collection_' but got '" +
expression + "'.");
}
lhs = match[1];
rhs = match[2];
match = lhs.match(
/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/);
if (!match) {
throw Error(
"'item' in 'item in collection' should be identifier or (key, value) but got '" +
lhs + "'.");
}
valueIdent = match[3] || match[1];
keyIdent = match[2];
// Store a list of elements from previous run. This is a hash where key is the item from the
// iterator, and the value is an array of objects with following properties.
// - scope: bound scope
// - element: previous element.
// - index: position
// We need an array of these objects since the same object can be returned from the iterator.
// We expect this to be a rare case.
var lastOrder = new HashQueueMap();
scope.$watch(function ngRepeatWatch(scope) {
var index, length,
collection = scope.$eval(rhs),
cursor = iterStartElement, // current position of the node
// Same as lastOrder but it has the current state. It will become the
// lastOrder on the next iteration.
nextOrder = new HashQueueMap(),
arrayBound,
childScope,
key, value, // key/value of iteration
array,
last; // last object information {scope, element, index}
if (!isArray(collection)) {
// if object, extract keys, sort them and use to determine order of iteration over obj props
array = [];
for (key in collection) {
if (collection.hasOwnProperty(key) && key.charAt(0) !=
'$') {
array.push(key);
}
}
array.sort();
} else {
array = collection || [];
}
arrayBound = array.length - 1;
// we are not using forEach for perf reasons (trying to avoid #call)
for (index = 0, length = array.length; index < length; index++) {
key = (collection === array) ? index : array[index];
value = collection[key];
last = lastOrder.shift(value);
if (last) {
// if we have already seen this object, then we need to reuse the
// associated scope/element
childScope = last.scope;
nextOrder.push(value, last);
if (index === last.index) {
// do nothing
cursor = last.element;
} else {
// existing item which got moved
last.index = index;
// This may be a noop, if the element is next, but I don't know of a good way to
// figure this out, since it would require extra DOM access, so let's just hope that
// the browsers realizes that it is noop, and treats it as such.
cursor.after(last.element);
cursor = last.element;
}
} else {
// new item which we don't know about
childScope = scope.$new();
}
childScope[valueIdent] = value;
if (keyIdent) childScope[keyIdent] = key;
childScope.$index = index;
childScope.$first = (index === 0);
childScope.$last = (index === arrayBound);
childScope.$middle = !(childScope.$first || childScope.$last);
if (!last) {
linker(childScope, function(clone) {
cursor.after(clone);
last = {
scope: childScope,
element: (cursor = clone),
index: index
};
nextOrder.push(value, last);
});
}
}
//shrink children
for (key in lastOrder) {
if (lastOrder.hasOwnProperty(key)) {
array = lastOrder[key];
while (array.length) {
value = array.pop();
value.element.remove();
value.scope.$destroy();
}
}
}
lastOrder = nextOrder;
});
};
}
});
/**
* @ngdoc directive
* @name ng.directive:ngShow
*
* @description
* The `ngShow` and `ngHide` directives show or hide a portion of the DOM tree (HTML)
* conditionally.
*
* @element ANY
* @param {expression} ngShow If the {@link guide/expression expression} is truthy
* then the element is shown or hidden respectively.
*
* @example
<doc:example>
<doc:source>
Click me: <input type="checkbox" ng-model="checked"><br/>
Show: <span ng-show="checked">I show up when your checkbox is checked.</span> <br/>
Hide: <span ng-hide="checked">I hide when your checkbox is checked.</span>
</doc:source>
<doc:scenario>
it('should check ng-show / ng-hide', function() {
expect(element('.doc-example-live span:first:hidden').count()).toEqual(1);
expect(element('.doc-example-live span:last:visible').count()).toEqual(1);
input('checked').check();
expect(element('.doc-example-live span:first:visible').count()).toEqual(1);
expect(element('.doc-example-live span:last:hidden').count()).toEqual(1);
});
</doc:scenario>
</doc:example>
*/
//TODO(misko): refactor to remove element from the DOM
var ngShowDirective = ngDirective(function(scope, element, attr) {
scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
element.css('display', toBoolean(value) ? '' : 'none');
});
});
/**
* @ngdoc directive
* @name ng.directive:ngHide
*
* @description
* The `ngHide` and `ngShow` directives hide or show a portion of the DOM tree (HTML)
* conditionally.
*
* @element ANY
* @param {expression} ngHide If the {@link guide/expression expression} is truthy then
* the element is shown or hidden respectively.
*
* @example
<doc:example>
<doc:source>
Click me: <input type="checkbox" ng-model="checked"><br/>
Show: <span ng-show="checked">I show up when you checkbox is checked?</span> <br/>
Hide: <span ng-hide="checked">I hide when you checkbox is checked?</span>
</doc:source>
<doc:scenario>
it('should check ng-show / ng-hide', function() {
expect(element('.doc-example-live span:first:hidden').count()).toEqual(1);
expect(element('.doc-example-live span:last:visible').count()).toEqual(1);
input('checked').check();
expect(element('.doc-example-live span:first:visible').count()).toEqual(1);
expect(element('.doc-example-live span:last:hidden').count()).toEqual(1);
});
</doc:scenario>
</doc:example>
*/
//TODO(misko): refactor to remove element from the DOM
var ngHideDirective = ngDirective(function(scope, element, attr) {
scope.$watch(attr.ngHide, function ngHideWatchAction(value) {
element.css('display', toBoolean(value) ? 'none' : '');
});
});
/**
* @ngdoc directive
* @name ng.directive:ngStyle
*
* @description
* The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
*
* @element ANY
* @param {expression} ngStyle {@link guide/expression Expression} which evals to an
* object whose keys are CSS style names and values are corresponding values for those CSS
* keys.
*
* @example
<example>
<file name="index.html">
<input type="button" value="set" ng-click="myStyle={color:'red'}">
<input type="button" value="clear" ng-click="myStyle={}">
<br/>
<span ng-style="myStyle">Sample Text</span>
<pre>myStyle={{myStyle}}</pre>
</file>
<file name="style.css">
span {
color: black;
}
</file>
<file name="scenario.js">
it('should check ng-style', function() {
expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)');
element('.doc-example-live :button[value=set]').click();
expect(element('.doc-example-live span').css('color')).toBe('rgb(255, 0, 0)');
element('.doc-example-live :button[value=clear]').click();
expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)');
});
</file>
</example>
*/
var ngStyleDirective = ngDirective(function(scope, element, attr) {
scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles,
oldStyles) {
if (oldStyles && (newStyles !== oldStyles)) {
forEach(oldStyles, function(val, style) {
element.css(style, '');
});
}
if (newStyles) element.css(newStyles);
}, true);
});
/**
* @ngdoc directive
* @name ng.directive:ngSwitch
* @restrict EA
*
* @description
* Conditionally change the DOM structure.
*
* @usage
* <ANY ng-switch="expression">
* <ANY ng-switch-when="matchValue1">...</ANY>
* <ANY ng-switch-when="matchValue2">...</ANY>
* ...
* <ANY ng-switch-default>...</ANY>
* </ANY>
*
* @scope
* @param {*} ngSwitch|on expression to match against <tt>ng-switch-when</tt>.
* @paramDescription
* On child elments add:
*
* * `ngSwitchWhen`: the case statement to match against. If match then this
* case will be displayed.
* * `ngSwitchDefault`: the default case when no other casses match.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.items = ['settings', 'home', 'other'];
$scope.selection = $scope.items[0];
}
</script>
<div ng-controller="Ctrl">
<select ng-model="selection" ng-options="item for item in items">
</select>
<tt>selection={{selection}}</tt>
<hr/>
<div ng-switch on="selection" >
<div ng-switch-when="settings">Settings Div</div>
<span ng-switch-when="home">Home Span</span>
<span ng-switch-default>default</span>
</div>
</div>
</doc:source>
<doc:scenario>
it('should start in settings', function() {
expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Settings Div/);
});
it('should change to home', function() {
select('selection').option('home');
expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Home Span/);
});
it('should select deafault', function() {
select('selection').option('other');
expect(element('.doc-example-live [ng-switch]').text()).toMatch(/default/);
});
</doc:scenario>
</doc:example>
*/
var NG_SWITCH = 'ng-switch';
var ngSwitchDirective = valueFn({
restrict: 'EA',
require: 'ngSwitch',
// asks for $scope to fool the BC controller module
controller: ['$scope',
function ngSwitchController() {
this.cases = {};
}
],
link: function(scope, element, attr, ctrl) {
var watchExpr = attr.ngSwitch || attr.on,
selectedTransclude,
selectedElement,
selectedScope;
scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
if (selectedElement) {
selectedScope.$destroy();
selectedElement.remove();
selectedElement = selectedScope = null;
}
if ((selectedTransclude = ctrl.cases['!' + value] || ctrl.cases[
'?'])) {
scope.$eval(attr.change);
selectedScope = scope.$new();
selectedTransclude(selectedScope, function(caseElement) {
selectedElement = caseElement;
element.append(caseElement);
});
}
});
}
});
var ngSwitchWhenDirective = ngDirective({
transclude: 'element',
priority: 500,
require: '^ngSwitch',
compile: function(element, attrs, transclude) {
return function(scope, element, attr, ctrl) {
ctrl.cases['!' + attrs.ngSwitchWhen] = transclude;
};
}
});
var ngSwitchDefaultDirective = ngDirective({
transclude: 'element',
priority: 500,
require: '^ngSwitch',
compile: function(element, attrs, transclude) {
return function(scope, element, attr, ctrl) {
ctrl.cases['?'] = transclude;
};
}
});
/**
* @ngdoc directive
* @name ng.directive:ngTransclude
*
* @description
* Insert the transcluded DOM here.
*
* @element ANY
*
* @example
<doc:example module="transclude">
<doc:source>
<script>
function Ctrl($scope) {
$scope.title = 'Lorem Ipsum';
$scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
}
angular.module('transclude', [])
.directive('pane', function(){
return {
restrict: 'E',
transclude: true,
scope: 'isolate',
locals: { title:'bind' },
template: '<div style="border: 1px solid black;">' +
'<div style="background-color: gray">{{title}}</div>' +
'<div ng-transclude></div>' +
'</div>'
};
});
</script>
<div ng-controller="Ctrl">
<input ng-model="title"><br>
<textarea ng-model="text"></textarea> <br/>
<pane title="{{title}}">{{text}}</pane>
</div>
</doc:source>
<doc:scenario>
it('should have transcluded', function() {
input('title').enter('TITLE');
input('text').enter('TEXT');
expect(binding('title')).toEqual('TITLE');
expect(binding('text')).toEqual('TEXT');
});
</doc:scenario>
</doc:example>
*
*/
var ngTranscludeDirective = ngDirective({
controller: ['$transclude', '$element',
function($transclude, $element) {
$transclude(function(clone) {
$element.append(clone);
});
}
]
});
/**
* @ngdoc directive
* @name ng.directive:ngView
* @restrict ECA
*
* @description
* # Overview
* `ngView` is a directive that complements the {@link ng.$route $route} service by
* including the rendered template of the current route into the main layout (`index.html`) file.
* Every time the current route changes, the included view changes with it according to the
* configuration of the `$route` service.
*
* @scope
* @example
<example module="ngView">
<file name="index.html">
<div ng-controller="MainCntl">
Choose:
<a href="Book/Moby">Moby</a> |
<a href="Book/Moby/ch/1">Moby: Ch1</a> |
<a href="Book/Gatsby">Gatsby</a> |
<a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
<a href="Book/Scarlet">Scarlet Letter</a><br/>
<div ng-view></div>
<hr />
<pre>$location.path() = {{$location.path()}}</pre>
<pre>$route.current.templateUrl = {{$route.current.templateUrl}}</pre>
<pre>$route.current.params = {{$route.current.params}}</pre>
<pre>$route.current.scope.name = {{$route.current.scope.name}}</pre>
<pre>$routeParams = {{$routeParams}}</pre>
</div>
</file>
<file name="book.html">
controller: {{name}}<br />
Book Id: {{params.bookId}}<br />
</file>
<file name="chapter.html">
controller: {{name}}<br />
Book Id: {{params.bookId}}<br />
Chapter Id: {{params.chapterId}}
</file>
<file name="script.js">
angular.module('ngView', [], function($routeProvider, $locationProvider) {
$routeProvider.when('/Book/:bookId', {
templateUrl: 'book.html',
controller: BookCntl
});
$routeProvider.when('/Book/:bookId/ch/:chapterId', {
templateUrl: 'chapter.html',
controller: ChapterCntl
});
// configure html5 to get links working on jsfiddle
$locationProvider.html5Mode(true);
});
function MainCntl($scope, $route, $routeParams, $location) {
$scope.$route = $route;
$scope.$location = $location;
$scope.$routeParams = $routeParams;
}
function BookCntl($scope, $routeParams) {
$scope.name = "BookCntl";
$scope.params = $routeParams;
}
function ChapterCntl($scope, $routeParams) {
$scope.name = "ChapterCntl";
$scope.params = $routeParams;
}
</file>
<file name="scenario.js">
it('should load and compile correct template', function() {
element('a:contains("Moby: Ch1")').click();
var content = element('.doc-example-live [ng-view]').text();
expect(content).toMatch(/controller\: ChapterCntl/);
expect(content).toMatch(/Book Id\: Moby/);
expect(content).toMatch(/Chapter Id\: 1/);
element('a:contains("Scarlet")').click();
content = element('.doc-example-live [ng-view]').text();
expect(content).toMatch(/controller\: BookCntl/);
expect(content).toMatch(/Book Id\: Scarlet/);
});
</file>
</example>
*/
/**
* @ngdoc event
* @name ng.directive:ngView#$viewContentLoaded
* @eventOf ng.directive:ngView
* @eventType emit on the current ngView scope
* @description
* Emitted every time the ngView content is reloaded.
*/
var ngViewDirective = ['$http', '$templateCache', '$route', '$anchorScroll',
'$compile',
'$controller',
function($http, $templateCache, $route, $anchorScroll, $compile,
$controller) {
return {
restrict: 'ECA',
terminal: true,
link: function(scope, element, attr) {
var lastScope,
onloadExp = attr.onload || '';
scope.$on('$routeChangeSuccess', update);
update();
function destroyLastScope() {
if (lastScope) {
lastScope.$destroy();
lastScope = null;
}
}
function clearContent() {
element.html('');
destroyLastScope();
}
function update() {
var locals = $route.current && $route.current.locals,
template = locals && locals.$template;
if (template) {
element.html(template);
destroyLastScope();
var link = $compile(element.contents()),
current = $route.current,
controller;
lastScope = current.scope = scope.$new();
if (current.controller) {
locals.$scope = lastScope;
controller = $controller(current.controller,
locals);
element.children().data(
'$ngControllerController', controller);
}
link(lastScope);
lastScope.$emit('$viewContentLoaded');
lastScope.$eval(onloadExp);
// $anchorScroll might listen on event...
$anchorScroll();
} else {
clearContent();
}
}
}
};
}
];
/**
* @ngdoc directive
* @name ng.directive:script
*
* @description
* Load content of a script tag, with type `text/ng-template`, into `$templateCache`, so that the
* template can be used by `ngInclude`, `ngView` or directive templates.
*
* @restrict E
* @param {'text/ng-template'} type must be set to `'text/ng-template'`
*
* @example
<doc:example>
<doc:source>
<script type="text/ng-template" id="/tpl.html">
Content of the template.
</script>
<a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
<div id="tpl-content" ng-include src="currentTpl"></div>
</doc:source>
<doc:scenario>
it('should load template defined inside script tag', function() {
element('#tpl-link').click();
expect(element('#tpl-content').text()).toMatch(/Content of the template/);
});
</doc:scenario>
</doc:example>
*/
var scriptDirective = ['$templateCache',
function($templateCache) {
return {
restrict: 'E',
terminal: true,
compile: function(element, attr) {
if (attr.type == 'text/ng-template') {
var templateUrl = attr.id,
// IE is not consistent, in scripts we have to read .text but in other nodes we have to read .textContent
text = element[0].text;
$templateCache.put(templateUrl, text);
}
}
};
}
];
/**
* @ngdoc directive
* @name ng.directive:select
* @restrict E
*
* @description
* HTML `SELECT` element with angular data-binding.
*
* # `ngOptions`
*
* Optionally `ngOptions` attribute can be used to dynamically generate a list of `<option>`
* elements for a `<select>` element using an array or an object obtained by evaluating the
* `ngOptions` expression.
*˝˝
* When an item in the select menu is select, the value of array element or object property
* represented by the selected option will be bound to the model identified by the `ngModel`
* directive of the parent select element.
*
* Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
* be nested into the `<select>` element. This element will then represent `null` or "not selected"
* option. See example below for demonstration.
*
* Note: `ngOptions` provides iterator facility for `<option>` element which should be used instead
* of {@link ng.directive:ngRepeat ngRepeat} when you want the
* `select` model to be bound to a non-string value. This is because an option element can currently
* be bound to string values only.
*
* @param {string} name assignable expression to data-bind to.
* @param {string=} required The control is considered valid only if value is entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {comprehension_expression=} ngOptions in one of the following forms:
*
* * for array data sources:
* * `label` **`for`** `value` **`in`** `array`
* * `select` **`as`** `label` **`for`** `value` **`in`** `array`
* * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
* * `select` **`as`** `label` **`group by`** `group` **`for`** `value` **`in`** `array`
* * for object data sources:
* * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
* * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
* * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
* * `select` **`as`** `label` **`group by`** `group`
* **`for` `(`**`key`**`,`** `value`**`) in`** `object`
*
* Where:
*
* * `array` / `object`: an expression which evaluates to an array / object to iterate over.
* * `value`: local variable which will refer to each item in the `array` or each property value
* of `object` during iteration.
* * `key`: local variable which will refer to a property name in `object` during iteration.
* * `label`: The result of this expression will be the label for `<option>` element. The
* `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
* * `select`: The result of this expression will be bound to the model of the parent `<select>`
* element. If not specified, `select` expression will default to `value`.
* * `group`: The result of this expression will be used to group options using the `<optgroup>`
* DOM element.
*
* @example
<doc:example>
<doc:source>
<script>
function MyCntrl($scope) {
$scope.colors = [
{name:'black', shade:'dark'},
{name:'white', shade:'light'},
{name:'red', shade:'dark'},
{name:'blue', shade:'dark'},
{name:'yellow', shade:'light'}
];
$scope.color = $scope.colors[2]; // red
}
</script>
<div ng-controller="MyCntrl">
<ul>
<li ng-repeat="color in colors">
Name: <input ng-model="color.name">
[<a href ng-click="colors.splice($index, 1)">X</a>]
</li>
<li>
[<a href ng-click="colors.push({})">add</a>]
</li>
</ul>
<hr/>
Color (null not allowed):
<select ng-model="color" ng-options="c.name for c in colors"></select><br>
Color (null allowed):
<span class="nullable">
<select ng-model="color" ng-options="c.name for c in colors">
<option value="">-- chose color --</option>
</select>
</span><br/>
Color grouped by shade:
<select ng-model="color" ng-options="c.name group by c.shade for c in colors">
</select><br/>
Select <a href ng-click="color={name:'not in list'}">bogus</a>.<br>
<hr/>
Currently selected: {{ {selected_color:color} }}
<div style="border:solid 1px black; height:20px"
ng-style="{'background-color':color.name}">
</div>
</div>
</doc:source>
<doc:scenario>
it('should check ng-options', function() {
expect(binding('{selected_color:color}')).toMatch('red');
select('color').option('0');
expect(binding('{selected_color:color}')).toMatch('black');
using('.nullable').select('color').option('');
expect(binding('{selected_color:color}')).toMatch('null');
});
</doc:scenario>
</doc:example>
*/
var ngOptionsDirective = valueFn({
terminal: true
});
var selectDirective = ['$compile', '$parse',
function($compile, $parse) {
//0000111110000000000022220000000000000000000000333300000000000000444444444444444440000000005555555555555555500000006666666666666666600000000000000077770
var NG_OPTIONS_REGEXP =
/^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w\d]*)|(?:\(\s*([\$\w][\$\w\d]*)\s*,\s*([\$\w][\$\w\d]*)\s*\)))\s+in\s+(.*)$/,
nullModelCtrl = {
$setViewValue: noop
};
return {
restrict: 'E',
require: ['select', '?ngModel'],
controller: ['$element', '$scope', '$attrs',
function($element, $scope, $attrs) {
var self = this,
optionsMap = {},
ngModelCtrl = nullModelCtrl,
nullOption,
unknownOption;
self.databound = $attrs.ngModel;
self.init = function(ngModelCtrl_, nullOption_,
unknownOption_) {
ngModelCtrl = ngModelCtrl_;
nullOption = nullOption_;
unknownOption = unknownOption_;
}
self.addOption = function(value) {
optionsMap[value] = true;
if (ngModelCtrl.$viewValue == value) {
$element.val(value);
if (unknownOption.parent()) unknownOption.remove();
}
};
self.removeOption = function(value) {
if (this.hasOption(value)) {
delete optionsMap[value];
if (ngModelCtrl.$viewValue == value) {
this.renderUnknownOption(value);
}
}
};
self.renderUnknownOption = function(val) {
var unknownVal = '? ' + hashKey(val) + ' ?';
unknownOption.val(unknownVal);
$element.prepend(unknownOption);
$element.val(unknownVal);
unknownOption.prop('selected', true); // needed for IE
}
self.hasOption = function(value) {
return optionsMap.hasOwnProperty(value);
}
$scope.$on('$destroy', function() {
// disable unknown option so that we don't do work when the whole select is being destroyed
self.renderUnknownOption = noop;
});
}
],
link: function(scope, element, attr, ctrls) {
// if ngModel is not defined, we don't need to do anything
if (!ctrls[1]) return;
var selectCtrl = ctrls[0],
ngModelCtrl = ctrls[1],
multiple = attr.multiple,
optionsExp = attr.ngOptions,
nullOption = false, // if false, user will not be able to select it (used by ngOptions)
emptyOption,
// we can't just jqLite('<option>') since jqLite is not smart enough
// to create it in <select> and IE barfs otherwise.
optionTemplate = jqLite(document.createElement('option')),
optGroupTemplate = jqLite(document.createElement(
'optgroup')),
unknownOption = optionTemplate.clone();
// find "null" option
for (var i = 0, children = element.children(), ii =
children.length; i < ii; i++) {
if (children[i].value == '') {
emptyOption = nullOption = children.eq(i);
break;
}
}
selectCtrl.init(ngModelCtrl, nullOption, unknownOption);
// required validator
if (multiple && (attr.required || attr.ngRequired)) {
var requiredValidator = function(value) {
ngModelCtrl.$setValidity('required', !attr.required ||
(value && value.length));
return value;
};
ngModelCtrl.$parsers.push(requiredValidator);
ngModelCtrl.$formatters.unshift(requiredValidator);
attr.$observe('required', function() {
requiredValidator(ngModelCtrl.$viewValue);
});
}
if (optionsExp) Options(scope, element, ngModelCtrl);
else if (multiple) Multiple(scope, element, ngModelCtrl);
else Single(scope, element, ngModelCtrl, selectCtrl);
////////////////////////////
function Single(scope, selectElement, ngModelCtrl,
selectCtrl) {
ngModelCtrl.$render = function() {
var viewValue = ngModelCtrl.$viewValue;
if (selectCtrl.hasOption(viewValue)) {
if (unknownOption.parent()) unknownOption.remove();
selectElement.val(viewValue);
if (viewValue === '') emptyOption.prop(
'selected', true); // to make IE9 happy
} else {
if (isUndefined(viewValue) && emptyOption) {
selectElement.val('');
} else {
selectCtrl.renderUnknownOption(viewValue);
}
}
};
selectElement.bind('change', function() {
scope.$apply(function() {
if (unknownOption.parent()) unknownOption.remove();
ngModelCtrl.$setViewValue(selectElement.val());
});
});
}
function Multiple(scope, selectElement, ctrl) {
var lastView;
ctrl.$render = function() {
var items = new HashMap(ctrl.$viewValue);
forEach(selectElement.find('option'), function(
option) {
option.selected = isDefined(items.get(option.value));
});
};
// we have to do it on each watch since ngModel watches reference, but
// we need to work of an array, so we need to see if anything was inserted/removed
scope.$watch(function selectMultipleWatch() {
if (!equals(lastView, ctrl.$viewValue)) {
lastView = copy(ctrl.$viewValue);
ctrl.$render();
}
});
selectElement.bind('change', function() {
scope.$apply(function() {
var array = [];
forEach(selectElement.find('option'), function(
option) {
if (option.selected) {
array.push(option.value);
}
});
ctrl.$setViewValue(array);
});
});
}
function Options(scope, selectElement, ctrl) {
var match;
if (!(match = optionsExp.match(NG_OPTIONS_REGEXP))) {
throw Error(
"Expected ngOptions in form of '_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
" but got '" + optionsExp + "'.");
}
var displayFn = $parse(match[2] || match[1]),
valueName = match[4] || match[6],
keyName = match[5],
groupByFn = $parse(match[3] || ''),
valueFn = $parse(match[2] ? match[1] : valueName),
valuesFn = $parse(match[7]),
// This is an array of array of existing option groups in DOM. We try to reuse these if possible
// optionGroupsCache[0] is the options with no option group
// optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element
optionGroupsCache = [
[{
element: selectElement,
label: ''
}
]
];
if (nullOption) {
// compile the element since there might be bindings in it
$compile(nullOption)(scope);
// remove the class, which is added automatically because we recompile the element and it
// becomes the compilation root
nullOption.removeClass('ng-scope');
// we need to remove it before calling selectElement.html('') because otherwise IE will
// remove the label from the element. wtf?
nullOption.remove();
}
// clear contents, we'll add what's needed based on the model
selectElement.html('');
selectElement.bind('change', function() {
scope.$apply(function() {
var optionGroup,
collection = valuesFn(scope) || [],
locals = {},
key, value, optionElement, index,
groupIndex, length, groupLength;
if (multiple) {
value = [];
for (groupIndex = 0, groupLength =
optionGroupsCache.length; groupIndex <
groupLength; groupIndex++) {
// list of options for that group. (first item has the parent)
optionGroup = optionGroupsCache[
groupIndex];
for (index = 1, length = optionGroup.length; index <
length; index++) {
if ((optionElement = optionGroup[
index].element)[0].selected) {
key = optionElement.val();
if (keyName) locals[keyName] =
key;
locals[valueName] = collection[
key];
value.push(valueFn(scope,
locals));
}
}
}
} else {
key = selectElement.val();
if (key == '?') {
value = undefined;
} else if (key == '') {
value = null;
} else {
locals[valueName] = collection[key];
if (keyName) locals[keyName] = key;
value = valueFn(scope, locals);
}
}
ctrl.$setViewValue(value);
});
});
ctrl.$render = render;
// TODO(vojta): can't we optimize this ?
scope.$watch(render);
function render() {
var optionGroups = {
'': []
}, // Temporary location for the option groups before we render them
optionGroupNames = [''],
optionGroupName,
optionGroup,
option,
existingParent, existingOptions, existingOption,
modelValue = ctrl.$modelValue,
values = valuesFn(scope) || [],
keys = keyName ? sortedKeys(values) : values,
groupLength, length,
groupIndex, index,
locals = {},
selected,
selectedSet = false, // nothing is selected yet
lastElement,
element,
label;
if (multiple) {
selectedSet = new HashMap(modelValue);
} else if (modelValue === null || nullOption) {
// if we are not multiselect, and we are null then we have to add the nullOption
optionGroups[''].push({
selected: modelValue === null,
id: '',
label: ''
});
selectedSet = true;
}
// We now build up the list of options we need (we merge later)
for (index = 0; length = keys.length, index <
length; index++) {
locals[valueName] = values[keyName ? locals[
keyName] = keys[index] : index];
optionGroupName = groupByFn(scope, locals) ||
'';
if (!(optionGroup = optionGroups[
optionGroupName])) {
optionGroup = optionGroups[optionGroupName] = [];
optionGroupNames.push(optionGroupName);
}
if (multiple) {
selected = selectedSet.remove(valueFn(scope,
locals)) != undefined;
} else {
selected = modelValue === valueFn(scope,
locals);
selectedSet = selectedSet || selected; // see if at least one item is selected
}
label = displayFn(scope, locals); // what will be seen by the user
label = label === undefined ? '' : label; // doing displayFn(scope, locals) || '' overwrites zero values
optionGroup.push({
id: keyName ? keys[index] : index, // either the index into array or key from object
label: label,
selected: selected // determine if we should be selected
});
}
if (!multiple && !selectedSet) {
// nothing was selected, we have to insert the undefined item
optionGroups[''].unshift({
id: '?',
label: '',
selected: true
});
}
// Now we need to update the list of DOM nodes to match the optionGroups we computed above
for (groupIndex = 0, groupLength = optionGroupNames
.length; groupIndex < groupLength; groupIndex++) {
// current option group name or '' if no group
optionGroupName = optionGroupNames[groupIndex];
// list of options for that group. (first item has the parent)
optionGroup = optionGroups[optionGroupName];
if (optionGroupsCache.length <= groupIndex) {
// we need to grow the optionGroups
existingParent = {
element: optGroupTemplate.clone().attr(
'label', optionGroupName),
label: optionGroup.label
};
existingOptions = [existingParent];
optionGroupsCache.push(existingOptions);
selectElement.append(existingParent.element);
} else {
existingOptions = optionGroupsCache[
groupIndex];
existingParent = existingOptions[0]; // either SELECT (no group) or OPTGROUP element
// update the OPTGROUP label if not the same.
if (existingParent.label != optionGroupName) {
existingParent.element.attr('label',
existingParent.label =
optionGroupName);
}
}
lastElement = null; // start at the beginning
for (index = 0, length = optionGroup.length; index <
length; index++) {
option = optionGroup[index];
if ((existingOption = existingOptions[index +
1])) {
// reuse elements
lastElement = existingOption.element;
if (existingOption.label !== option.label) {
lastElement.text(existingOption.label =
option.label);
}
if (existingOption.id !== option.id) {
lastElement.val(existingOption.id =
option.id);
}
if (existingOption.element.selected !==
option.selected) {
lastElement.prop('selected', (
existingOption.selected =
option.selected));
}
} else {
// grow elements
// if it's a null option
if (option.id === '' && nullOption) {
// put back the pre-compiled element
element = nullOption;
} else {
// jQuery(v1.4.2) Bug: We should be able to chain the method calls, but
// in this version of jQuery on some browser the .text() returns a string
// rather then the element.
(element = optionTemplate.clone())
.val(option.id)
.attr('selected', option.selected)
.text(option.label);
}
existingOptions.push(existingOption = {
element: element,
label: option.label,
id: option.id,
selected: option.selected
});
if (lastElement) {
lastElement.after(element);
} else {
existingParent.element.append(
element);
}
lastElement = element;
}
}
// remove any excessive OPTIONs in a group
index++; // increment since the existingOptions[0] is parent element not OPTION
while (existingOptions.length > index) {
existingOptions.pop().element.remove();
}
}
// remove any excessive OPTGROUPs from select
while (optionGroupsCache.length > groupIndex) {
optionGroupsCache.pop()[0].element.remove();
}
}
}
}
}
}
];
var optionDirective = ['$interpolate',
function($interpolate) {
var nullSelectCtrl = {
addOption: noop,
removeOption: noop
};
return {
restrict: 'E',
priority: 100,
compile: function(element, attr) {
if (isUndefined(attr.value)) {
var interpolateFn = $interpolate(element.text(), true);
if (!interpolateFn) {
attr.$set('value', element.text());
}
}
return function(scope, element, attr) {
var selectCtrlName = '$selectController',
parent = element.parent(),
selectCtrl = parent.data(selectCtrlName) ||
parent.parent().data(selectCtrlName); // in case we are in optgroup
if (selectCtrl && selectCtrl.databound) {
// For some reason Opera defaults to true and if not overridden this messes up the repeater.
// We don't want the view to drive the initialization of the model anyway.
element.prop('selected', false);
} else {
selectCtrl = nullSelectCtrl;
}
if (interpolateFn) {
scope.$watch(interpolateFn, function interpolateWatchAction(
newVal, oldVal) {
attr.$set('value', newVal);
if (newVal !== oldVal) selectCtrl.removeOption(
oldVal);
selectCtrl.addOption(newVal);
});
} else {
selectCtrl.addOption(attr.value);
}
element.bind('$destroy', function() {
selectCtrl.removeOption(attr.value);
});
};
}
}
}
];
var styleDirective = valueFn({
restrict: 'E',
terminal: true
});
//try to bind to jquery now so that one can write angular.element().read()
//but we will rebind on bootstrap again.
bindJQuery();
publishExternalAPI(angular);
jqLite(document).ready(function() {
angularInit(document, bootstrap);
});
})(window, document);
angular.element(document).find('head').append(
'<style type="text/css">@charset "UTF-8";[ng\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak{display:none;}ng\\:form{display:block;}</style>');
| {
"content_hash": "42a3c06fd481ef80a8849634b5ce3c3b",
"timestamp": "",
"source": "github",
"line_count": 15523,
"max_line_length": 170,
"avg_line_length": 38.73806609547124,
"alnum_prop": 0.4828754878760616,
"repo_name": "diesire/mood",
"id": "9337ba711feb06406263838d8529a5ee083cddcf",
"size": "601500",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server/app/components/angular/angular.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "20968"
},
{
"name": "CSS",
"bytes": "4316"
},
{
"name": "HTML",
"bytes": "25888"
},
{
"name": "JavaScript",
"bytes": "376413"
}
],
"symlink_target": ""
} |
<?php
/**
* Generates human readable output from an PHP_CodeCoverage object.
*
* The output gets put into a text file our written to the CLI.
*
* @since Class available since Release 1.1.0
*/
class PHP_CodeCoverage_Report_Text
{
protected $lowUpperBound;
protected $highLowerBound;
protected $showUncoveredFiles;
protected $showOnlySummary;
protected $colors = array(
'green' => "\x1b[30;42m",
'yellow' => "\x1b[30;43m",
'red' => "\x1b[37;41m",
'header' => "\x1b[1;37;40m",
'reset' => "\x1b[0m",
'eol' => "\x1b[2K",
);
public function __construct($lowUpperBound, $highLowerBound, $showUncoveredFiles, $showOnlySummary)
{
$this->lowUpperBound = $lowUpperBound;
$this->highLowerBound = $highLowerBound;
$this->showUncoveredFiles = $showUncoveredFiles;
$this->showOnlySummary = $showOnlySummary;
}
/**
* @param PHP_CodeCoverage $coverage
* @param bool $showColors
* @return string
*/
public function process(PHP_CodeCoverage $coverage, $showColors = false)
{
$output = PHP_EOL . PHP_EOL;
$report = $coverage->getReport();
unset($coverage);
$colors = array(
'header' => '',
'classes' => '',
'methods' => '',
'lines' => '',
'reset' => '',
'eol' => ''
);
if ($showColors) {
$colors['classes'] = $this->getCoverageColor(
$report->getNumTestedClassesAndTraits(),
$report->getNumClassesAndTraits()
);
$colors['methods'] = $this->getCoverageColor(
$report->getNumTestedMethods(),
$report->getNumMethods()
);
$colors['lines'] = $this->getCoverageColor(
$report->getNumExecutedLines(),
$report->getNumExecutableLines()
);
$colors['reset'] = $this->colors['reset'];
$colors['header'] = $this->colors['header'];
$colors['eol'] = $this->colors['eol'];
}
$classes = sprintf(
' Classes: %6s (%d/%d)',
PHP_CodeCoverage_Util::percent(
$report->getNumTestedClassesAndTraits(),
$report->getNumClassesAndTraits(),
true
),
$report->getNumTestedClassesAndTraits(),
$report->getNumClassesAndTraits()
);
$methods = sprintf(
' Methods: %6s (%d/%d)',
PHP_CodeCoverage_Util::percent(
$report->getNumTestedMethods(),
$report->getNumMethods(),
true
),
$report->getNumTestedMethods(),
$report->getNumMethods()
);
$lines = sprintf(
' Lines: %6s (%d/%d)',
PHP_CodeCoverage_Util::percent(
$report->getNumExecutedLines(),
$report->getNumExecutableLines(),
true
),
$report->getNumExecutedLines(),
$report->getNumExecutableLines()
);
$padding = max(array_map('strlen', array($classes, $methods, $lines)));
if ($this->showOnlySummary) {
$title = 'Code Coverage Report Summary:';
$padding = max($padding, strlen($title));
$output .= $this->format($colors['header'], $padding, $title);
} else {
$date = date(' Y-m-d H:i:s', $_SERVER['REQUEST_TIME']);
$title = 'Code Coverage Report:';
$output .= $this->format($colors['header'], $padding, $title);
$output .= $this->format($colors['header'], $padding, $date);
$output .= $this->format($colors['header'], $padding, '');
$output .= $this->format($colors['header'], $padding, ' Summary:');
}
$output .= $this->format($colors['classes'], $padding, $classes);
$output .= $this->format($colors['methods'], $padding, $methods);
$output .= $this->format($colors['lines'], $padding, $lines);
if ($this->showOnlySummary) {
return $output . PHP_EOL;
}
$classCoverage = array();
foreach ($report as $item) {
if (!$item instanceof PHP_CodeCoverage_Report_Node_File) {
continue;
}
$classes = $item->getClassesAndTraits();
foreach ($classes as $className => $class) {
$classStatements = 0;
$coveredClassStatements = 0;
$coveredMethods = 0;
$classMethods = 0;
foreach ($class['methods'] as $method) {
if ($method['executableLines'] == 0) {
continue;
}
$classMethods++;
$classStatements += $method['executableLines'];
$coveredClassStatements += $method['executedLines'];
if ($method['coverage'] == 100) {
$coveredMethods++;
}
}
if (!empty($class['package']['namespace'])) {
$namespace = '\\' . $class['package']['namespace'] . '::';
} elseif (!empty($class['package']['fullPackage'])) {
$namespace = '@' . $class['package']['fullPackage'] . '::';
} else {
$namespace = '';
}
$classCoverage[$namespace . $className] = array(
'namespace' => $namespace,
'className ' => $className,
'methodsCovered' => $coveredMethods,
'methodCount' => $classMethods,
'statementsCovered' => $coveredClassStatements,
'statementCount' => $classStatements,
);
}
}
ksort($classCoverage);
$methodColor = '';
$linesColor = '';
$resetColor = '';
foreach ($classCoverage as $fullQualifiedPath => $classInfo) {
if ($classInfo['statementsCovered'] != 0 ||
$this->showUncoveredFiles) {
if ($showColors) {
$methodColor = $this->getCoverageColor($classInfo['methodsCovered'], $classInfo['methodCount']);
$linesColor = $this->getCoverageColor($classInfo['statementsCovered'], $classInfo['statementCount']);
$resetColor = $colors['reset'];
}
$output .= PHP_EOL . $fullQualifiedPath . PHP_EOL
. ' ' . $methodColor . 'Methods: ' . $this->printCoverageCounts($classInfo['methodsCovered'], $classInfo['methodCount'], 2) . $resetColor . ' '
. ' ' . $linesColor . 'Lines: ' . $this->printCoverageCounts($classInfo['statementsCovered'], $classInfo['statementCount'], 3) . $resetColor
;
}
}
return $output . PHP_EOL;
}
protected function getCoverageColor($numberOfCoveredElements, $totalNumberOfElements)
{
$coverage = PHP_CodeCoverage_Util::percent(
$numberOfCoveredElements,
$totalNumberOfElements
);
if ($coverage >= $this->highLowerBound) {
return $this->colors['green'];
} elseif ($coverage > $this->lowUpperBound) {
return $this->colors['yellow'];
}
return $this->colors['red'];
}
protected function printCoverageCounts($numberOfCoveredElements, $totalNumberOfElements, $presicion)
{
$format = '%' . $presicion . 's';
return PHP_CodeCoverage_Util::percent(
$numberOfCoveredElements,
$totalNumberOfElements,
true,
true
) .
' (' . sprintf($format, $numberOfCoveredElements) . '/' .
sprintf($format, $totalNumberOfElements) . ')';
}
private function format($color, $padding, $string)
{
$reset = $color ? $this->colors['reset'] : '';
return $color . str_pad($string, $padding) . $reset . PHP_EOL;
}
}
| {
"content_hash": "9d984e493d75e1335c09f7a065c84aca",
"timestamp": "",
"source": "github",
"line_count": 239,
"max_line_length": 164,
"avg_line_length": 34.82426778242678,
"alnum_prop": 0.4928511354079058,
"repo_name": "StephaneTrebel/iadv",
"id": "72b7a71c072615aa5042cd01e32888f607001842",
"size": "8565",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "vendor/phpunit/php-code-coverage/src/CodeCoverage/Report/Text.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "85"
},
{
"name": "Cucumber",
"bytes": "400"
},
{
"name": "PHP",
"bytes": "18850"
},
{
"name": "Shell",
"bytes": "41"
}
],
"symlink_target": ""
} |
#pragma once
#include <aws/guardduty/GuardDuty_EXPORTS.h>
#include <aws/guardduty/model/PermissionConfiguration.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace GuardDuty
{
namespace Model
{
/**
* <p>Describes the public access policies that apply to the S3
* bucket.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/guardduty-2017-11-28/PublicAccess">AWS
* API Reference</a></p>
*/
class AWS_GUARDDUTY_API PublicAccess
{
public:
PublicAccess();
PublicAccess(Aws::Utils::Json::JsonView jsonValue);
PublicAccess& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>Contains information about how permissions are configured for the S3
* bucket.</p>
*/
inline const PermissionConfiguration& GetPermissionConfiguration() const{ return m_permissionConfiguration; }
/**
* <p>Contains information about how permissions are configured for the S3
* bucket.</p>
*/
inline bool PermissionConfigurationHasBeenSet() const { return m_permissionConfigurationHasBeenSet; }
/**
* <p>Contains information about how permissions are configured for the S3
* bucket.</p>
*/
inline void SetPermissionConfiguration(const PermissionConfiguration& value) { m_permissionConfigurationHasBeenSet = true; m_permissionConfiguration = value; }
/**
* <p>Contains information about how permissions are configured for the S3
* bucket.</p>
*/
inline void SetPermissionConfiguration(PermissionConfiguration&& value) { m_permissionConfigurationHasBeenSet = true; m_permissionConfiguration = std::move(value); }
/**
* <p>Contains information about how permissions are configured for the S3
* bucket.</p>
*/
inline PublicAccess& WithPermissionConfiguration(const PermissionConfiguration& value) { SetPermissionConfiguration(value); return *this;}
/**
* <p>Contains information about how permissions are configured for the S3
* bucket.</p>
*/
inline PublicAccess& WithPermissionConfiguration(PermissionConfiguration&& value) { SetPermissionConfiguration(std::move(value)); return *this;}
/**
* <p>Describes the effective permission on this bucket after factoring all
* attached policies.</p>
*/
inline const Aws::String& GetEffectivePermission() const{ return m_effectivePermission; }
/**
* <p>Describes the effective permission on this bucket after factoring all
* attached policies.</p>
*/
inline bool EffectivePermissionHasBeenSet() const { return m_effectivePermissionHasBeenSet; }
/**
* <p>Describes the effective permission on this bucket after factoring all
* attached policies.</p>
*/
inline void SetEffectivePermission(const Aws::String& value) { m_effectivePermissionHasBeenSet = true; m_effectivePermission = value; }
/**
* <p>Describes the effective permission on this bucket after factoring all
* attached policies.</p>
*/
inline void SetEffectivePermission(Aws::String&& value) { m_effectivePermissionHasBeenSet = true; m_effectivePermission = std::move(value); }
/**
* <p>Describes the effective permission on this bucket after factoring all
* attached policies.</p>
*/
inline void SetEffectivePermission(const char* value) { m_effectivePermissionHasBeenSet = true; m_effectivePermission.assign(value); }
/**
* <p>Describes the effective permission on this bucket after factoring all
* attached policies.</p>
*/
inline PublicAccess& WithEffectivePermission(const Aws::String& value) { SetEffectivePermission(value); return *this;}
/**
* <p>Describes the effective permission on this bucket after factoring all
* attached policies.</p>
*/
inline PublicAccess& WithEffectivePermission(Aws::String&& value) { SetEffectivePermission(std::move(value)); return *this;}
/**
* <p>Describes the effective permission on this bucket after factoring all
* attached policies.</p>
*/
inline PublicAccess& WithEffectivePermission(const char* value) { SetEffectivePermission(value); return *this;}
private:
PermissionConfiguration m_permissionConfiguration;
bool m_permissionConfigurationHasBeenSet;
Aws::String m_effectivePermission;
bool m_effectivePermissionHasBeenSet;
};
} // namespace Model
} // namespace GuardDuty
} // namespace Aws
| {
"content_hash": "1d51cc4c2f8309aacd7cf65e1fe98bb9",
"timestamp": "",
"source": "github",
"line_count": 135,
"max_line_length": 169,
"avg_line_length": 34.407407407407405,
"alnum_prop": 0.7080731969860065,
"repo_name": "awslabs/aws-sdk-cpp",
"id": "0295a68b62a080455783c067d109e06f39352f76",
"size": "4764",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "aws-cpp-sdk-guardduty/include/aws/guardduty/model/PublicAccess.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "7596"
},
{
"name": "C++",
"bytes": "61740540"
},
{
"name": "CMake",
"bytes": "337520"
},
{
"name": "Java",
"bytes": "223122"
},
{
"name": "Python",
"bytes": "47357"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
NUB Generator [autonym]
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "fd311f47c71f5fafb8d5ec85a635ee31",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 23,
"avg_line_length": 9.076923076923077,
"alnum_prop": 0.6779661016949152,
"repo_name": "mdoering/backbone",
"id": "8343ea579899155368ba870b3de656e81c0cf2e1",
"size": "172",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Laurales/Lauraceae/Nectandra/Nectandra villosa/Nectandra villosa villosa/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
The calculator can be checked [here](https://codepen.io/rkpattnaik780/full/QgLMJa/) | {
"content_hash": "d4231c71ffa80a998504feb332ebb890",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 83,
"avg_line_length": 83,
"alnum_prop": 0.7951807228915663,
"repo_name": "vansjyo/Hacktoberfest-2k17",
"id": "55ca77853da721dc33cc3b42733c9a34508496a3",
"size": "147",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "GUI_Calculator/rkpattnaik780/README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "111337"
},
{
"name": "C#",
"bytes": "845"
},
{
"name": "C++",
"bytes": "20350"
},
{
"name": "CSS",
"bytes": "1069"
},
{
"name": "HTML",
"bytes": "31211"
},
{
"name": "Java",
"bytes": "17497"
},
{
"name": "JavaScript",
"bytes": "2507"
},
{
"name": "Lua",
"bytes": "394"
},
{
"name": "PHP",
"bytes": "1042"
},
{
"name": "Pascal",
"bytes": "166"
},
{
"name": "Perl",
"bytes": "579"
},
{
"name": "Python",
"bytes": "25962"
},
{
"name": "Ruby",
"bytes": "60"
},
{
"name": "VHDL",
"bytes": "1542"
}
],
"symlink_target": ""
} |
using System;
using NUnit.Framework.Internal;
namespace NUnit.Framework.Constraints
{
public abstract class ConstraintTestBaseNoData
{
protected Constraint TheConstraint;
protected string ExpectedDescription = "<NOT SET>";
protected string StringRepresentation = "<NOT SET>";
[Test]
public void ProvidesProperDescription()
{
Assert.That(TheConstraint.Description, Is.EqualTo(ExpectedDescription));
}
[Test]
public void ProvidesProperStringRepresentation()
{
Assert.That(TheConstraint.ToString(), Is.EqualTo(StringRepresentation));
}
}
public abstract class ConstraintTestBase : ConstraintTestBaseNoData
{
[Test, TestCaseSource("SuccessData")]
public void SucceedsWithGoodValues(object value)
{
var constraintResult = TheConstraint.ApplyTo(value);
if (!constraintResult.IsSuccess)
{
MessageWriter writer = new TextMessageWriter();
constraintResult.WriteMessageTo(writer);
Assert.Fail(writer.ToString());
}
}
[Test, TestCaseSource("FailureData")]
public void FailsWithBadValues(object badValue, string message)
{
string NL = Environment.NewLine;
var constraintResult = TheConstraint.ApplyTo(badValue);
Assert.IsFalse(constraintResult.IsSuccess);
TextMessageWriter writer = new TextMessageWriter();
constraintResult.WriteMessageTo(writer);
Assert.That( writer.ToString(), Is.EqualTo(
TextMessageWriter.Pfx_Expected + ExpectedDescription + NL +
TextMessageWriter.Pfx_Actual + message + NL ));
}
}
}
| {
"content_hash": "6312afa30b111669297f3fa885690ec4",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 84,
"avg_line_length": 33.370370370370374,
"alnum_prop": 0.6276359600443951,
"repo_name": "JustinRChou/nunit",
"id": "bbcddc6167394fe3ef69c22c456e96f6ea34da90",
"size": "3081",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/NUnitFramework/tests/Constraints/ConstraintTestBase.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "48"
},
{
"name": "C#",
"bytes": "4737405"
},
{
"name": "PowerShell",
"bytes": "8019"
},
{
"name": "Shell",
"bytes": "3249"
},
{
"name": "Visual Basic",
"bytes": "1681"
}
],
"symlink_target": ""
} |
package com.adobe.internal.fxg.dom;
import com.adobe.fxg.dom.FXGNode;
/**
* A marker interface to denote that an FXG node represents a type of transform.
*/
public interface TransformNode extends FXGNode
{
/**
* An id attribute provides a well defined name to a transform node.
* @return the node id.
*/
public String getId();
/**
* Sets the node id.
* @param value - the node id as a String.
*/
public void setId(String value);
}
| {
"content_hash": "87645d354489c8bfa087d3fb16240563",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 81,
"avg_line_length": 21.08695652173913,
"alnum_prop": 0.6453608247422681,
"repo_name": "adufilie/flex-sdk",
"id": "797036fb4009b5e5b2be89ae7d147039828b16c1",
"size": "1304",
"binary": false,
"copies": "6",
"ref": "refs/heads/develop",
"path": "modules/fxgutils/src/java/com/adobe/internal/fxg/dom/TransformNode.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AGS Script",
"bytes": "478"
},
{
"name": "ASP",
"bytes": "6381"
},
{
"name": "ActionScript",
"bytes": "34995123"
},
{
"name": "Awk",
"bytes": "1958"
},
{
"name": "Batchfile",
"bytes": "40336"
},
{
"name": "C",
"bytes": "4601"
},
{
"name": "C++",
"bytes": "10259"
},
{
"name": "CSS",
"bytes": "508448"
},
{
"name": "Groff",
"bytes": "59633"
},
{
"name": "HTML",
"bytes": "84174"
},
{
"name": "Java",
"bytes": "15072764"
},
{
"name": "JavaScript",
"bytes": "110516"
},
{
"name": "PureBasic",
"bytes": "362"
},
{
"name": "Shell",
"bytes": "306455"
},
{
"name": "Visual Basic",
"bytes": "4498"
},
{
"name": "XSLT",
"bytes": "757371"
}
],
"symlink_target": ""
} |
<!doctype html>
<html>
<head>
<link rel="shortcut icon" href="static/images/favicon.ico" type="image/x-icon">
<title>Separator (Closure Library API Documentation - JavaScript)</title>
<link rel="stylesheet" href="static/css/base.css">
<link rel="stylesheet" href="static/css/doc.css">
<link rel="stylesheet" href="static/css/sidetree.css">
<link rel="stylesheet" href="static/css/prettify.css">
<script>
var _staticFilePath = "static/";
</script>
<script src="static/js/doc.js">
</script>
<meta charset="utf8">
</head>
<body onload="prettyPrint()">
<div id="header">
<div class="g-section g-tpl-50-50 g-split">
<div class="g-unit g-first">
<a id="logo" href="index.html">Closure Library API Documentation</a>
</div>
<div class="g-unit">
<div class="g-c">
<strong>Go to class or file:</strong>
<input type="text" id="ac">
</div>
</div>
</div>
</div>
<div class="colmask rightmenu">
<div class="colleft">
<div class="col1">
<!-- Column 1 start -->
<div id="title">
<span class="fn">ui.Separator</span>
<span>Extends</span>
<span class="fn-name">
<a href="class_goog_ui_Control.html">
goog.ui.Control</a>
</span>
</div>
<div class="g-section g-tpl-75-25">
<div class="g-unit g-first" id="description">
Class representing a separator. Although it extends goog.ui.Control,
the Separator class doesn't allocate any event handlers, nor does it change
its appearance on mouseover, etc.
</div>
<div class="g-unit" id="useful-links">
<div class="title">Useful links</div>
<ol>
<li><a href="closure_goog_ui_separator.js.source.html"><span class='source-code-link'>Source Code</span></a></li>
</ol>
</div>
</div>
<h2 class="g-first">Inheritance</h2>
<pre class="inheritance">
Object
<img src="static/images/inherit.gif"><span class="type"><a href="class_goog_Disposable.html">goog.Disposable</a></span>
<img src="static/images/inherit.gif"><span class="type"><a href="class_goog_events_EventTarget.html">goog.events.EventTarget</a></span>
<img src="static/images/inherit.gif"><span class="type"><a href="class_goog_ui_Component.html">goog.ui.Component</a></span>
<img src="static/images/inherit.gif"><span class="type"><a href="class_goog_ui_Control.html">goog.ui.Control</a></span>
<img src="static/images/inherit.gif">goog.ui.Separator
</pre>
<h2>Constructor</h2>
<div class="fn-constructor">
goog.ui.Separator(<span><span class="arg">opt_renderer</span>, <span class="arg">opt_domHelper</span></span>)
</div>
<h3>Parameters</h3>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">opt_renderer</span>
: <div class="fullType"><span class="type"><a href="class_goog_ui_MenuSeparatorRenderer.html">goog.ui.MenuSeparatorRenderer</a></span></div>
<div class="entryOverview">Renderer to render or decorate the separator; defaults to goog.ui.MenuSeparatorRenderer.</div>
</td>
</tr>
<tr class="odd">
<td>
<span class="entryName">opt_domHelper</span>
: <div class="fullType"><span class="type"><a href="class_goog_dom_DomHelper.html">goog.dom.DomHelper</a></span></div>
<div class="entryOverview">Optional DOM helper, used for document interaction.</div>
</td>
</tr>
</table>
<h2>Instance Methods</h2>
<div class="legend">
<span class="key publickey"></span><span>Public</span>
<span class="key protectedkey"></span><span>Protected</span>
<span class="key privatekey"></span><span>Private</span>
</div>
<div>
<div class="desc">
Defined in
<span class="fn-name">
<a href="class_goog_ui_Separator.html">
goog.ui.Separator
</a>
</span>
</div>
<div class="section">
<table class="horiz-rule">
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Separator.prototype.enterDocument"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">enterDocument<span class="args">()</span>
</span>
</div>
<div class="entryOverview">
<span class='nodesc'>No description.</span>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_separator.js.source.html#line61">code »</a>
</td>
</tr>
</table>
</div>
</div>
<div>
<div class="desc">
Defined in
<span class="fn-name">
<a href="class_goog_ui_Control.html">
goog.ui.Control
</a>
</span>
</div>
<div class="section">
<table class="horiz-rule">
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.addClassName"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">addClassName<span class="args">(<span class="arg">className</span>)</span>
</span>
</div>
<div class="entryOverview">
Adds the given class name to the list of classes to be applied to the
component's root element.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">className</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String">string</a></span></div>
<div class="entryOverview">Additional class name to be applied to the component's root element.</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line348">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.canDecorate"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">canDecorate<span class="args">(<span class="arg">element</span>)</span>
</span>
⇒ <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
</div>
<div class="entryOverview">
Returns true if the given element can be decorated by this component.
Overrides goog.ui.Component#canDecorate.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">element</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/DOM/Element">Element</a></span></div>
<div class="entryOverview">Element to decorate.</div>
</td>
</tr>
</table>
</div>
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
Whether the element can be decorated by this component.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line443">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.createDom"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">createDom<span class="args">()</span>
</span>
</div>
<div class="entryOverview">
Creates the control's DOM. Overrides goog.ui.Component#createDom by
delegating DOM manipulation to the control's renderer.
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line402">code »</a>
</td>
</tr>
<tr class="odd entry protected">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.decorateInternal"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">decorateInternal<span class="args">(<span class="arg">element</span>)</span>
</span>
</div>
<div class="entryOverview">
Decorates the given element with this component. Overrides {@link
goog.ui.Component#decorateInternal} by delegating DOM manipulation
to the control's renderer.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">element</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/DOM/Element">Element</a></span></div>
<div class="entryOverview">Element to decorate.</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line457">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.disposeInternal"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">disposeInternal<span class="args">()</span>
</span>
</div>
<div class="entryOverview">
<span class='nodesc'>No description.</span>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line572">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.enableClassName"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">enableClassName<span class="args">(<span class="arg">className</span>, <span class="arg">enable</span>)</span>
</span>
</div>
<div class="entryOverview">
Adds or removes the given class name to/from the list of classes to be
applied to the component's root element.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">className</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String">string</a></span></div>
<div class="entryOverview">CSS class name to add or remove.</div>
</td>
</tr>
<tr class="odd">
<td>
<span class="entryName">enable</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
<div class="entryOverview">Whether to add or remove the class name.</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line385">code »</a>
</td>
</tr>
<tr class="even entry private">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.enableMouseEventHandling_"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">enableMouseEventHandling_<span class="args">(<span class="arg">enable</span>)</span>
</span>
</div>
<div class="entryOverview">
Enables or disables mouse event handling on the control.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">enable</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
<div class="entryOverview">Whether to enable mouse event handling.</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line524">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.enterDocument"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">enterDocument<span class="args">()</span>
</span>
</div>
<div class="entryOverview">
Configures the component after its DOM has been rendered, and sets up event
handling. Overrides goog.ui.Component#enterDocument.
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line481">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.exitDocument"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">exitDocument<span class="args">()</span>
</span>
</div>
<div class="entryOverview">
Cleans up the component before its DOM is removed from the document, and
removes event handlers. Overrides goog.ui.Component#exitDocument
by making sure that components that are removed from the document aren't
focusable (i.e. have no tab index).
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line560">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.getCaption"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">getCaption<span class="args">()</span>
</span>
⇒ <div class="fullType"><span>?</span><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String">string</a></span></div>
</div>
<div class="entryOverview">
Returns the text caption of the component.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span>?</span><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String">string</a></span></div>
Text caption of the component (null if none).
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line632">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.getContent"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">getContent<span class="args">()</span>
</span>
⇒ <div class="fullType"><span class="type">goog.ui.ControlContent</span></div>
</div>
<div class="entryOverview">
Returns the text caption or DOM structure displayed in the component.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span class="type">goog.ui.ControlContent</span></div>
Text caption or DOM structure comprising the component's contents.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line592">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.getContentElement"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">getContentElement<span class="args">()</span>
</span>
⇒ <div class="fullType"><span>?</span><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/DOM/Element">Element</a></span></div>
</div>
<div class="entryOverview">
Returns the DOM element into which child components are to be rendered,
or null if the control itself hasn't been rendered yet. Overrides
goog.ui.Component#getContentElement by delegating to the renderer.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span>?</span><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/DOM/Element">Element</a></span></div>
Element to contain child elements (null if none).
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line431">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.getExtraClassNames"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">getExtraClassNames<span class="args">()</span>
</span>
⇒ <div class="fullType"><span>?</span><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array">Array</a></span>.<<span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String">string</a></span>></div>
</div>
<div class="entryOverview">
Returns any additional class name(s) to be applied to the component's
root element, or null if no extra class names are needed.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span>?</span><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array">Array</a></span>.<<span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String">string</a></span>></div>
Additional class names to be applied to the component's root element (null if none).
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line337">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.getKeyEventTarget"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">getKeyEventTarget<span class="args">()</span>
</span>
⇒ <div class="fullType"><span>?</span><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/DOM/Element">Element</a></span></div>
</div>
<div class="entryOverview">
Returns the DOM element on which the control is listening for keyboard
events (null if none).
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span>?</span><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/DOM/Element">Element</a></span></div>
Element on which the control is listening for key events.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line276">code »</a>
</td>
</tr>
<tr class="even entry protected">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.getKeyHandler"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">getKeyHandler<span class="args">()</span>
</span>
⇒ <div class="fullType"><span class="type"><a href="class_goog_events_KeyHandler.html">goog.events.KeyHandler</a></span></div>
</div>
<div class="entryOverview">
Returns the keyboard event handler for this component, lazily created the
first time this method is called. Considered protected; should only be
used within this package and by subclasses.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span class="type"><a href="class_goog_events_KeyHandler.html">goog.events.KeyHandler</a></span></div>
Keyboard event handler for this component.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line289">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.getRenderer"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">getRenderer<span class="args">()</span>
</span>
⇒ <div class="fullType"><span class="type"><a href="class_goog_ui_ControlRenderer.html">goog.ui.ControlRenderer</a></span><span> | </span><span class="type">undefined</span></div>
</div>
<div class="entryOverview">
Returns the renderer used by this component to render itself or to decorate
an existing element.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span class="type"><a href="class_goog_ui_ControlRenderer.html">goog.ui.ControlRenderer</a></span><span> | </span><span class="type">undefined</span></div>
Renderer used by the component (undefined if none).
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line300">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.getState"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">getState<span class="args">()</span>
</span>
⇒ <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Number">number</a></span></div>
</div>
<div class="entryOverview">
Returns the component's state as a bit mask of {@link
goog.ui.Component.State}s.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Number">number</a></span></div>
Bit mask representing component state.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line931">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.handleBlur"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">handleBlur<span class="args">(<span class="arg">e</span>)</span>
</span>
</div>
<div class="entryOverview">
Handles blur events on the component's key event target element. Always
deactivates the component. In addition, if the component is focusable,
updates its state and styling to indicate that it no longer has keyboard
focus. Considered protected; should only be used within this package and
by subclasses. <b>Warning:</b> IE dispatches focus and blur events
asynchronously!
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">e</span>
: <div class="fullType"><span class="type"><a href="class_goog_events_Event.html">goog.events.Event</a></span></div>
<div class="entryOverview">Blur event to handle.</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line1269">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.handleDblClick"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">handleDblClick<span class="args">(<span class="arg">e</span>)</span>
</span>
</div>
<div class="entryOverview">
Handles dblclick events. Should only be registered if the user agent is
IE. If the component is enabled, performs its associated action by calling
performActionInternal. This is used to allow more performant
buttons in IE. In IE, no mousedown event is fired when that mousedown will
trigger a dblclick event. Because of this, a user clicking quickly will
only cause ACTION events to fire on every other click. This is a workaround
to generate ACTION events for every click. Unfortunately, this workaround
won't ever trigger the ACTIVE state. This is roughly the same behaviour as
if this were a 'button' element with a listener on mouseup. Considered
protected; should only be used within this package and by subclasses.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">e</span>
: <div class="fullType"><span class="type"><a href="class_goog_events_Event.html">goog.events.Event</a></span></div>
<div class="entryOverview">Mouse event to handle.</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line1206">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.handleFocus"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">handleFocus<span class="args">(<span class="arg">e</span>)</span>
</span>
</div>
<div class="entryOverview">
Handles focus events on the component's key event target element. If the
component is focusable, updates its state and styling to indicate that it
now has keyboard focus. Considered protected; should only be used within
this package and by subclasses. <b>Warning:</b> IE dispatches focus and
blur events asynchronously!
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">e</span>
: <div class="fullType"><span class="type"><a href="class_goog_events_Event.html">goog.events.Event</a></span></div>
<div class="entryOverview">Focus event to handle.</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line1253">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.handleKeyEvent"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">handleKeyEvent<span class="args">(<span class="arg">e</span>)</span>
</span>
⇒ <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
</div>
<div class="entryOverview">
Attempts to handle a keyboard event, if the component is enabled and visible,
by calling handleKeyEventInternal. Considered protected; should only
be used within this package and by subclasses.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">e</span>
: <div class="fullType"><span class="type"><a href="class_goog_events_KeyEvent.html">goog.events.KeyEvent</a></span></div>
<div class="entryOverview">Key event to handle.</div>
</td>
</tr>
</table>
</div>
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
Whether the key event was handled.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line1286">code »</a>
</td>
</tr>
<tr class="odd entry protected">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.handleKeyEventInternal"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">handleKeyEventInternal<span class="args">(<span class="arg">e</span>)</span>
</span>
⇒ <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
</div>
<div class="entryOverview">
Attempts to handle a keyboard event; returns true if the event was handled,
false otherwise. Considered protected; should only be used within this
package and by subclasses.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">e</span>
: <div class="fullType"><span class="type"><a href="class_goog_events_KeyEvent.html">goog.events.KeyEvent</a></span></div>
<div class="entryOverview">Key event to handle.</div>
</td>
</tr>
</table>
</div>
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
Whether the key event was handled.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line1305">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.handleMouseDown"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">handleMouseDown<span class="args">(<span class="arg">e</span>)</span>
</span>
</div>
<div class="entryOverview">
Handles mousedown events. If the component is enabled, highlights and
activates it. If the component isn't configured for keyboard access,
prevents it from receiving keyboard focus. Considered protected; should
only be used within this package andy by subclasses.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">e</span>
: <div class="fullType"><span class="type"><a href="class_goog_events_Event.html">goog.events.Event</a></span></div>
<div class="entryOverview">Mouse event to handle.</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line1145">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.handleMouseOut"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">handleMouseOut<span class="args">(<span class="arg">e</span>)</span>
</span>
</div>
<div class="entryOverview">
Handles mouseout events. Dispatches a LEAVE event; if the event isn't
canceled, and the component supports auto-highlighting, deactivates and
un-highlights the component. Considered protected; should only be used
within this package and by subclasses.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">e</span>
: <div class="fullType"><span class="type"><a href="class_goog_events_BrowserEvent.html">goog.events.BrowserEvent</a></span></div>
<div class="entryOverview">Mouse event to handle.</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line1122">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.handleMouseOver"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">handleMouseOver<span class="args">(<span class="arg">e</span>)</span>
</span>
</div>
<div class="entryOverview">
Handles mouseover events. Dispatches an ENTER event; if the event isn't
canceled, the component is enabled, and it supports auto-highlighting,
highlights the component. Considered protected; should only be used
within this package and by subclasses.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">e</span>
: <div class="fullType"><span class="type"><a href="class_goog_events_BrowserEvent.html">goog.events.BrowserEvent</a></span></div>
<div class="entryOverview">Mouse event to handle.</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line1103">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.handleMouseUp"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">handleMouseUp<span class="args">(<span class="arg">e</span>)</span>
</span>
</div>
<div class="entryOverview">
Handles mouseup events. If the component is enabled, highlights it. If
the component has previously been activated, performs its associated action
by calling performActionInternal, then deactivates it. Considered
protected; should only be used within this package and by subclasses.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">e</span>
: <div class="fullType"><span class="type"><a href="class_goog_events_Event.html">goog.events.Event</a></span></div>
<div class="entryOverview">Mouse event to handle.</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line1179">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.hasState"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">hasState<span class="args">(<span class="arg">state</span>)</span>
</span>
⇒ <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
</div>
<div class="entryOverview">
Returns true if the component is in the specified state, false otherwise.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">state</span>
: <div class="fullType"><span class="type">goog.ui.Component.State</span></div>
<div class="entryOverview">State to check.</div>
</td>
</tr>
</table>
</div>
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
Whether the component is in the given state.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line941">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.isActive"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">isActive<span class="args">()</span>
</span>
⇒ <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
</div>
<div class="entryOverview">
Returns true if the component is active (pressed), false otherwise.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
Whether the component is active.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line812">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.isAllowTextSelection"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">isAllowTextSelection<span class="args">()</span>
</span>
⇒ <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
</div>
<div class="entryOverview">
Returns true if the control allows text selection within its DOM, false
otherwise. Controls that disallow text selection have the appropriate
unselectable styling applied to their elements. Note that controls hosted
in containers will report that they allow text selection even if their
container disallows text selection.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
Whether the control allows text selection.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line677">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.isAutoState"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">isAutoState<span class="args">(<span class="arg">state</span>)</span>
</span>
⇒ <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
</div>
<div class="entryOverview">
Returns true if the component provides default event handling for the state,
false otherwise.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">state</span>
: <div class="fullType"><span class="type">goog.ui.Component.State</span></div>
<div class="entryOverview">State to check.</div>
</td>
</tr>
</table>
</div>
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
Whether the component provides default event handling for the state.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line1017">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.isChecked"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">isChecked<span class="args">()</span>
</span>
⇒ <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
</div>
<div class="entryOverview">
Returns true if the component is checked, false otherwise.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
Whether the component is checked.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line856">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.isDispatchTransitionEvents"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">isDispatchTransitionEvents<span class="args">(<span class="arg">state</span>)</span>
</span>
⇒ <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
</div>
<div class="entryOverview">
Returns true if the component is set to dispatch transition events for the
given state, false otherwise.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">state</span>
: <div class="fullType"><span class="type">goog.ui.Component.State</span></div>
<div class="entryOverview">State to check.</div>
</td>
</tr>
</table>
</div>
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
Whether the component dispatches transition events for the state.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line1042">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.isEnabled"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">isEnabled<span class="args">()</span>
</span>
⇒ <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
</div>
<div class="entryOverview">
Returns true if the component is enabled, false otherwise.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
Whether the component is enabled.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line742">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.isFocused"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">isFocused<span class="args">()</span>
</span>
⇒ <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
</div>
<div class="entryOverview">
Returns true if the component is styled to indicate that it has keyboard
focus, false otherwise. Note that <code>isFocused()</code> returning true
doesn't guarantee that the component's key event target has keyborad focus,
only that it is styled as such.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
Whether the component is styled to indicate as having keyboard focus.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line882">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.isHandleMouseEvents"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">isHandleMouseEvents<span class="args">()</span>
</span>
⇒ <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
</div>
<div class="entryOverview">
Returns true if the control is configured to handle its own mouse events,
false otherwise. Controls not hosted in goog.ui.Containers have
to handle their own mouse events, but controls hosted in containers may
allow their parent to handle mouse events on their behalf. Considered
protected; should only be used within this package and by subclasses.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
Whether the control handles its own mouse events.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line249">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.isHighlighted"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">isHighlighted<span class="args">()</span>
</span>
⇒ <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
</div>
<div class="entryOverview">
Returns true if the component is currently highlighted, false otherwise.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
Whether the component is highlighted.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line790">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.isOpen"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">isOpen<span class="args">()</span>
</span>
⇒ <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
</div>
<div class="entryOverview">
Returns true if the component is open (expanded), false otherwise.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
Whether the component is open.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line908">code »</a>
</td>
</tr>
<tr class="odd entry private">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.isParentDisabled_"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">isParentDisabled_<span class="args">()</span>
</span>
⇒ <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
</div>
<div class="entryOverview">
Returns true if the control has a parent that is itself disabled, false
otherwise.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
Whether the component is hosted in a disabled container.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line753">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.isSelected"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">isSelected<span class="args">()</span>
</span>
⇒ <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
</div>
<div class="entryOverview">
Returns true if the component is selected, false otherwise.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
Whether the component is selected.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line834">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.isSupportedState"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">isSupportedState<span class="args">(<span class="arg">state</span>)</span>
</span>
⇒ <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
</div>
<div class="entryOverview">
Returns true if the component supports the specified state, false otherwise.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">state</span>
: <div class="fullType"><span class="type">goog.ui.Component.State</span></div>
<div class="entryOverview">State to check.</div>
</td>
</tr>
</table>
</div>
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
Whether the component supports the given state.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line982">code »</a>
</td>
</tr>
<tr class="even entry protected">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.isTransitionAllowed"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">isTransitionAllowed<span class="args">(<span class="arg">state</span>, <span class="arg">enable</span>)</span>
</span>
⇒ <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
</div>
<div class="entryOverview">
Returns true if the transition into or out of the given state is allowed to
proceed, false otherwise. A state transition is allowed under the following
conditions:
<ul>
<li>the component supports the state,
<li>the component isn't already in the target state,
<li>either the component is configured not to dispatch events for this
state transition, or a transition event was dispatched and wasn't
canceled by any event listener, and
<li>the component hasn't been disposed of
</li></li></li></li></ul>
Considered protected; should only be used within this package and by
subclasses.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">state</span>
: <div class="fullType"><span class="type">goog.ui.Component.State</span></div>
<div class="entryOverview">State to/from which the control is transitioning.</div>
</td>
</tr>
<tr class="odd">
<td>
<span class="entryName">enable</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
<div class="entryOverview">Whether the control is entering or leaving the state.</div>
</td>
</tr>
</table>
</div>
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
Whether the state transition is allowed to proceed.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line1084">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.isVisible"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">isVisible<span class="args">()</span>
</span>
⇒ <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
</div>
<div class="entryOverview">
Returns true if the component's visibility is set to visible, false if
it is set to hidden. A component that is set to hidden is guaranteed
to be hidden from the user, but the reverse isn't necessarily true.
A component may be set to visible but can otherwise be obscured by another
element, rendered off-screen, or hidden using direct CSS manipulation.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
Whether the component is visible.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line704">code »</a>
</td>
</tr>
<tr class="even entry protected">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.performActionInternal"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">performActionInternal<span class="args">(<span class="arg">e</span>)</span>
</span>
⇒ <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
</div>
<div class="entryOverview">
Performs the appropriate action when the control is activated by the user.
The default implementation first updates the checked and selected state of
controls that support them, then dispatches an ACTION event. Considered
protected; should only be used within this package and by subclasses.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">e</span>
: <div class="fullType"><span class="type"><a href="class_goog_events_Event.html">goog.events.Event</a></span></div>
<div class="entryOverview">Event that triggered the action.</div>
</td>
</tr>
</table>
</div>
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
Whether the action is allowed to proceed.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line1222">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.removeClassName"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">removeClassName<span class="args">(<span class="arg">className</span>)</span>
</span>
</div>
<div class="entryOverview">
Removes the given class name from the list of classes to be applied to
the component's root element.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">className</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String">string</a></span></div>
<div class="entryOverview">Class name to be removed from the component's root element.</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line368">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.setActive"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">setActive<span class="args">(<span class="arg">active</span>)</span>
</span>
</div>
<div class="entryOverview">
Activates or deactivates the component. Does nothing if this state
transition is disallowed.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">active</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
<div class="entryOverview">Whether to activate or deactivate the component.</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line823">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.setAllowTextSelection"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">setAllowTextSelection<span class="args">(<span class="arg">allow</span>)</span>
</span>
</div>
<div class="entryOverview">
Allows or disallows text selection within the control's DOM.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">allow</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
<div class="entryOverview">Whether the control should allow text selection.</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line686">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.setAutoStates"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">setAutoStates<span class="args">(<span class="arg">states</span>, <span class="arg">enable</span>)</span>
</span>
</div>
<div class="entryOverview">
Enables or disables automatic event handling for the given state(s).
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">states</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Number">number</a></span></div>
<div class="entryOverview">Bit mask of goog.ui.Component.States for which default event handling is to be enabled or disabled.</div>
</td>
</tr>
<tr class="odd">
<td>
<span class="entryName">enable</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
<div class="entryOverview">Whether the component should provide default event handling for the state(s).</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line1029">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.setCaption"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">setCaption<span class="args">(<span class="arg">caption</span>)</span>
</span>
</div>
<div class="entryOverview">
Sets the text caption of the component.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">caption</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String">string</a></span></div>
<div class="entryOverview">Text caption of the component (null to clear).</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line649">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.setChecked"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">setChecked<span class="args">(<span class="arg">check</span>)</span>
</span>
</div>
<div class="entryOverview">
Checks or unchecks the component. Does nothing if this state transition
is disallowed.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">check</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
<div class="entryOverview">Whether to check or uncheck the component.</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line867">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.setContent"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">setContent<span class="args">(<span class="arg">content</span>)</span>
</span>
</div>
<div class="entryOverview">
Sets the component's content to the given text caption, element, or array of
nodes. (If the argument is an array of nodes, it must be an actual array,
not an array-like object.)
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">content</span>
: <div class="fullType"><span class="type">goog.ui.ControlContent</span></div>
<div class="entryOverview">Text caption or DOM structure to set as the component's contents.</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line604">code »</a>
</td>
</tr>
<tr class="even entry protected">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.setContentInternal"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">setContentInternal<span class="args">(<span class="arg">content</span>)</span>
</span>
</div>
<div class="entryOverview">
Sets the component's content to the given text caption, element, or array
of nodes. Unlike #setContent, doesn't modify the component's DOM.
Called by renderers during element decoration. Considered protected; should
only be used within this package and by subclasses.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">content</span>
: <div class="fullType"><span class="type">goog.ui.ControlContent</span></div>
<div class="entryOverview">Text caption or DOM structure to set as the component's contents.</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line623">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.setDispatchTransitionEvents"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">setDispatchTransitionEvents<span class="args">(<span class="arg">states</span>, <span class="arg">enable</span>)</span>
</span>
</div>
<div class="entryOverview">
Enables or disables transition events for the given state(s). Controls
handle state transitions internally by default, and only dispatch state
transition events if explicitly requested to do so by calling this mentod.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">states</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Number">number</a></span></div>
<div class="entryOverview">Bit mask of goog.ui.Component.States for which transition events should be enabled or disabled.</div>
</td>
</tr>
<tr class="odd">
<td>
<span class="entryName">enable</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
<div class="entryOverview">Whether transition events should be enabled.</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line1056">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.setEnabled"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">setEnabled<span class="args">(<span class="arg">enable</span>)</span>
</span>
</div>
<div class="entryOverview">
Enables or disables the component. Does nothing if this state transition
is disallowed. If the component is both visible and focusable, updates its
focused state and tab index as needed. If the component is being disabled,
ensures that it is also deactivated and un-highlighted first. Note that the
component's enabled/disabled state is "locked" as long as it is hosted in a
goog.ui.Container that is itself disabled; this is to prevent clients
from accidentally re-enabling a control that is in a disabled container.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">enable</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
<div class="entryOverview">Whether to enable or disable the component.</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line771">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.setFocused"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">setFocused<span class="args">(<span class="arg">focused</span>)</span>
</span>
</div>
<div class="entryOverview">
Applies or removes styling indicating that the component has keyboard focus.
Note that unlike the other "set" methods, this method is called as a result
of the component's element having received or lost keyboard focus, not the
other way around, so calling <code>setFocused(true)</code> doesn't guarantee that
the component's key event target has keyboard focus, only that it is styled
as such.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">focused</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
<div class="entryOverview">Whether to apply or remove styling to indicate that the component's element has keyboard focus.</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line897">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.setHandleMouseEvents"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">setHandleMouseEvents<span class="args">(<span class="arg">enable</span>)</span>
</span>
</div>
<div class="entryOverview">
Enables or disables mouse event handling for the control. Containers may
use this method to disable mouse event handling in their child controls.
Considered protected; should only be used within this package and by
subclasses.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">enable</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
<div class="entryOverview">Whether to enable or disable mouse event handling.</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line261">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.setHighlighted"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">setHighlighted<span class="args">(<span class="arg">highlight</span>)</span>
</span>
</div>
<div class="entryOverview">
Highlights or unhighlights the component. Does nothing if this state
transition is disallowed.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">highlight</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
<div class="entryOverview">Whether to highlight or unhighlight the component.</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line801">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.setOpen"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">setOpen<span class="args">(<span class="arg">open</span>)</span>
</span>
</div>
<div class="entryOverview">
Opens (expands) or closes (collapses) the component. Does nothing if this
state transition is disallowed.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">open</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
<div class="entryOverview">Whether to open or close the component.</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line919">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.setRenderer"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">setRenderer<span class="args">(<span class="arg">renderer</span>)</span>
</span>
</div>
<div class="entryOverview">
Registers the given renderer with the component. Changing renderers after
the component has entered the document is an error.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">renderer</span>
: <div class="fullType"><span class="type"><a href="class_goog_ui_ControlRenderer.html">goog.ui.ControlRenderer</a></span></div>
<div class="entryOverview">Renderer used by the component.</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line311">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.setRightToLeft"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">setRightToLeft<span class="args">(<span class="arg">rightToLeft</span>)</span>
</span>
</div>
<div class="entryOverview">
<span class='nodesc'>No description.</span>
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">rightToLeft</span>
:
<div class="entryOverview"><span class='nodesc'>No description.</span></div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line658">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.setSelected"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">setSelected<span class="args">(<span class="arg">select</span>)</span>
</span>
</div>
<div class="entryOverview">
Selects or unselects the component. Does nothing if this state transition
is disallowed.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">select</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
<div class="entryOverview">Whether to select or unselect the component.</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line845">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.setState"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">setState<span class="args">(<span class="arg">state</span>, <span class="arg">enable</span>)</span>
</span>
</div>
<div class="entryOverview">
Sets or clears the given state on the component, and updates its styling
accordingly. Does nothing if the component is already in the correct state
or if it doesn't support the specified state. Doesn't dispatch any state
transition events; use advisedly.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">state</span>
: <div class="fullType"><span class="type">goog.ui.Component.State</span></div>
<div class="entryOverview">State to set or clear.</div>
</td>
</tr>
<tr class="odd">
<td>
<span class="entryName">enable</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
<div class="entryOverview">Whether to set or clear the state (if supported).</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line954">code »</a>
</td>
</tr>
<tr class="odd entry protected">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.setStateInternal"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">setStateInternal<span class="args">(<span class="arg">state</span>)</span>
</span>
</div>
<div class="entryOverview">
Sets the component's state to the state represented by a bit mask of
goog.ui.Component.States. Unlike #setState, doesn't
update the component's styling, and doesn't reject unsupported states.
Called by renderers during element decoration. Considered protected;
should only be used within this package and by subclasses.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">state</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Number">number</a></span></div>
<div class="entryOverview">Bit mask representing component state.</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line972">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.setSupportedState"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">setSupportedState<span class="args">(<span class="arg">state</span>, <span class="arg">support</span>)</span>
</span>
</div>
<div class="entryOverview">
Enables or disables support for the given state. Disabling support
for a state while the component is in that state is an error.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">state</span>
: <div class="fullType"><span class="type">goog.ui.Component.State</span></div>
<div class="entryOverview">State to support or de-support.</div>
</td>
</tr>
<tr class="odd">
<td>
<span class="entryName">support</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
<div class="entryOverview">Whether the component should support the state.</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line994">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Control.prototype.setVisible"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">setVisible<span class="args">(<span class="arg">visible</span>, <span class="arg">opt_force</span>)</span>
</span>
⇒ <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
</div>
<div class="entryOverview">
Shows or hides the component. Does nothing if the component already has
the requested visibility. Otherwise, dispatches a SHOW or HIDE event as
appropriate, giving listeners a chance to prevent the visibility change.
When showing a component that is both enabled and focusable, ensures that
its key target has a tab index. When hiding a component that is enabled
and focusable, blurs its key target and removes its tab index.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">visible</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
<div class="entryOverview">Whether to show or hide the component.</div>
</td>
</tr>
<tr class="odd">
<td>
<span class="entryName">opt_force</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
<div class="entryOverview">If true, doesn't check whether the component already has the requested visibility, and doesn't dispatch any events.</div>
</td>
</tr>
</table>
</div>
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
Whether the visibility was changed.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line721">code »</a>
</td>
</tr>
</table>
</div>
</div>
<div>
<div class="desc">
Defined in
<span class="fn-name">
<a href="class_goog_ui_Component.html">
goog.ui.Component
</a>
</span>
</div>
<div class="section">
<table class="horiz-rule">
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Component.prototype.addChild"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">addChild<span class="args">(<span class="arg">child</span>, <span class="arg">opt_render</span>)</span>
</span>
</div>
<div class="entryOverview">
Adds the specified component as the last child of this component. See
goog.ui.Component#addChildAt for detailed semantics.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">child</span>
: <div class="fullType"><span class="type"><a href="class_goog_ui_Component.html">goog.ui.Component</a></span></div>
<div class="entryOverview">The new child component.</div>
</td>
</tr>
<tr class="odd">
<td>
<span class="entryName">opt_render</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
<div class="entryOverview">If true, the child component will be rendered into the parent.</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line848">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Component.prototype.addChildAt"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">addChildAt<span class="args">(<span class="arg">child</span>, <span class="arg">index</span>, <span class="arg">opt_render</span>)</span>
</span>
</div>
<div class="entryOverview">
Adds the specified component as a child of this component at the given
0-based index.
Both <code>addChild</code> and <code>addChildAt</code> assume the following contract
between parent and child components:
<ul>
<li>the child component's element must be a descendant of the parent
component's element, and
<li>the DOM state of the child component must be consistent with the DOM
state of the parent component (see <code>isInDocument</code>).
</li></li></ul>
In particular, <code>parent.addChild(child)</code> will throw an error if the
child component is already in the document, but the parent isn't.
Clients of this API may call <code>addChild</code> and <code>addChildAt</code> with
<code>opt_render</code> set to true. If <code>opt_render</code> is true, calling these
methods will automatically render the child component's element into the
parent component's element. However, <code>parent.addChild(child, true)</code>
will throw an error if:
<ul>
<li>the parent component has no DOM (i.e. <code>parent.getElement()</code> is
null), or
<li>the child component is already in the document, regardless of the
parent's DOM state.
</li></li></ul>
Finally, this method also throws an error if the new child already has a
different parent, or the given index is out of bounds.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">child</span>
: <div class="fullType"><span class="type"><a href="class_goog_ui_Component.html">goog.ui.Component</a></span></div>
<div class="entryOverview">The new child component.</div>
</td>
</tr>
<tr class="odd">
<td>
<span class="entryName">index</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Number">number</a></span></div>
<div class="entryOverview">0-based index at which the new child component is to be added; must be between 0 and the current child count (inclusive).</div>
</td>
</tr>
<tr class="even">
<td>
<span class="entryName">opt_render</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
<div class="entryOverview">If true, the child component will be rendered into the parent.</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line891">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Component.prototype.canDecorate"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">canDecorate<span class="args">(<span class="arg">element</span>)</span>
</span>
⇒ <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
</div>
<div class="entryOverview">
Determines if a given element can be decorated by this type of component.
This method should be overridden by inheriting objects.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">element</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/DOM/Element">Element</a></span></div>
<div class="entryOverview">Element to decorate.</div>
</td>
</tr>
</table>
</div>
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
True if the element can be decorated, false otherwise.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line674">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Component.prototype.createDom"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">createDom<span class="args">()</span>
</span>
</div>
<div class="entryOverview">
<span class='nodesc'>No description.</span>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line567">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Component.prototype.decorate"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">decorate<span class="args">(<span class="arg">element</span>)</span>
</span>
</div>
<div class="entryOverview">
Decorates the element for the UI component.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">element</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/DOM/Element">Element</a></span></div>
<div class="entryOverview">Element to decorate.</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line647">code »</a>
</td>
</tr>
<tr class="odd entry protected">
<td class="access"></td>
<td>
<a name="goog.ui.Component.prototype.decorateInternal"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">decorateInternal<span class="args">(<span class="arg">element</span>)</span>
</span>
</div>
<div class="entryOverview">
Actually decorates the element. Should be overridden by inheriting objects.
This method can assume there are checks to ensure the component has not
already been rendered have occurred and that enter document will be called
afterwards. This method is considered protected.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">element</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/DOM/Element">Element</a></span></div>
<div class="entryOverview">Element to decorate.</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line695">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Component.prototype.disposeInternal"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">disposeInternal<span class="args">()</span>
</span>
</div>
<div class="entryOverview">
Disposes of the component. Calls <code>exitDocument</code>, which is expected to
remove event handlers and clean up the component. Propagates the call to
the component's children, if any. Removes the component's DOM from the
document unless it was decorated.
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line753">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Component.prototype.enterDocument"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">enterDocument<span class="args">()</span>
</span>
</div>
<div class="entryOverview">
<span class='nodesc'>No description.</span>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line707">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Component.prototype.exitDocument"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">exitDocument<span class="args">()</span>
</span>
</div>
<div class="entryOverview">
<span class='nodesc'>No description.</span>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line730">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Component.prototype.forEachChild"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">forEachChild<span class="args">(<span class="arg">f</span>, <span class="arg">opt_obj</span>)</span>
</span>
</div>
<div class="entryOverview">
Calls the given function on each of this component's children in order. If
<code>opt_obj</code> is provided, it will be used as the 'this' object in the
function when called. The function should take two arguments: the child
component and its 0-based index. The return value is ignored.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">f</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Function">Function</a></span></div>
<div class="entryOverview">The function to call for every child component; should take 2 arguments (the child and its index).</div>
</td>
</tr>
<tr class="odd">
<td>
<span class="entryName">opt_obj</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Object">Object</a></span></div>
<div class="entryOverview">Used as the 'this' object in f when called.</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line1067">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Component.prototype.getChild"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">getChild<span class="args">(<span class="arg">id</span>)</span>
</span>
⇒ <div class="fullType"><span>?</span><span class="type"><a href="class_goog_ui_Component.html">goog.ui.Component</a></span></div>
</div>
<div class="entryOverview">
Returns the child with the given ID, or null if no such child exists.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">id</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String">string</a></span></div>
<div class="entryOverview">Child component ID.</div>
</td>
</tr>
</table>
</div>
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span>?</span><span class="type"><a href="class_goog_ui_Component.html">goog.ui.Component</a></span></div>
The child with the given ID; null if none.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line1040">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Component.prototype.getChildAt"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">getChildAt<span class="args">(<span class="arg">index</span>)</span>
</span>
⇒ <div class="fullType"><span>?</span><span class="type"><a href="class_goog_ui_Component.html">goog.ui.Component</a></span></div>
</div>
<div class="entryOverview">
Returns the child at the given index, or null if the index is out of bounds.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">index</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Number">number</a></span></div>
<div class="entryOverview">0-based index.</div>
</td>
</tr>
</table>
</div>
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span>?</span><span class="type"><a href="class_goog_ui_Component.html">goog.ui.Component</a></span></div>
The child at the given index; null if none.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line1052">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Component.prototype.getChildCount"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">getChildCount<span class="args">()</span>
</span>
⇒ <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Number">number</a></span></div>
</div>
<div class="entryOverview">
Returns the number of children of this component.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Number">number</a></span></div>
The number of children.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line1011">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Component.prototype.getChildIds"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">getChildIds<span class="args">()</span>
</span>
⇒ <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array">Array</a></span>.<<span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String">string</a></span>></div>
</div>
<div class="entryOverview">
Returns an array containing the IDs of the children of this component, or an
empty array if the component has no children.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array">Array</a></span>.<<span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String">string</a></span>></div>
Child component IDs.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line1021">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Component.prototype.getContentElement"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">getContentElement<span class="args">()</span>
</span>
⇒ <div class="fullType"><span>?</span><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/DOM/Element">Element</a></span></div>
</div>
<div class="entryOverview">
Returns the DOM element into which child components are to be rendered,
or null if the component itself hasn't been rendered yet. This default
implementation returns the component's root element. Subclasses with
complex DOM structures must override this method.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span>?</span><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/DOM/Element">Element</a></span></div>
Element to contain child elements (null if none).
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line963">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Component.prototype.getDomHelper"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">getDomHelper<span class="args">()</span>
</span>
⇒ <div class="fullType"><span class="type"><a href="class_goog_dom_DomHelper.html">goog.dom.DomHelper</a></span></div>
</div>
<div class="entryOverview">
Returns the dom helper that is being used on this component.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span class="type"><a href="class_goog_dom_DomHelper.html">goog.dom.DomHelper</a></span></div>
The dom helper used on this component.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line549">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Component.prototype.getElement"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">getElement<span class="args">()</span>
</span>
⇒ <div class="fullType"><span>?</span><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/DOM/Element">Element</a></span></div>
</div>
<div class="entryOverview">
Gets the component's element.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span>?</span><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/DOM/Element">Element</a></span></div>
The element for the component.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line466">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Component.prototype.getElementByFragment"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">getElementByFragment<span class="args">(<span class="arg">idFragment</span>)</span>
</span>
⇒ <div class="fullType"><span>?</span><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/DOM/Element">Element</a></span></div>
</div>
<div class="entryOverview">
Helper function for returning an element in the document with a unique id
generated using makeId().
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">idFragment</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String">string</a></span></div>
<div class="entryOverview">The partial id.</div>
</td>
</tr>
</table>
</div>
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span>?</span><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/DOM/Element">Element</a></span></div>
The element with the unique id, or null if it cannot be found.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line831">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Component.prototype.getFragmentFromId"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">getFragmentFromId<span class="args">(<span class="arg">id</span>)</span>
</span>
⇒ <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String">string</a></span></div>
</div>
<div class="entryOverview">
Helper function for returning the fragment portion of an id generated using
makeId().
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">id</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String">string</a></span></div>
<div class="entryOverview">Id generated with makeId().</div>
</td>
</tr>
</table>
</div>
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String">string</a></span></div>
Fragment.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line819">code »</a>
</td>
</tr>
<tr class="odd entry protected">
<td class="access"></td>
<td>
<a name="goog.ui.Component.prototype.getHandler"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">getHandler<span class="args">()</span>
</span>
⇒ <div class="fullType"><span>!</span><span class="type"><a href="class_goog_events_EventHandler.html">goog.events.EventHandler</a></span></div>
</div>
<div class="entryOverview">
Returns the event handler for this component, lazily created the first time
this method is called.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span>!</span><span class="type"><a href="class_goog_events_EventHandler.html">goog.events.EventHandler</a></span></div>
Event handler for this component.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line488">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Component.prototype.getId"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">getId<span class="args">()</span>
</span>
⇒ <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String">string</a></span></div>
</div>
<div class="entryOverview">
Gets the unique ID for the instance of this component. If the instance
doesn't already have an ID, generates one on the fly.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String">string</a></span></div>
Unique component ID.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line437">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Component.prototype.getModel"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">getModel<span class="args">()</span>
</span>
⇒ <div class="fullType"><span class="type">*</span></div>
</div>
<div class="entryOverview">
Returns the model associated with the UI component.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span class="type">*</span></div>
The model.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line799">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Component.prototype.getParent"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">getParent<span class="args">()</span>
</span>
⇒ <div class="fullType"><span>?</span><span class="type"><a href="class_goog_ui_Component.html">goog.ui.Component</a></span></div>
</div>
<div class="entryOverview">
Returns the component's parent, if any.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span>?</span><span class="type"><a href="class_goog_ui_Component.html">goog.ui.Component</a></span></div>
The parent component.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line526">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Component.prototype.hasChildren"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">hasChildren<span class="args">()</span>
</span>
⇒ <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
</div>
<div class="entryOverview">
Returns true if the component has children.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
True if the component has children.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line1002">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Component.prototype.indexOfChild"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">indexOfChild<span class="args">(<span class="arg">child</span>)</span>
</span>
⇒ <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Number">number</a></span></div>
</div>
<div class="entryOverview">
Returns the 0-based index of the given child component, or -1 if no such
child is found.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">child</span>
: <div class="fullType"><span>?</span><span class="type"><a href="class_goog_ui_Component.html">goog.ui.Component</a></span></div>
<div class="entryOverview">The child component.</div>
</td>
</tr>
</table>
</div>
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Number">number</a></span></div>
0-based index of the child component; -1 if not found.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line1080">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Component.prototype.isInDocument"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">isInDocument<span class="args">()</span>
</span>
⇒ <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
</div>
<div class="entryOverview">
Determines whether the component has been added to the document.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
TRUE if rendered. Otherwise, FALSE.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line558">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Component.prototype.isRightToLeft"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">isRightToLeft<span class="args">()</span>
</span>
⇒ <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
</div>
<div class="entryOverview">
Returns true if the component is rendered right-to-left, false otherwise.
The first time this function is invoked, the right-to-left rendering property
is set if it has not been already.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
Whether the control is rendered right-to-left.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line974">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Component.prototype.makeId"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">makeId<span class="args">(<span class="arg">idFragment</span>)</span>
</span>
⇒ <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String">string</a></span></div>
</div>
<div class="entryOverview">
Helper function for subclasses that gets a unique id for a given fragment,
this can be used by components to
generate unique string ids for DOM elements
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">idFragment</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String">string</a></span></div>
<div class="entryOverview">A partial id.</div>
</td>
</tr>
</table>
</div>
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String">string</a></span></div>
Unique element id.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line790">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Component.prototype.removeChild"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">removeChild<span class="args">(<span class="arg">child</span>, <span class="arg">opt_unrender</span>)</span>
</span>
⇒ <div class="fullType"><span class="type"><a href="class_goog_ui_Component.html">goog.ui.Component</a></span></div>
</div>
<div class="entryOverview">
Removes the given child from this component, and returns it. Throws an error
if the argument is invalid or if the specified child isn't found in the
parent component. The argument can either be a string (interpreted as the
ID of the child component to remove) or the child component itself.
If <code>opt_unrender</code> is true, calls goog.ui.component#exitDocument
on the removed child, and subsequently detaches the child's DOM from the
document. Otherwise it is the caller's responsibility to clean up the child
component's DOM.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">child</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String">string</a></span><span> | </span><span class="type"><a href="class_goog_ui_Component.html">goog.ui.Component</a></span><span> | </span><span class="type">null</span></div>
<div class="entryOverview">The ID of the child to remove, or the child component itself.</div>
</td>
</tr>
<tr class="odd">
<td>
<span class="entryName">opt_unrender</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
<div class="entryOverview">If true, calls <code>exitDocument</code> on the removed child component, and detaches its DOM from the document.</div>
</td>
</tr>
</table>
</div>
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span class="type"><a href="class_goog_ui_Component.html">goog.ui.Component</a></span></div>
The removed component, if any.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line1104">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Component.prototype.removeChildAt"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">removeChildAt<span class="args">(<span class="arg">index</span>, <span class="arg">opt_unrender</span>)</span>
</span>
⇒ <div class="fullType"><span class="type"><a href="class_goog_ui_Component.html">goog.ui.Component</a></span></div>
</div>
<div class="entryOverview">
Removes the child at the given index from this component, and returns it.
Throws an error if the argument is out of bounds, or if the specified child
isn't found in the parent. See goog.ui.Component#removeChild for
detailed semantics.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">index</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Number">number</a></span></div>
<div class="entryOverview">0-based index of the child to remove.</div>
</td>
</tr>
<tr class="odd">
<td>
<span class="entryName">opt_unrender</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
<div class="entryOverview">If true, calls <code>exitDocument</code> on the removed child component, and detaches its DOM from the document.</div>
</td>
</tr>
</table>
</div>
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span class="type"><a href="class_goog_ui_Component.html">goog.ui.Component</a></span></div>
The removed component, if any.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line1150">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Component.prototype.removeChildren"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">removeChildren<span class="args">(<span class="arg">opt_unrender</span>)</span>
</span>
</div>
<div class="entryOverview">
Removes every child component attached to this one.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">opt_unrender</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
<div class="entryOverview">If true, calls #exitDocument on the removed child components, and detaches their DOM from the document.</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line1163">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Component.prototype.render"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">render<span class="args">(<span class="arg">opt_parentElement</span>)</span>
</span>
</div>
<div class="entryOverview">
Renders the component. If a parent element is supplied, it should already be
in the document and then the component's element will be appended to it. If
there is no optional parent element and the element doesn't have a parentNode
then it will be appended to the document body.
Throws an Error if the component is already rendered.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">opt_parentElement</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/DOM/Element">Element</a></span></div>
<div class="entryOverview">Optional parent element to render the component into.</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line583">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Component.prototype.renderBefore"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">renderBefore<span class="args">(<span class="arg">siblingElement</span>)</span>
</span>
</div>
<div class="entryOverview">
Renders the component before another element. The other element should be in
the document already.
Throws an Error if the component is already rendered.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">siblingElement</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/DOM/Element">Element</a></span></div>
<div class="entryOverview">Element to render the component before.</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line596">code »</a>
</td>
</tr>
<tr class="odd entry private">
<td class="access"></td>
<td>
<a name="goog.ui.Component.prototype.render_"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">render_<span class="args">(<span class="arg">opt_parentElement</span>, <span class="arg">opt_beforeElement</span>)</span>
</span>
</div>
<div class="entryOverview">
Renders the component. If a parent element is supplied, it should already be
in the document and then the component's element will be appended to it. If
there is no optional parent element and the element doesn't have a parentNode
then it will be appended to the document body.
Throws an Error if the component is already rendered.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">opt_parentElement</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/DOM/Element">Element</a></span></div>
<div class="entryOverview">Optional parent element to render the component into.</div>
</td>
</tr>
<tr class="odd">
<td>
<span class="entryName">opt_beforeElement</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/DOM/Element">Element</a></span></div>
<div class="entryOverview">Element before which the component is to be rendered. If left out the node is appended to the parent element.</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line616">code »</a>
</td>
</tr>
<tr class="even entry protected">
<td class="access"></td>
<td>
<a name="goog.ui.Component.prototype.setElementInternal"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">setElementInternal<span class="args">(<span class="arg">element</span>)</span>
</span>
</div>
<div class="entryOverview">
Sets the component's root element to the given element. Considered
protected and final.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">element</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/DOM/Element">Element</a></span></div>
<div class="entryOverview">Root element for the component.</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line477">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Component.prototype.setId"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">setId<span class="args">(<span class="arg">id</span>)</span>
</span>
</div>
<div class="entryOverview">
Assigns an ID to this component instance. It is the caller's responsibility
to guarantee that the ID is unique. If the component is a child of a parent
component, then the parent component's child index is updated to reflect the
new ID; this may throw an error if the parent already has a child with an ID
that conflicts with the new ID.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">id</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String">string</a></span></div>
<div class="entryOverview">Unique component ID.</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line450">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Component.prototype.setModel"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">setModel<span class="args">(<span class="arg">obj</span>)</span>
</span>
</div>
<div class="entryOverview">
Sets the model associated with the UI component.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">obj</span>
: <div class="fullType"><span class="type">*</span></div>
<div class="entryOverview">The model.</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line808">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Component.prototype.setParent"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">setParent<span class="args">(<span class="arg">parent</span>)</span>
</span>
</div>
<div class="entryOverview">
Sets the parent of this component to use for event bubbling. Throws an error
if the component already has a parent or if an attempt is made to add a
component to itself as a child. Callers must use <code>removeChild</code>
or <code>removeChildAt</code> to remove components from their containers before
calling this method.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">parent</span>
: <div class="fullType"><span class="type"><a href="class_goog_ui_Component.html">goog.ui.Component</a></span></div>
<div class="entryOverview">The parent component.</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line504">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Component.prototype.setParentEventTarget"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">setParentEventTarget<span class="args">(<span class="arg">parent</span>)</span>
</span>
</div>
<div class="entryOverview">
Overrides goog.events.EventTarget#setParentEventTarget to throw an
error if the parent component is set, and the argument is not the parent.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">parent</span>
: <div class="fullType"><span class="type"><a href="class_goog_events_EventTarget.html">goog.events.EventTarget</a></span></div>
<div class="entryOverview">Parent EventTarget (null if none).</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line537">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Component.prototype.setRightToLeft"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">setRightToLeft<span class="args">(<span class="arg">rightToLeft</span>)</span>
</span>
</div>
<div class="entryOverview">
Set is right-to-left. This function should be used if the component needs
to know the rendering direction during dom creation (i.e. before
#enterDocument is called and is right-to-left is set).
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">rightToLeft</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
<div class="entryOverview">Whether the component is rendered right-to-left.</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line990">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.ui.Component.prototype.wasDecorated"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">wasDecorated<span class="args">()</span>
</span>
⇒ <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
</div>
<div class="entryOverview">
<span class='nodesc'>No description.</span>
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
Whether the component was decorated.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line682">code »</a>
</td>
</tr>
</table>
</div>
</div>
<div>
<div class="desc">
Defined in
<span class="fn-name">
<a href="class_goog_events_EventTarget.html">
goog.events.EventTarget
</a>
</span>
</div>
<div class="section">
<table class="horiz-rule">
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.events.EventTarget.prototype.addEventListener"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">addEventListener<span class="args">(<span class="arg">type</span>, <span class="arg">handler</span>, <span class="arg">opt_capture</span>, <span class="arg">opt_handlerScope</span>)</span>
</span>
</div>
<div class="entryOverview">
Adds an event listener to the event target. The same handler can only be
added once per the type. Even if you add the same handler multiple times
using the same type then it will only be called once when the event is
dispatched.
Supported for legacy but use goog.events.listen(src, type, handler) instead.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">type</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String">string</a></span></div>
<div class="entryOverview">The type of the event to listen for.</div>
</td>
</tr>
<tr class="odd">
<td>
<span class="entryName">handler</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Function">Function</a></span><span> | </span><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Object">Object</a></span></div>
<div class="entryOverview">The function to handle the event. The handler can also be an object that implements the handleEvent method which takes the event object as argument.</div>
</td>
</tr>
<tr class="even">
<td>
<span class="entryName">opt_capture</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
<div class="entryOverview">In DOM-compliant browsers, this determines whether the listener is fired during the capture or bubble phase of the event.</div>
</td>
</tr>
<tr class="odd">
<td>
<span class="entryName">opt_handlerScope</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Object">Object</a></span></div>
<div class="entryOverview">Object in whose scope to call the listener.</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_events_eventtarget.js.source.html#line136">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.events.EventTarget.prototype.dispatchEvent"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">dispatchEvent<span class="args">(<span class="arg">e</span>)</span>
</span>
⇒ <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
</div>
<div class="entryOverview">
Dispatches an event (or event like object) and calls all listeners
listening for events of this type. The type of the event is decided by the
type property on the event object.
If any of the listeners returns false OR calls preventDefault then this
function will return false. If one of the capture listeners calls
stopPropagation, then the bubble listeners won't fire.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">e</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String">string</a></span><span> | </span><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Object">Object</a></span><span> | </span><span class="type"><a href="class_goog_events_Event.html">goog.events.Event</a></span></div>
<div class="entryOverview">Event object.</div>
</td>
</tr>
</table>
</div>
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
If anyone called preventDefault on the event object (or if any of the handlers returns false this will also return false.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_events_eventtarget.js.source.html#line174">code »</a>
</td>
</tr>
<tr class="even entry protected">
<td class="access"></td>
<td>
<a name="goog.events.EventTarget.prototype.disposeInternal"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">disposeInternal<span class="args">()</span>
</span>
</div>
<div class="entryOverview">
Unattach listeners from this object. Classes that extend EventTarget may
need to override this method in order to remove references to DOM Elements
and additional listeners, it should be something like this:
<pre class="lang-js">
MyClass.prototype.disposeInternal = function() {
MyClass.superClass_.disposeInternal.call(this);
// Dispose logic for MyClass
};
</pre>
</div>
</td>
<td class="view-code">
<a href="closure_goog_events_eventtarget.js.source.html#line191">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.events.EventTarget.prototype.getParentEventTarget"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">getParentEventTarget<span class="args">()</span>
</span>
⇒ <div class="fullType"><span class="type"><a href="class_goog_events_EventTarget.html">goog.events.EventTarget</a></span></div>
</div>
<div class="entryOverview">
Returns the parent of this event target to use for bubbling.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span class="type"><a href="class_goog_events_EventTarget.html">goog.events.EventTarget</a></span></div>
The parent EventTarget or null if there is no parent.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_events_eventtarget.js.source.html#line104">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.events.EventTarget.prototype.removeEventListener"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">removeEventListener<span class="args">(<span class="arg">type</span>, <span class="arg">handler</span>, <span class="arg">opt_capture</span>, <span class="arg">opt_handlerScope</span>)</span>
</span>
</div>
<div class="entryOverview">
Removes an event listener from the event target. The handler must be the
same object as the one added. If the handler has not been added then
nothing is done.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">type</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String">string</a></span></div>
<div class="entryOverview">The type of the event to listen for.</div>
</td>
</tr>
<tr class="odd">
<td>
<span class="entryName">handler</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Function">Function</a></span><span> | </span><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Object">Object</a></span></div>
<div class="entryOverview">The function to handle the event. The handler can also be an object that implements the handleEvent method which takes the event object as argument.</div>
</td>
</tr>
<tr class="even">
<td>
<span class="entryName">opt_capture</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
<div class="entryOverview">In DOM-compliant browsers, this determines whether the listener is fired during the capture or bubble phase of the event.</div>
</td>
</tr>
<tr class="odd">
<td>
<span class="entryName">opt_handlerScope</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Object">Object</a></span></div>
<div class="entryOverview">Object in whose scope to call the listener.</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_events_eventtarget.js.source.html#line155">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.events.EventTarget.prototype.setParentEventTarget"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">setParentEventTarget<span class="args">(<span class="arg">parent</span>)</span>
</span>
</div>
<div class="entryOverview">
Sets the parent of this event target to use for bubbling.
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Arguments: </b>
<table class="horiz-rule">
<tr class="even">
<td>
<span class="entryName">parent</span>
: <div class="fullType"><span>?</span><span class="type"><a href="class_goog_events_EventTarget.html">goog.events.EventTarget</a></span></div>
<div class="entryOverview">Parent EventTarget (null if none).</div>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_events_eventtarget.js.source.html#line114">code »</a>
</td>
</tr>
</table>
</div>
</div>
<div>
<div class="desc">
Defined in
<span class="fn-name">
<a href="class_goog_Disposable.html">
goog.Disposable
</a>
</span>
</div>
<div class="section">
<table class="horiz-rule">
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.Disposable.prototype.dispose"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">dispose<span class="args">()</span>
</span>
</div>
<div class="entryOverview">
<span class='nodesc'>No description.</span>
</div>
</td>
<td class="view-code">
<a href="closure_goog_disposable_disposable.js.source.html#line64">code »</a>
</td>
</tr>
<tr class="odd entry protected">
<td class="access"></td>
<td>
<a name="goog.Disposable.prototype.disposeInternal"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">disposeInternal<span class="args">()</span>
</span>
</div>
<div class="entryOverview">
Deletes or nulls out any references to COM objects, DOM nodes, or other
disposable objects. Classes that extend <code>goog.Disposable</code> should
override this method. For example:
<pre class="lang-js">
mypackage.MyClass = function() {
goog.Disposable.call(this);
// Constructor logic specific to MyClass.
...
};
goog.inherits(mypackage.MyClass, goog.Disposable);
mypackage.MyClass.prototype.disposeInternal = function() {
mypackage.MyClass.superClass_.disposeInternal.call(this);
// Dispose logic specific to MyClass.
...
};
</pre>
</div>
</td>
<td class="view-code">
<a href="closure_goog_disposable_disposable.js.source.html#line94">code »</a>
</td>
</tr>
<tr class="even entry public">
<td class="access"></td>
<td>
<a name="goog.Disposable.prototype.getDisposed"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">getDisposed<span class="args">()</span>
</span>
⇒ <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
</div>
<div class="entryOverview">
<span class='nodesc'>No description.</span>
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
Whether the object has been disposed of.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_disposable_disposable.js.source.html#line55">code »</a>
</td>
</tr>
<tr class="odd entry public">
<td class="access"></td>
<td>
<a name="goog.Disposable.prototype.isDisposed"></a>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">isDisposed<span class="args">()</span>
</span>
⇒ <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
</div>
<div class="entryOverview">
<span class='nodesc'>No description.</span>
</div>
<! -- Method details -->
<div class="entryDetails">
<div class="detailsSection">
<b>Returns:</b> <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
Whether the object has been disposed of.
</div>
</div>
</td>
<td class="view-code">
<a href="closure_goog_disposable_disposable.js.source.html#line46">code »</a>
</td>
</tr>
</table>
</div>
</div>
<h2>Instance Properties</h2>
<div>
<div class="desc">
Defined in
<span class="fn-name">
<a href="class_goog_ui_Control.html">
goog.ui.Control
</a>
</span>
</div>
<div class="section">
<table class="horiz-rule">
<tr class="even entry private">
<td class="access"></td>
<a name="goog.ui.Control.prototype.allowTextSelection_"></a>
<td>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">allowTextSelection_</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
</div>
<div class="entryOverview">
Whether the control allows text selection within its DOM. Defaults to false.
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line235">Code »</a>
</td>
</tr>
<tr class="odd entry private">
<td class="access"></td>
<a name="goog.ui.Control.prototype.autoStates_"></a>
<td>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">autoStates_</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Number">number</a></span></div>
</div>
<div class="entryOverview">
A bit mask of goog.ui.Component.States for which this component
provides default event handling. For example, a component that handles
the HOVER state automatically will highlight itself on mouseover, whereas
a component that doesn't handle HOVER automatically will only dispatch
ENTER and LEAVE events but not call setHighlighted on itself.
By default, components provide default event handling for all states.
Controls hosted in containers (e.g. menu items in a menu, or buttons in a
toolbar) will typically want to have their container manage their highlight
state. Selectable controls managed by a selection model will also typically
want their selection state to be managed by the model.
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line180">Code »</a>
</td>
</tr>
<tr class="even entry private">
<td class="access"></td>
<a name="goog.ui.Control.prototype.content_"></a>
<td>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">content_</span>
: <div class="fullType"><span class="type">goog.ui.ControlContent</span></div>
</div>
<div class="entryOverview">
Text caption or DOM structure displayed in the component.
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line143">Code »</a>
</td>
</tr>
<tr class="odd entry private">
<td class="access"></td>
<a name="goog.ui.Control.prototype.extraClassNames_"></a>
<td>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">extraClassNames_</span>
: <div class="fullType"><span>?</span><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array">Array</a></span>.<<span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String">string</a></span>></div>
</div>
<div class="entryOverview">
Additional class name(s) to apply to the control's root element, if any.
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line218">Code »</a>
</td>
</tr>
<tr class="even entry private">
<td class="access"></td>
<a name="goog.ui.Control.prototype.handleMouseEvents_"></a>
<td>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">handleMouseEvents_</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
</div>
<div class="entryOverview">
Whether the control should listen for and handle mouse events; defaults to
true.
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line227">Code »</a>
</td>
</tr>
<tr class="odd entry private">
<td class="access"></td>
<a name="goog.ui.Control.prototype.state_"></a>
<td>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">state_</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Number">number</a></span></div>
</div>
<div class="entryOverview">
Current component state; a bit mask of goog.ui.Component.States.
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line151">Code »</a>
</td>
</tr>
<tr class="even entry private">
<td class="access"></td>
<a name="goog.ui.Control.prototype.statesWithTransitionEvents_"></a>
<td>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">statesWithTransitionEvents_</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Number">number</a></span></div>
</div>
<div class="entryOverview">
A bit mask of goog.ui.Component.States for which this component
dispatches state transition events. Because events are expensive, the
default behavior is to not dispatch any state transition events at all.
Use the #setDispatchTransitionEvents API to request transition
events as needed. Subclasses may enable transition events by default.
Controls hosted in containers or managed by a selection model will typically
want to dispatch transition events.
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line194">Code »</a>
</td>
</tr>
<tr class="odd entry private">
<td class="access"></td>
<a name="goog.ui.Control.prototype.supportedStates_"></a>
<td>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">supportedStates_</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Number">number</a></span></div>
</div>
<div class="entryOverview">
A bit mask of goog.ui.Component.States this component supports.
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line159">Code »</a>
</td>
</tr>
<tr class="even entry private">
<td class="access"></td>
<a name="goog.ui.Control.prototype.visible_"></a>
<td>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">visible_</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
</div>
<div class="entryOverview">
Component visibility.
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_control.js.source.html#line202">Code »</a>
</td>
</tr>
</table>
</div>
</div>
<div>
<div class="desc">
Defined in
<span class="fn-name">
<a href="class_goog_ui_Component.html">
goog.ui.Component
</a>
</span>
</div>
<div class="section">
<table class="horiz-rule">
<tr class="even entry private">
<td class="access"></td>
<a name="goog.ui.Component.prototype.childIndex_"></a>
<td>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">childIndex_</span>
: <div class="fullType"><span>?</span><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Object">Object</a></span></div>
</div>
<div class="entryOverview">
Map of child component IDs to child components. Used for constant-time
random access to child components by ID. Lazily initialized on first use.
Must be kept in sync with <code>children_</code>. This property is strictly
private and must not be accessed directly outside of this class!
We use a plain Object, not a goog.structs.Map, for simplicity.
This means components can't have children with IDs such as 'constructor' or
'valueOf', but this shouldn't really be an issue in practice, and if it is,
we can always fix it later without changing the API.
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line419">Code »</a>
</td>
</tr>
<tr class="odd entry private">
<td class="access"></td>
<a name="goog.ui.Component.prototype.children_"></a>
<td>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">children_</span>
: <div class="fullType"><span>?</span><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array">Array</a></span>.<<span class="type"><a href="class_goog_ui_Component.html">goog.ui.Component</a></span>></div>
</div>
<div class="entryOverview">
Array of child components. Lazily initialized on first use. Must be kept in
sync with <code>childIndex_</code>. This property is strictly private and must
not be accessed directly outside of this class!
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line402">Code »</a>
</td>
</tr>
<tr class="even entry protected">
<td class="access"></td>
<a name="goog.ui.Component.prototype.dom_"></a>
<td>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">dom_</span>
: <div class="fullType"><span>?</span><span class="type"><a href="class_goog_dom_DomHelper.html">goog.dom.DomHelper</a></span></div>
</div>
<div class="entryOverview">
DomHelper used to interact with the document, allowing components to be
created in a different window.
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line337">Code »</a>
</td>
</tr>
<tr class="odd entry private">
<td class="access"></td>
<a name="goog.ui.Component.prototype.element_"></a>
<td>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">element_</span>
: <div class="fullType"><span>?</span><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/DOM/Element">Element</a></span></div>
</div>
<div class="entryOverview">
The DOM element for the component.
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line354">Code »</a>
</td>
</tr>
<tr class="even entry private">
<td class="access"></td>
<a name="goog.ui.Component.prototype.idGenerator_"></a>
<td>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">idGenerator_</span>
: <div class="fullType"><span class="type"><a href="class_goog_ui_IdGenerator.html">goog.ui.IdGenerator</a></span></div>
</div>
<div class="entryOverview">
Generator for unique IDs.
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line61">Code »</a>
</td>
</tr>
<tr class="odd entry private">
<td class="access"></td>
<a name="goog.ui.Component.prototype.id_"></a>
<td>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">id_</span>
: <div class="fullType"><span>?</span><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String">string</a></span></div>
</div>
<div class="entryOverview">
Unique ID of the component, lazily initialized in {@link
goog.ui.Component#getId} if needed. This property is strictly private and
must not be accessed directly outside of this class!
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line327">Code »</a>
</td>
</tr>
<tr class="even entry private">
<td class="access"></td>
<a name="goog.ui.Component.prototype.inDocument_"></a>
<td>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">inDocument_</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
</div>
<div class="entryOverview">
Whether the component is in the document.
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line345">Code »</a>
</td>
</tr>
<tr class="odd entry private">
<td class="access"></td>
<a name="goog.ui.Component.prototype.parent_"></a>
<td>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">parent_</span>
: <div class="fullType"><span>?</span><span class="type"><a href="class_goog_ui_Component.html">goog.ui.Component</a></span></div>
</div>
<div class="entryOverview">
Parent component to which events will be propagated. This property is
strictly private and must not be accessed directly outside of this class!
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line392">Code »</a>
</td>
</tr>
<tr class="even entry private">
<td class="access"></td>
<a name="goog.ui.Component.prototype.rightToLeft_"></a>
<td>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">rightToLeft_</span>
: <div class="fullType"><span>?</span><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
</div>
<div class="entryOverview">
Whether the component is rendered right-to-left. Right-to-left is set
lazily when #isRightToLeft is called the first time, unless it has
been set by calling #setRightToLeft explicitly.
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line375">Code »</a>
</td>
</tr>
<tr class="odd entry private">
<td class="access"></td>
<a name="goog.ui.Component.prototype.wasDecorated_"></a>
<td>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">wasDecorated_</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
</div>
<div class="entryOverview">
Flag used to keep track of whether a component decorated an already existing
element or whether it created the DOM itself. If an element was decorated
dispose will remove the node from the document, it is left up to the app.
</div>
</td>
<td class="view-code">
<a href="closure_goog_ui_component.js.source.html#line429">Code »</a>
</td>
</tr>
</table>
</div>
</div>
<div>
<div class="desc">
Defined in
<span class="fn-name">
<a href="class_goog_events_EventTarget.html">
goog.events.EventTarget
</a>
</span>
</div>
<div class="section">
<table class="horiz-rule">
<tr class="even entry private">
<td class="access"></td>
<a name="goog.events.EventTarget.prototype.customEvent_"></a>
<td>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">customEvent_</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
</div>
<div class="entryOverview">
Used to tell if an event is a real event in goog.events.listen() so we don't
get listen() calling addEventListener() and vice-versa.
</div>
</td>
<td class="view-code">
<a href="closure_goog_events_eventtarget.js.source.html#line87">Code »</a>
</td>
</tr>
<tr class="odd entry private">
<td class="access"></td>
<a name="goog.events.EventTarget.prototype.parentEventTarget_"></a>
<td>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">parentEventTarget_</span>
: <div class="fullType"><span>?</span><span class="type"><a href="class_goog_events_EventTarget.html">goog.events.EventTarget</a></span></div>
</div>
<div class="entryOverview">
Parent event target, used during event bubbling.
</div>
</td>
<td class="view-code">
<a href="closure_goog_events_eventtarget.js.source.html#line95">Code »</a>
</td>
</tr>
</table>
</div>
</div>
<div>
<div class="desc">
Defined in
<span class="fn-name">
<a href="class_goog_Disposable.html">
goog.Disposable
</a>
</span>
</div>
<div class="section">
<table class="horiz-rule">
<tr class="even entry private">
<td class="access"></td>
<a name="goog.Disposable.prototype.disposed_"></a>
<td>
<div class="arg">
<img align="left" src="static/images/blank.gif">
<span class="entryName">disposed_</span>
: <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">boolean</a></span></div>
</div>
<div class="entryOverview">
Whether the object has been disposed of.
</div>
</td>
<td class="view-code">
<a href="closure_goog_disposable_disposable.js.source.html#line40">Code »</a>
</td>
</tr>
</table>
</div>
</div>
<div class="section">
<table class="horiz-rule">
</table>
</div>
<div class="section">
<table class="horiz-rule">
</table>
</div>
<!-- Column 1 end -->
</div>
<div class="col2">
<!-- Column 2 start -->
<div class="col2-c">
<h2 id="ref-head">Package ui</h2>
<div id="localView"></div>
</div>
<div class="col2-c">
<h2 id="ref-head">Package Reference</h2>
<div id="sideTypeIndex" rootPath="goog" current="ui.Separator"></div>
</div>
<!-- Column 2 end -->
</div>
</div>
</div>
</body>
</html>
| {
"content_hash": "3064f473a2a1047067edfb371d864f3e",
"timestamp": "",
"source": "github",
"line_count": 7837,
"max_line_length": 504,
"avg_line_length": 24.064437922674493,
"alnum_prop": 0.608511450584062,
"repo_name": "yesudeep/puppy",
"id": "aaf1fdeb038221830698bd8ed6a5a0d5eeaed1b3",
"size": "188593",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "tools/google-closure-library/closure/goog/docs/class_goog_ui_Separator.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "7979495"
},
{
"name": "Python",
"bytes": "117877"
},
{
"name": "Ruby",
"bytes": "592"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 1.0 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="../includes/main.css" type="text/css">
<link rel="shortcut icon" href="../favicon.ico" type="image/x-icon">
<title>Apache CloudStack | The Power Behind Your Cloud</title>
</head>
<body>
<div id="insidetopbg">
<div id="inside_wrapper">
<div class="uppermenu_panel">
<div class="uppermenu_box"></div>
</div>
<div id="main_master">
<div id="inside_header">
<div class="header_top">
<a class="cloud_logo" href="http://cloudstack.org"></a>
<div class="mainemenu_panel"></div>
</div>
</div>
<div id="main_content">
<div class="inside_apileftpanel">
<div class="inside_contentpanel" style="width:930px;">
<div class="api_titlebox">
<div class="api_titlebox_left">
<span>
Apache CloudStack v4.8.0 Domain Admin API Reference
</span>
<p></p>
<h1>listUsageRecords</h1>
<p>Lists usage records for accounts</p>
</div>
<div class="api_titlebox_right">
<a class="api_backbutton" href="../TOC_Domain_Admin.html"></a>
</div>
</div>
<div class="api_tablepanel">
<h2>Request parameters</h2>
<table class="apitable">
<tr class="hed">
<td style="width:200px;"><strong>Parameter Name</strong></td><td style="width:500px;">Description</td><td style="width:180px;">Required</td>
</tr>
<tr>
<td style="width:200px;"><strong>enddate</strong></td><td style="width:500px;"><strong>End date range for usage record query (use format "yyyy-MM-dd" or the new format "yyyy-MM-dd HH:mm:ss", e.g. startDate=2015-01-01 or startdate=2015-01-01 10:30:00).</strong></td><td style="width:180px;"><strong>true</strong></td>
</tr>
<tr>
<td style="width:200px;"><strong>startdate</strong></td><td style="width:500px;"><strong>Start date range for usage record query (use format "yyyy-MM-dd" or the new format "yyyy-MM-dd HH:mm:ss", e.g. startDate=2015-01-01 or startdate=2015-01-01 11:00:00).</strong></td><td style="width:180px;"><strong>true</strong></td>
</tr>
<tr>
<td style="width:200px;"><i>account</i></td><td style="width:500px;"><i>List usage records for the specified user.</i></td><td style="width:180px;"><i>false</i></td>
</tr>
<tr>
<td style="width:200px;"><i>accountid</i></td><td style="width:500px;"><i>List usage records for the specified account</i></td><td style="width:180px;"><i>false</i></td>
</tr>
<tr>
<td style="width:200px;"><i>domainid</i></td><td style="width:500px;"><i>List usage records for the specified domain.</i></td><td style="width:180px;"><i>false</i></td>
</tr>
<tr>
<td style="width:200px;"><i>keyword</i></td><td style="width:500px;"><i>List by keyword</i></td><td style="width:180px;"><i>false</i></td>
</tr>
<tr>
<td style="width:200px;"><i>page</i></td><td style="width:500px;"><i></i></td><td style="width:180px;"><i>false</i></td>
</tr>
<tr>
<td style="width:200px;"><i>pagesize</i></td><td style="width:500px;"><i></i></td><td style="width:180px;"><i>false</i></td>
</tr>
<tr>
<td style="width:200px;"><i>projectid</i></td><td style="width:500px;"><i>List usage records for specified project</i></td><td style="width:180px;"><i>false</i></td>
</tr>
<tr>
<td style="width:200px;"><i>type</i></td><td style="width:500px;"><i>List usage records for the specified usage type</i></td><td style="width:180px;"><i>false</i></td>
</tr>
<tr>
<td style="width:200px;"><i>usageid</i></td><td style="width:500px;"><i>List usage records for the specified usage UUID. Can be used only together with TYPE parameter.</i></td><td style="width:180px;"><i>false</i></td>
</tr>
</table>
</div>
<div class="api_tablepanel">
<h2>Response Tags</h2>
<table class="apitable">
<tr class="hed">
<td style="width:200px;"><strong>Response Name</strong></td><td style="width:500px;">Description</td>
</tr>
<tr>
<td style="width:200px;"><strong>account</strong></td><td style="width:500px;">the user account name</td>
</tr>
<tr>
<td style="width:200px;"><strong>accountid</strong></td><td style="width:500px;">the user account Id</td>
</tr>
<tr>
<td style="width:200px;"><strong>cpunumber</strong></td><td style="width:500px;">number of cpu of resource</td>
</tr>
<tr>
<td style="width:200px;"><strong>cpuspeed</strong></td><td style="width:500px;">speed of each cpu of resource</td>
</tr>
<tr>
<td style="width:200px;"><strong>description</strong></td><td style="width:500px;">description of the usage record</td>
</tr>
<tr>
<td style="width:200px;"><strong>domain</strong></td><td style="width:500px;">the domain the resource is associated with</td>
</tr>
<tr>
<td style="width:200px;"><strong>domainid</strong></td><td style="width:500px;">the domain ID</td>
</tr>
<tr>
<td style="width:200px;"><strong>enddate</strong></td><td style="width:500px;">end date of the usage record</td>
</tr>
<tr>
<td style="width:200px;"><strong>isdefault</strong></td><td style="width:500px;">True if the resource is default</td>
</tr>
<tr>
<td style="width:200px;"><strong>issourcenat</strong></td><td style="width:500px;">True if the IPAddress is source NAT</td>
</tr>
<tr>
<td style="width:200px;"><strong>issystem</strong></td><td style="width:500px;">True if the IPAddress is system IP - allocated during vm deploy or lb rule create</td>
</tr>
<tr>
<td style="width:200px;"><strong>memory</strong></td><td style="width:500px;">memory allocated for the resource</td>
</tr>
<tr>
<td style="width:200px;"><strong>name</strong></td><td style="width:500px;">virtual machine name</td>
</tr>
<tr>
<td style="width:200px;"><strong>networkid</strong></td><td style="width:500px;">id of the network</td>
</tr>
<tr>
<td style="width:200px;"><strong>offeringid</strong></td><td style="width:500px;">offering ID</td>
</tr>
<tr>
<td style="width:200px;"><strong>project</strong></td><td style="width:500px;">the project name of the resource</td>
</tr>
<tr>
<td style="width:200px;"><strong>projectid</strong></td><td style="width:500px;">the project id of the resource</td>
</tr>
<tr>
<td style="width:200px;"><strong>rawusage</strong></td><td style="width:500px;">raw usage in hours</td>
</tr>
<tr>
<td style="width:200px;"><strong>size</strong></td><td style="width:500px;">resource size</td>
</tr>
<tr>
<td style="width:200px;"><strong>startdate</strong></td><td style="width:500px;">start date of the usage record</td>
</tr>
<tr>
<td style="width:200px;"><strong>templateid</strong></td><td style="width:500px;">template ID</td>
</tr>
<tr>
<td style="width:200px;"><strong>type</strong></td><td style="width:500px;">resource type</td>
</tr>
<tr>
<td style="width:200px;"><strong>usage</strong></td><td style="width:500px;">usage in hours</td>
</tr>
<tr>
<td style="width:200px;"><strong>usageid</strong></td><td style="width:500px;">id of the resource</td>
</tr>
<tr>
<td style="width:200px;"><strong>usagetype</strong></td><td style="width:500px;">usage type ID</td>
</tr>
<tr>
<td style="width:200px;"><strong>virtualmachineid</strong></td><td style="width:500px;">virtual machine ID</td>
</tr>
<tr>
<td style="width:200px;"><strong>virtualsize</strong></td><td style="width:500px;">virtual size of resource</td>
</tr>
<tr>
<td style="width:200px;"><strong>zoneid</strong></td><td style="width:500px;">the zone ID</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
<div id="footer">
<div id="footer_mainmaster">
<p>Copyright © 2016 The Apache Software Foundation, Licensed under the
<a href="http://www.apache.org/licenses/LICENSE-2.0">Apache License, Version 2.0.</a>
<br>
Apache, CloudStack, Apache CloudStack, the Apache CloudStack logo, the CloudMonkey logo and the Apache feather logo are trademarks of The Apache Software Foundation.</p>
</div>
</div>
</div>
</div>
</body>
</html>
| {
"content_hash": "c3649682cf6f7943150647e39a83653a",
"timestamp": "",
"source": "github",
"line_count": 187,
"max_line_length": 320,
"avg_line_length": 41.63101604278075,
"alnum_prop": 0.6742453436095055,
"repo_name": "terbolous/cloudstack-www",
"id": "68e5daec49460382d01b061836111f9affe4cc75",
"size": "7785",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "content/api/apidocs-4.8/domain_admin/listUsageRecords.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "303768"
},
{
"name": "HTML",
"bytes": "123165841"
},
{
"name": "Python",
"bytes": "2684"
},
{
"name": "Ruby",
"bytes": "1967"
},
{
"name": "Shell",
"bytes": "861"
}
],
"symlink_target": ""
} |
FROM rocker/verse:3.3.1
RUN apt-get update && apt-get -y install --no-install-recommends jekyll ruby-rouge
WORKDIR /home/rstudio
EXPOSE 4000
ENV SERVE TRUE
CMD Rscript -e "dirs = c('.', 'readings', 'assignments', 'lectures'); servr::jekyll('website', serve=$SERVE, input = dirs, output = dirs, host = '0.0.0.0', port=4000)"
## Build & view site on localhost:
# docker run -d -p 4000:4000 -v $(pwd):/home/rstudio cboettig/rcds
## Build site into docs/
# docker run -ti -v $(pwd):/home/rstudio -e SERVE=FALSE cboettig/rcds
| {
"content_hash": "964e95f40ec565caf82dac0f72203582",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 167,
"avg_line_length": 32.9375,
"alnum_prop": 0.6888045540796964,
"repo_name": "ds421/rcds",
"id": "2ddab82a8672a7966b744cb00a3e860d46f990f5",
"size": "527",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Dockerfile",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "CSS",
"bytes": "21000"
},
{
"name": "HTML",
"bytes": "5317884"
},
{
"name": "R",
"bytes": "833"
},
{
"name": "Shell",
"bytes": "1122"
}
],
"symlink_target": ""
} |
<?php
namespace Werkspot\Bundle\StatsdBundle\Event;
use Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Werkspot\Bundle\StatsdBundle\Client\StatsdClientInterface;
class RecordingDispatcher implements EventDispatcherInterface
{
/**
* @var ContainerAwareEventDispatcher|EventDispatcherInterface
*/
private $originalDispatcher;
/**
* @var StatsdClientInterface
*/
private $statsdClient;
/**
* @param EventDispatcherInterface $originalDispatcher
* @param StatsdClientInterface $statsdClient
*/
public function __construct(
EventDispatcherInterface $originalDispatcher,
StatsdClientInterface $statsdClient
) {
$this->originalDispatcher = $originalDispatcher;
$this->statsdClient = $statsdClient;
}
/**
* @see ContainerAwareEventDispatcher::addListenerService
*/
public function addListenerService($eventName, $callback, $priority = 0)
{
$this->originalDispatcher->addListenerService($eventName, $callback, $priority);
}
/**
* @see ContainerAwareEventDispatcher::addSubscriberService
*/
public function addSubscriberService($serviceId, $class)
{
$this->originalDispatcher->addSubscriberService($serviceId, $class);
}
/**
* {@inheritdoc}
*/
public function dispatch($eventName, Event $event = null)
{
$this->statsdClient->increment(str_replace('.', '-', $eventName));
return $this->originalDispatcher->dispatch($eventName, $event);
}
/**
* {@inheritdoc}
*/
public function addListener($eventName, $listener, $priority = 0)
{
$this->originalDispatcher->addListener($eventName, $listener, $priority);
}
/**
* {@inheritdoc}
*/
public function addSubscriber(EventSubscriberInterface $subscriber)
{
$this->originalDispatcher->addSubscriber($subscriber);
}
/**
* {@inheritdoc}
*/
public function removeListener($eventName, $listener)
{
$this->originalDispatcher->removeListener($eventName, $listener);
}
/**
* {@inheritdoc}
*/
public function removeSubscriber(EventSubscriberInterface $subscriber)
{
$this->originalDispatcher->removeSubscriber($subscriber);
}
/**
* {@inheritdoc}
*/
public function getListeners($eventName = null)
{
return $this->originalDispatcher->getListeners($eventName);
}
/**
* {@inheritdoc}
*/
public function hasListeners($eventName = null)
{
return $this->originalDispatcher->hasListeners($eventName);
}
/**
* {@inheritdoc}
*/
public function getListenerPriority($eventName, $listener)
{
return $this->getListenerPriority($eventName, $listener);
}
}
| {
"content_hash": "b7901682d947fabfbbffcde1b1a60a23",
"timestamp": "",
"source": "github",
"line_count": 115,
"max_line_length": 88,
"avg_line_length": 26.252173913043478,
"alnum_prop": 0.6608148393507784,
"repo_name": "Werkspot/statsd-bundle",
"id": "47e83b2dcaaf9e01f3d0ec553c729d19d963396c",
"size": "3019",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Event/RecordingDispatcher.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "18747"
}
],
"symlink_target": ""
} |
import collections
from .. import scalartypes as scalars
from .. import ir
def allocateRequiredConstants(pool, long_irs):
# see comments in writebytecode.finishCodeAttrs
# We allocate the constants pretty much greedily. This is far from optimal,
# but it shouldn't be a big deal since this code is almost never required
# in the first place. In fact, there are no known real world classes that
# even come close to exhausting the constant pool.
narrow_pairs = collections.Counter()
wide_pairs = collections.Counter()
alt_lens = {}
for _ir in long_irs:
for ins in _ir.flat_instructions:
if isinstance(ins, ir.PrimConstant):
key = ins.cpool_key()
alt_lens[key] = len(ins.bytecode)
if scalars.iswide(ins.st):
if len(ins.bytecode) > 3:
wide_pairs[key] += 1
else:
if len(ins.bytecode) > 2:
narrow_pairs[key] += 1
# see if already in the constant pool
for x in pool.vals:
del narrow_pairs[x]
del wide_pairs[x]
# if we have enough space for all required constants, preferentially allocate
# most commonly used constants to first 255 slots
if pool.space() >= len(narrow_pairs) + 2*len(wide_pairs) and pool.lowspace() > 0:
# We can't use Counter.most_common here because it is nondeterminstic in
# the case of ties.
most_common = sorted(narrow_pairs, key=lambda p:(-narrow_pairs[p], p))
for key in most_common[:pool.lowspace()]:
pool.insertDirectly(key, True)
del narrow_pairs[key]
scores = {}
for p, count in narrow_pairs.items():
scores[p] = (alt_lens[p] - 3) * count
for p, count in wide_pairs.items():
scores[p] = (alt_lens[p] - 3) * count
# sort by score
narrowq = sorted(narrow_pairs, key=lambda p:(scores[p], p))
wideq = sorted(wide_pairs, key=lambda p:(scores[p], p))
while pool.space() >= 1 and (narrowq or wideq):
if not narrowq and pool.space() < 2:
break
wscore = sum(scores[p] for p in wideq[-1:])
nscore = sum(scores[p] for p in narrowq[-2:])
if pool.space() >= 2 and wscore > nscore and wscore > 0:
pool.insertDirectly(wideq.pop(), False)
elif nscore > 0:
pool.insertDirectly(narrowq.pop(), True)
else:
break
| {
"content_hash": "eeab938778b87f2b586c361f657397f6",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 85,
"avg_line_length": 39.70967741935484,
"alnum_prop": 0.5934199837530463,
"repo_name": "tp7309/AndroidOneKeyDecompiler",
"id": "60f77e73a6cf2d6eace32d6124a394e63d7a0477",
"size": "3059",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "libs/enjarify/enjarify/jvm/optimization/consts.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "17032"
},
{
"name": "Python",
"bytes": "6214"
},
{
"name": "Shell",
"bytes": "28752"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
World Register of Marine Species
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "33cb5edf44fb825af55aa14759ddf8f3",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 32,
"avg_line_length": 9.76923076923077,
"alnum_prop": 0.7007874015748031,
"repo_name": "mdoering/backbone",
"id": "f257cbc09bbb280ba51300b3492afeeac032aed6",
"size": "178",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Chromista/Ochrophyta/Talarodictyon/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package com.intellij.xdebugger.impl.evaluate.quick.common;
import com.intellij.codeInsight.hint.HintManager;
import com.intellij.codeInsight.hint.HintManagerImpl;
import com.intellij.codeInsight.hint.HintUtil;
import com.intellij.codeInsight.navigation.NavigationUtil;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.colors.EditorColors;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.event.EditorMouseEvent;
import com.intellij.openapi.editor.markup.HighlighterLayer;
import com.intellij.openapi.editor.markup.HighlighterTargetArea;
import com.intellij.openapi.editor.markup.RangeHighlighter;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
import com.intellij.ui.ClickListener;
import com.intellij.ui.HintListener;
import com.intellij.ui.LightweightHint;
import com.intellij.ui.SimpleColoredText;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.util.IconUtil;
import org.intellij.lang.annotations.JdkConstants;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.EventObject;
/**
* @author nik
*/
public abstract class AbstractValueHint {
private static final Logger LOG = Logger.getInstance(AbstractValueHint.class);
private final KeyListener myEditorKeyListener = new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
if (!isAltMask(e.getModifiers())) {
ValueLookupManager.getInstance(myProject).hideHint();
}
}
};
private RangeHighlighter myHighlighter;
private Cursor myStoredCursor;
private final Project myProject;
private final Editor myEditor;
private final ValueHintType myType;
protected final Point myPoint;
private LightweightHint myCurrentHint;
private boolean myHintHidden;
private TextRange myCurrentRange;
private Runnable myHideRunnable;
public AbstractValueHint(@NotNull Project project, @NotNull Editor editor, @NotNull Point point, @NotNull ValueHintType type,
final TextRange textRange) {
myPoint = point;
myProject = project;
myEditor = editor;
myType = type;
myCurrentRange = textRange;
}
protected abstract boolean canShowHint();
protected abstract void evaluateAndShowHint();
public boolean isKeepHint(Editor editor, Point point) {
if (myCurrentHint != null && myCurrentHint.canControlAutoHide()) {
return true;
}
if (myType == ValueHintType.MOUSE_ALT_OVER_HINT) {
return false;
}
else if (myType == ValueHintType.MOUSE_CLICK_HINT) {
if (myCurrentHint != null && myCurrentHint.isVisible()) {
return true;
}
}
else {
int offset = calculateOffset(editor, point);
if (myCurrentRange != null && myCurrentRange.getStartOffset() <= offset && offset <= myCurrentRange.getEndOffset()) {
return true;
}
}
return false;
}
public static int calculateOffset(@NotNull Editor editor, @NotNull Point point) {
return editor.logicalPositionToOffset(editor.xyToLogicalPosition(point));
}
public void hideHint() {
myHintHidden = true;
myCurrentRange = null;
if (myStoredCursor != null) {
Component internalComponent = myEditor.getContentComponent();
internalComponent.setCursor(myStoredCursor);
if (LOG.isDebugEnabled()) {
LOG.debug("internalComponent.setCursor(myStoredCursor)");
}
internalComponent.removeKeyListener(myEditorKeyListener);
}
if (myCurrentHint != null) {
myCurrentHint.hide();
myCurrentHint = null;
}
if (myHighlighter != null) {
myHighlighter.dispose();
myHighlighter = null;
}
}
public void invokeHint() {
invokeHint(null);
}
public void invokeHint(Runnable hideRunnable) {
myHideRunnable = hideRunnable;
if (!canShowHint()) {
hideHint();
return;
}
if (myType == ValueHintType.MOUSE_ALT_OVER_HINT) {
EditorColorsScheme scheme = EditorColorsManager.getInstance().getGlobalScheme();
TextAttributes attributes = scheme.getAttributes(EditorColors.REFERENCE_HYPERLINK_COLOR);
attributes = NavigationUtil.patchAttributesColor(attributes, myCurrentRange, myEditor);
myHighlighter = myEditor.getMarkupModel().addRangeHighlighter(myCurrentRange.getStartOffset(), myCurrentRange.getEndOffset(),
HighlighterLayer.SELECTION + 1, attributes,
HighlighterTargetArea.EXACT_RANGE);
Component internalComponent = myEditor.getContentComponent();
myStoredCursor = internalComponent.getCursor();
internalComponent.addKeyListener(myEditorKeyListener);
internalComponent.setCursor(hintCursor());
if (LOG.isDebugEnabled()) {
LOG.debug("internalComponent.setCursor(hintCursor())");
}
}
else {
evaluateAndShowHint();
}
}
private static Cursor hintCursor() {
return Cursor.getPredefinedCursor(Cursor.HAND_CURSOR);
}
public Project getProject() {
return myProject;
}
protected Editor getEditor() {
return myEditor;
}
protected ValueHintType getType() {
return myType;
}
protected boolean showHint(final JComponent component) {
if (myCurrentHint != null) {
myCurrentHint.hide();
}
myCurrentHint = new LightweightHint(component);
myCurrentHint.addHintListener(new HintListener() {
@Override
public void hintHidden(EventObject event) {
if (myHideRunnable != null) {
myHideRunnable.run();
}
}
});
// editor may be disposed before later invokator process this action
if (myEditor.isDisposed() || myEditor.getComponent().getRootPane() == null) {
return false;
}
Point p = HintManagerImpl.getHintPosition(myCurrentHint, myEditor, myEditor.xyToLogicalPosition(myPoint), HintManager.UNDER);
HintManagerImpl.getInstanceImpl().showEditorHint(myCurrentHint, myEditor, p,
HintManager.HIDE_BY_ANY_KEY |
HintManager.HIDE_BY_TEXT_CHANGE |
HintManager.HIDE_BY_SCROLLING, 0, false,
HintManagerImpl.createHintHint(myEditor, p, myCurrentHint, HintManager.UNDER, true));
return true;
}
protected boolean isHintHidden() {
return myHintHidden;
}
protected JComponent createExpandableHintComponent(final SimpleColoredText text, final Runnable expand) {
final JComponent component = HintUtil.createInformationLabel(text, IconUtil.getAddIcon());
addClickListenerToHierarchy(component, new ClickListener() {
@Override
public boolean onClick(@NotNull MouseEvent event, int clickCount) {
if (myCurrentHint != null) {
myCurrentHint.hide();
}
expand.run();
return true;
}
});
return component;
}
private static void addClickListenerToHierarchy(Component c, ClickListener l) {
l.installOn(c);
if (c instanceof Container) {
Component[] children = ((Container)c).getComponents();
for (Component child : children) {
addClickListenerToHierarchy(child, l);
}
}
}
protected TextRange getCurrentRange() {
return myCurrentRange;
}
private static boolean isAltMask(@JdkConstants.InputEventMask int modifiers) {
return modifiers == InputEvent.ALT_MASK;
}
public static ValueHintType getType(final EditorMouseEvent e) {
return isAltMask(e.getMouseEvent().getModifiers()) ? ValueHintType.MOUSE_ALT_OVER_HINT : ValueHintType.MOUSE_OVER_HINT;
}
public boolean isInsideHint(Editor editor, Point point) {
return myCurrentHint != null && myCurrentHint.isInsideHint(new RelativePoint(editor.getContentComponent(), point));
}
protected <D> void showTreePopup(@NotNull DebuggerTreeCreator<D> creator, @NotNull D descriptor) {
DebuggerTreeWithHistoryPopup.showTreePopup(creator, descriptor, getEditor(), myPoint, getProject());
}
}
| {
"content_hash": "99e083ea9c5b083c45077d5adff31c5c",
"timestamp": "",
"source": "github",
"line_count": 246,
"max_line_length": 138,
"avg_line_length": 34.146341463414636,
"alnum_prop": 0.6953571428571429,
"repo_name": "ernestp/consulo",
"id": "c24ce74df1c66b34cf21486f23f3b0f18e719c9c",
"size": "9000",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "platform/xdebugger-impl/src/com/intellij/xdebugger/impl/evaluate/quick/common/AbstractValueHint.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "3588"
},
{
"name": "C",
"bytes": "47018"
},
{
"name": "C++",
"bytes": "88348"
},
{
"name": "CSS",
"bytes": "12523"
},
{
"name": "Groovy",
"bytes": "41575"
},
{
"name": "HTML",
"bytes": "188389"
},
{
"name": "Java",
"bytes": "54360143"
},
{
"name": "Lex",
"bytes": "5949"
},
{
"name": "Objective-C",
"bytes": "18984"
},
{
"name": "Python",
"bytes": "2985"
},
{
"name": "Shell",
"bytes": "8598"
},
{
"name": "Thrift",
"bytes": "1228"
},
{
"name": "XSLT",
"bytes": "49230"
}
],
"symlink_target": ""
} |
<?php
namespace app\controllers;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\models\LoginForm;
use app\models\ContactForm;
class SiteController extends Controller
{
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout'],
'rules' => [
[
'actions' => ['logout'],
'allow' => true,
'roles' => ['@'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
/**
* @inheritdoc
*/
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV ? 'testme' : null,
],
];
}
/**
* Displays homepage.
*
* @return string
*/
public function actionIndex()
{
return $this->render('index');
}
/**
* Login action.
*
* @return string
*/
public function actionLogin()
{
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
}
return $this->render('login', [
'model' => $model,
]);
}
/**
* Logout action.
*
* @return string
*/
public function actionLogout()
{
Yii::$app->user->logout();
return $this->goHome();
}
/**
* Displays contact page.
*
* @return string
*/
public function actionContact()
{
$model = new ContactForm();
if ($model->load(Yii::$app->request->post()) && $model->contact(Yii::$app->params['adminEmail'])) {
Yii::$app->session->setFlash('contactFormSubmitted');
return $this->refresh();
}
return $this->render('contact', [
'model' => $model,
]);
}
/**
* Displays about page.
*
* @return string
*/
public function actionAbout()
{
return $this->render('about');
}
public function actionTampil($nama="")
{
return $this->render('Hello',[
'nama'=> $nama,
]);
}
public function actionPesan()
{
$model = new \app\models\Pesan();
if(Yii::$app->request->post())
{
$model->load(Yii::$app->request->post());
if($model->validate())
{
Yii::$app->session->setFlash('success','Terima Kasih');
}else{
Yii::$app->session->setFlash('error','Maaf, Salah!');
}
return $this->render('hasil_komentar',[
'model' => $model,
]);
}else{
return $this->render('Pesan',[
'model'=>$model,
]);
}
}
public function actionQuery()
{
$db = Yii::$app->db;
$command = $db->createCommand('SELECT * FROM anggota');
$employees = $command->queryAll();
foreach($employees as $employee){
echo "<br>";
echo $employee['nak']." ";
echo $employee['nama']." ";
echo $employee['tgllahir']." ";
}
}
public function actionDataAnggota()
{
$anggota = \app\models\Anggota::find()
->all();
foreach ($anggota as $agt)
{
echo "<br>";
echo $agt->nak." ";
echo $agt->nama." ";
echo "(".$agt->tgllahir.")";
}
}
public function actionLog() {
Yii::trace('tracel log message', __METHOD__);
Yii::info('info log message');
Yii::warning('warning log message');
Yii::error('error log message');
}
}
| {
"content_hash": "97ec031fdc7cdbea86891b6d2887ccdb",
"timestamp": "",
"source": "github",
"line_count": 188,
"max_line_length": 107,
"avg_line_length": 22.069148936170212,
"alnum_prop": 0.4485418173053748,
"repo_name": "zickkeen/KopApp",
"id": "8f89f99de3f1a5b35ff85ad9338eecb40b042491",
"size": "4149",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "controllers/SiteController.php",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "203"
},
{
"name": "Batchfile",
"bytes": "1030"
},
{
"name": "CSS",
"bytes": "1364"
},
{
"name": "PHP",
"bytes": "92999"
}
],
"symlink_target": ""
} |
// Copyright (c) 2022, WNProject Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// clang-format off
#include "ElementTextSelection.h"
#include "WidgetTextInput.h"
namespace Rocket {
namespace Controls {
ElementTextSelection::ElementTextSelection(
Core::Context* _context, const Rocket::Core::String& tag)
: Rocket::Core::Element(_context, tag) {
widget = NULL;
}
ElementTextSelection::~ElementTextSelection() {}
// Set the widget that this selection element was created for.
void ElementTextSelection::SetWidget(WidgetTextInput* _widget) {
widget = _widget;
}
// Processes 'color' and 'background-color' property changes.
void ElementTextSelection::OnPropertyChange(
const Rocket::Core::PropertyNameList& changed_properties) {
Element::OnPropertyChange(changed_properties);
if (widget == NULL)
return;
// Check for a colour change.
if (changed_properties.find("color") != changed_properties.end() ||
changed_properties.find("background-color") != changed_properties.end()) {
widget->UpdateSelectionColours();
}
}
} // namespace Controls
} // namespace Rocket
| {
"content_hash": "693b5acac6cea6c29d243212278ffffc",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 80,
"avg_line_length": 27.837209302325583,
"alnum_prop": 0.7293233082706767,
"repo_name": "WNProject/WNFramework",
"id": "30eab42ce851576ae556e2ddc349fc886d994e6a",
"size": "2486",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "externals/librocket/Source/Controls/ElementTextSelection.cpp",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Assembly",
"bytes": "21585"
},
{
"name": "C",
"bytes": "178806"
},
{
"name": "C++",
"bytes": "4268348"
},
{
"name": "CMake",
"bytes": "163273"
},
{
"name": "GAP",
"bytes": "40323"
},
{
"name": "GLSL",
"bytes": "1516"
},
{
"name": "HLSL",
"bytes": "6436"
},
{
"name": "Objective-C",
"bytes": "14271"
},
{
"name": "PostScript",
"bytes": "394"
},
{
"name": "PowerShell",
"bytes": "3448"
},
{
"name": "Python",
"bytes": "66228"
},
{
"name": "Shell",
"bytes": "5208"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "a8c04294f95474a1e490d93408b9757f",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.307692307692308,
"alnum_prop": 0.6940298507462687,
"repo_name": "mdoering/backbone",
"id": "5c4e160617670322a368be5a63218a7963594fe2",
"size": "182",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Liliopsida/Poales/Restionaceae/Elegia/Elegia prominens/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
namespace Cosmos.Assembler {
public class Label : Instruction {
public string Comment
{
get
{
return mComment;
}
}
private readonly string mComment;
public Label(string aName, bool isGlobal = false)
: this(aName, string.Empty)
{
mIsGlobal = isGlobal;
}
public Label(string aName, string aComment) {
mName = aName;
if (aName.StartsWith(".")) {
mQualifiedName = LastFullLabel + aName;
} else {
mQualifiedName = aName;
// Some older code passes the whole label in the argument, so we check for any . in it.
// That assumes that the main prefix can never have a . in it.
// This code isnt perfect and doenst label X# code properly, but we don't care about
// auto emitted X# labels for now.
var xParts = aName.Split('.');
if (xParts.Length < 3) {
LastFullLabel = aName;
}
}
mComment = aComment;
}
public static string GetLabel(object aObject) {
Label xLabel = aObject as Label;
if (xLabel == null) {
return string.Empty;
}
return xLabel.Name;
}
public static string LastFullLabel { get; set; }
public string QualifiedName {
get
{
return mQualifiedName;
}
}
private readonly string mQualifiedName;
public bool IsGlobal {
get
{
return mIsGlobal;
}
}
private readonly bool mIsGlobal;
private readonly string mName;
public string Name {
get { return mName; }
}
public override void WriteText(Cosmos.Assembler.Assembler aAssembler, System.IO.TextWriter aOutput)
{
if (IsGlobal)
{
aOutput.Write("global ");
aOutput.WriteLine(QualifiedName);
}
aOutput.Write(QualifiedName);
aOutput.Write(":");
if (Comment.Length > 0)
{
aOutput.Write(" ;");
aOutput.Write(Comment);
}
}
public override bool IsComplete(Assembler aAssembler) {
return true;
}
public override void WriteData(Cosmos.Assembler.Assembler aAssembler, System.IO.Stream aOutput) { }
}
} | {
"content_hash": "173a2c2c6ebcdf31fc66066001e2149e",
"timestamp": "",
"source": "github",
"line_count": 92,
"max_line_length": 105,
"avg_line_length": 26.01086956521739,
"alnum_prop": 0.5390722941913916,
"repo_name": "Cyber4/Cosmos",
"id": "8c4f9372f33963c3d48aed1b88dc69e3def4e856",
"size": "2395",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "source/Cosmos.Assembler/Label.cs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "27066"
},
{
"name": "AutoIt",
"bytes": "814"
},
{
"name": "Batchfile",
"bytes": "3889"
},
{
"name": "C",
"bytes": "17776"
},
{
"name": "C#",
"bytes": "17307127"
},
{
"name": "C++",
"bytes": "7495"
},
{
"name": "F#",
"bytes": "1583"
},
{
"name": "HTML",
"bytes": "114818"
},
{
"name": "Inno Setup",
"bytes": "30874"
},
{
"name": "Pascal",
"bytes": "2597"
},
{
"name": "Python",
"bytes": "4886"
},
{
"name": "SourcePawn",
"bytes": "3948"
},
{
"name": "Visual Basic",
"bytes": "3336"
},
{
"name": "XS",
"bytes": "31167"
}
],
"symlink_target": ""
} |
title: Make Links Navigatable with HTML Access Keys
localeTitle: Сделать ссылки навигационными с ключами доступа к HTML
---
## Сделать ссылки навигационными с ключами доступа к HTML
Следуя инструкциям: Добавьте атрибут accesskey к обоим ссылкам и установите первый для «g» (для Гарфилда), а второй - «c» (для Chuck Norris). линии 8 и 16 становятся:
```css
<h2><a id="first" accesskey="g" href="">The Garfield Files: Lasagna as Training Fuel?</a></h2>
```
```css
<h2><a id="second" accesskey="c" href="">Is Chuck Norris a Cat Person?</a></h2>
```
Таким образом, ссылки вокруг двух статей в блогах, чтобы иметь быстрые клавиши, чтобы пользователи сайта могли быстро перейти к полной истории. | {
"content_hash": "37f0f81e4d2fdb2c020e3b8d9342ccdc",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 166,
"avg_line_length": 43.4375,
"alnum_prop": 0.7410071942446043,
"repo_name": "otavioarc/freeCodeCamp",
"id": "7f6a3e1feb6cf0c36e8b90831532336a5de3da91",
"size": "1010",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "guide/russian/certifications/responsive-web-design/applied-accessibility/make-links-navigatable-with-html-access-keys/index.md",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "35491"
},
{
"name": "HTML",
"bytes": "17600"
},
{
"name": "JavaScript",
"bytes": "777274"
}
],
"symlink_target": ""
} |
import ctypes
import windows.generated_def as gdef
from ..apiproxy import ApiProxy, NeededParameter
from ..error import fail_on_zero, no_error_check
class User32Proxy(ApiProxy):
APIDLL = "user32"
default_error_check = staticmethod(fail_on_zero)
# Window
@User32Proxy()
def EnumWindows(lpEnumFunc, lParam):
return EnumWindows.ctypes_function(lpEnumFunc, lParam)
@User32Proxy()
def GetParent(hWnd):
return GetParent.ctypes_function(hWnd)
@User32Proxy(error_check=no_error_check)
def GetWindowTextA(hWnd, lpString, nMaxCount):
return GetWindowTextA.ctypes_function(hWnd, lpString, nMaxCount)
@User32Proxy()
def GetWindowTextW(hWnd, lpString, nMaxCount):
return GetWindowTextW.ctypes_function(hWnd, lpString, nMaxCount)
@User32Proxy()
def FindWindowA(lpClassName, lpWindowName):
return FindWindowA.ctypes_function(lpClassName, lpWindowName)
@User32Proxy()
def FindWindowW(lpClassName, lpWindowName):
return FindWindowW.ctypes_function(lpClassName, lpWindowName)
@User32Proxy()
def GetWindowModuleFileNameA(hwnd, pszFileName, cchFileNameMax):
return GetWindowModuleFileNameA.ctypes_function(hwnd, pszFileName, cchFileNameMax)
@User32Proxy()
def GetWindowModuleFileNameW(hwnd, pszFileName, cchFileNameMax):
return GetWindowModuleFileNameW.ctypes_function(hwnd, pszFileName, cchFileNameMax)
@User32Proxy()
def EnumChildWindows(hWndParent, lpEnumFunc, lParam):
return EnumChildWindows.ctypes_function(hWndParent, lpEnumFunc, lParam)
@User32Proxy()
def GetClassInfoExA(hinst, lpszClass, lpwcx):
return GetClassInfoExA.ctypes_function(hinst, lpszClass, lpwcx)
@User32Proxy()
def GetClassInfoExW(hinst, lpszClass, lpwcx):
return GetClassInfoExW.ctypes_function(hinst, lpszClass, lpwcx)
@User32Proxy()
def GetWindowThreadProcessId(hWnd, lpdwProcessId):
return GetWindowThreadProcessId.ctypes_function(hWnd, lpdwProcessId)
@User32Proxy()
def WindowFromPoint(Point):
return WindowFromPoint.ctypes_function(Point)
@User32Proxy()
def GetWindowRect(hWnd, lpRect):
return GetWindowRect.ctypes_function(hWnd, lpRect)
@User32Proxy("RealGetWindowClassA")
def RealGetWindowClassA(hwnd, pszType, cchType=None):
if cchType is None:
cchType = len(pszType)
return RealGetWindowClassA.ctypes_function(hwnd, pszType, cchType)
@User32Proxy("RealGetWindowClassW")
def RealGetWindowClassW(hwnd, pszType, cchType=None):
if cchType is None:
cchType = len(pszType)
return RealGetWindowClassW.ctypes_function(hwnd, pszType, cchType)
@User32Proxy("GetClassNameA")
def GetClassNameA (hwnd, pszType, cchType=None):
if cchType is None:
cchType = len(pszType)
return GetClassNameA .ctypes_function(hwnd, pszType, cchType)
@User32Proxy("GetClassNameW")
def GetClassNameW (hwnd, pszType, cchType=None):
if cchType is None:
cchType = len(pszType)
return GetClassNameW .ctypes_function(hwnd, pszType, cchType)
## Windows Message
@User32Proxy()
def MessageBoxA(hWnd=0, lpText=NeededParameter, lpCaption=None, uType=0):
return MessageBoxA.ctypes_function(hWnd, lpText, lpCaption, uType)
@User32Proxy()
def MessageBoxW(hWnd=0, lpText=NeededParameter, lpCaption=None, uType=0):
return MessageBoxW.ctypes_function(hWnd, lpText, lpCaption, uType)
# Cursor
@User32Proxy()
def GetCursorPos(lpPoint):
return GetCursorPos.ctypes_function(lpPoint)
# System
# If the function succeeds, the return value is the requested system metric or configuration setting.
# If the function fails, the return value is 0. GetLastError does not provide extended error information.
# And 0 is also a valid return value.. Thanks a lot..
@User32Proxy(error_check=no_error_check)
def GetSystemMetrics(nIndex):
return GetSystemMetrics.ctypes_function(nIndex)
| {
"content_hash": "a9d87bae10ed15063317c9c845be8aec",
"timestamp": "",
"source": "github",
"line_count": 119,
"max_line_length": 105,
"avg_line_length": 31.57983193277311,
"alnum_prop": 0.7783395423097392,
"repo_name": "hakril/PythonForWindows",
"id": "98b16bc037d03c527f48a224565465096739ed6e",
"size": "3758",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "windows/winproxy/apis/user32.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "4087889"
}
],
"symlink_target": ""
} |
C AUTHORS: MIKE MYERS AND LUCIA SPAGNUOLO
C DATE: MAY 8, 1989
C Variables:
C SCORE -> an array of test scores
C SUM -> sum of the test scores
C COUNT -> counter of scores read in
C I -> loop counter
REAL FUNCTION COMPAV(SCORE,COUNT)
INTEGER SUM,COUNT,J,SCORE(5)
DO 30 I = 1,COUNT
SUM = SUM + SCORE(I)
30 CONTINUE
COMPAV = SUM/COUNT
END
PROGRAM AVENUM
C
C MAIN PROGRAM
C
C AUTHOR: LOIS BIGBIE
C DATE: MAY 15, 1990
C
C Variables:
C MAXNOS -> maximum number of input values
C NUMS -> an array of numbers
C COUNT -> exact number of input values
C AVG -> average returned by COMPAV
C I -> loop counter
C
PARAMETER(MAXNOS=5)
INTEGER I, COUNT
REAL NUMS(MAXNOS), AVG
COUNT = 0
DO 80 I = 1,MAXNOS
READ (5,*,END=100) NUMS(I)
COUNT = COUNT + 1
80 CONTINUE
100 AVG = COMPAV(NUMS, COUNT)
END
| {
"content_hash": "c7c9de8d4bef2b393b683f2654b8b4c3",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 56,
"avg_line_length": 27.295454545454547,
"alnum_prop": 0.4687760199833472,
"repo_name": "OS2World/DEV-FORTRAN-UTIL-ftnchek",
"id": "4defec6da4d6e15452c7cebebf8d5364d2ecd9d7",
"size": "1201",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "test/average.f",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
//
// ActivityDetailViewController.m
// iZJU
//
// Created by 爱机 on 12-9-9.
// Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//
#import "ActivityDetail.h"
#import "ActivityDetailCell.h"
#import "SVProgressHUD.h"
@interface ActivityDetail ()
@end
@implementation ActivityDetail
@synthesize tableView = _tableView;
@synthesize detailTitle = _detailTitle;
@synthesize detailTitleLabel = _detailTitleLabel;
- (id)initWithNibName:(NSString *)nibNameOrNil
bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil
bundle:nibBundleOrNil];
if (self) {
self.title = @"详情";
}
return self;
}
- (id)init
{
return [self initWithNibName:NSStringFromClass([self class])
bundle:nil];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
NSString *text = self.detailTitle;
/*
CGSize size = CGSizeMake(284, MAXFLOAT);
UIFont *font = [UIFont systemFontOfSize:17];
size = [text sizeWithFont:font
constrainedToSize:size
lineBreakMode:UILineBreakModeWordWrap];
size.height = MAX(size.height + 27, 49);
self.tableView.tableHeaderView.frame = CGRectMake(0, 0, size.width, size.height);
*/
self.detailTitleLabel.text = text;
[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"outsidenavbar.png"]
forBarMetrics:UIBarMetricsDefault];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
if (_detailInfo)
return;
_request = [ZJUOutsideDetailRequest dataRequest];
_request.ID = self.ID;
[[ZJUDataServer sharedServer] executeRequest:_request
delegate:self];
[SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeNone];
[SVProgressHUD setStatus:@"加载中..."];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[[ZJUDataServer sharedServer] cancelRequest:_request];
[SVProgressHUD dismiss];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - UITableView Datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
return _detailInfo.count;
}
- (CGFloat)tableView:(UITableView *)tableView
heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
int row = [indexPath row];
NSString *text = [[_detailInfo objectAtIndex:row] valueForKey:@"value"];
CGSize size = CGSizeMake(210, MAXFLOAT);
UIFont *font = [UIFont systemFontOfSize:12];
size = [text sizeWithFont:font
constrainedToSize:size
lineBreakMode:UILineBreakModeWordWrap];
return MAX(size.height + 22, 44);
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"ActivityDetailCell";
ActivityDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
NSArray *a = [[NSBundle mainBundle] loadNibNamed:@"ActivityDetailCell"
owner:self
options:nil];
for (id obj in a) {
if ([obj isKindOfClass:[ActivityDetailCell class]]) {
cell = (ActivityDetailCell*)obj;
break;
}
}
}
cell.backgroundColor = [UIColor yellowColor];
int index = [indexPath row];
NSDictionary *data = [_detailInfo objectAtIndex:index];
cell.content.text = [data valueForKey:@"value"];
cell.title.text = [[data valueForKey:@"key"] stringByAppendingString:@":"];
/*
switch (index) {
case 0:
cell.title.text = @"报名时间:";
break;
case 1:
cell.title.text = @"交流时间:";
break;
case 2:
cell.title.text = @"简介:";
break;
case 3:
cell.title.text = @"选拔条件:";
break;
case 4:
cell.title.text = @"费用:";
break;
default:
break;
}
*/
// Configure the cell...
return cell;
}
#pragma mark - ZJUDate delegate
- (void)requestDidFailed:(ZJUDataRequest *)request
withError:(NSError *)error
{
_request = nil;
[SVProgressHUD showErrorWithStatus:@"矮油,貌似失败了...再试试啦"];
}
- (void)requestDidFinished:(ZJUDataRequest *)request withData:(id)data
{
_request = nil;
ZJUOutsideDetailItem *item = (ZJUOutsideDetailItem*)data;
_detailInfo = item.details;
[self.tableView reloadData];
[SVProgressHUD dismiss];
}
@end
| {
"content_hash": "68e37c2c17315fc69f2c960d6f8b9868",
"timestamp": "",
"source": "github",
"line_count": 192,
"max_line_length": 105,
"avg_line_length": 26.84375,
"alnum_prop": 0.6255335661622041,
"repo_name": "iOS-Applications/iZJU",
"id": "dbc1d2d71dab199f65129f044c84ecf2c2b3418a",
"size": "5238",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "iOS-2.1.2/iZJU/ActivityDetail.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "154804"
},
{
"name": "HTML",
"bytes": "2517"
},
{
"name": "Java",
"bytes": "224878"
},
{
"name": "Objective-C",
"bytes": "2338574"
},
{
"name": "Objective-C++",
"bytes": "7658"
},
{
"name": "Ruby",
"bytes": "1707"
},
{
"name": "Shell",
"bytes": "1465"
}
],
"symlink_target": ""
} |
//
// AppController.m
// b-music
//
// Created by Sergey P on 01.10.13.
// Copyright (c) 2013 Sergey P. 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:
//
// 1. The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// 2. This Software cannot be used to archive or collect data such as (but not
// limited to) that of events, news, experiences and activities, for the
// purpose of any concept relating to diary/journal keeping.
//
// 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.
//
#import "AppController.h"
@implementation AppController{
NSDictionary * _currentTrack;
NSMutableArray * _viewPlaylist;//Playlist for table
NSMutableArray * _soundPlaylist;//Playlist for playing
NSMutableArray * _shufflePlaylist;
NSMutableDictionary * _imageList;
NSString * _currentTableRow;//For table whitch one cell is shown
BOOL _isInitialLoadingFinish;//Indicator starting app
// BOOL _userHoldKey;//global key event holding indicator
CGSize _windowSize;//size player
BOOL _scrobbleIndicator;//Shows send track has been sent or not
}
- (id)init
{
self = [super init];
if (self) {
_vkAPI=[[vkAPI alloc] init];
[_vkAPI setDelegate:self];
_lastfmAPI=[[LastfmAPI alloc] init];
[_lastfmAPI setDelegate:self];
_PC=[[PlayerController alloc] init];
[_PC setDelegate:self];
_currentTableRow=@"MainRow";
//Delegate notafications
[[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:self];
}
return self;
}
/*
* Preferences Delegate
*****************************/
#pragma mark Preferences Delegate
-(void)updateMenuBarIcon{
if (Settings.sharedInstance.settings.showIconMenubar) { //Add status bar
[self addStatusBarItem];
}else{
[self removeStatusBarItem];
}
}
-(void)updateDockIcon{
if(Settings.sharedInstance.settings.showArtworkDock){
NSImage * image = [_imageList objectForKey:_currentTrack];
[NSApp setApplicationIconImage: image];
}else{
[NSApp setApplicationIconImage: nil];
}
}
-(void)logoutVkFromPreferences{
[self.vkAPI logout];
}
/*
* Lastfm API Delegate
*****************************/
#pragma mark LastfmAPI Delegate
-(void)finishAuthorizeLastfm{
NSLog(@"FinishAuthorise lastfm");
if (!preferences) return;
[preferences updateProfileLastfm];
}
/*
* Api VK Delegate
*****************************/
#pragma mark vkAPI Delegate
-(void) finishAuthVK{
NSLog(@"Finish auth vk");
[self loadMainPlaylist];
[[[NSApp delegate] window] makeKeyAndOrderFront:self];
[self authorizationVK:NO];
if (!preferences) return;
[preferences updateProfileVk];
}
-(void) beginAuthVK{
[self authorizationVK:YES];
}
/*
* Window Methods
*
*****************************************************************************************/
#pragma mark Window Delegate
-(void)windowDidResize:(NSNotification *)notification{
NSEvent *event = [[NSApplication sharedApplication] currentEvent];
if ([event type]==6) {
id window=[[NSApp delegate] window];
_windowSize=[window frame].size;
}
}
-(void)windowDidBecomeMain:(NSNotification *)notification{ NSLog(@"DidBecomeMain");
//add b-music to menu window
[[NSApplication sharedApplication]addWindowsItem:[[NSApp delegate] window] title:@"b-music" filename:NO];
if (!_isInitialLoadingFinish) {
[self registerHandlerLinks];//Handler tokens /lastfm/vk
//Print settings
NSLog(@"%@",[Settings sharedInstance]);
//add status bar item
if (Settings.sharedInstance.settings.showIconMenubar) { //Add status bar
[self addStatusBarItem];
}
[_Controls0 setDelegate:self];//Set delegation method
[self addSubviewHelper:self.Controls0
slerve:self.Controls1];//Add view to superview (Controls1)
[self addSubviewHelper:self.BottomControls0
slerve:self.BottomControls1];//Add view to superview (Bottom)
[self.volume setProgress:Settings.sharedInstance.settings.volume];//Set volume on view
if (Settings.sharedInstance.settings.alwaysOnTop) { //Set Always on top
[[[NSApp delegate] window] setLevel:1000];
[[self.windowMenu itemWithTag:4] setState:1];
[[[NSApp delegate] window] setCollectionBehavior: NSWindowCollectionBehaviorCanJoinAllSpaces];
}
[[self.Controls2 viewWithTag:8] setFlag:Settings.sharedInstance.settings.shuffle];//Set shuffle on view
[[self.controlsMenu itemWithTag:5] setState:Settings.sharedInstance.settings.shuffle];//Set shuffle on top in menu
[[self.Controls2 viewWithTag:7] setFlag:Settings.sharedInstance.settings.repeat];//Set repeat on view
[[self.controlsMenu itemWithTag:6] setState:Settings.sharedInstance.settings.repeat];//Set repeat on top in menu
//Set search
[[self.searchField cell]setFocusRingType:NSFocusRingTypeNone];
//Setting size window
_windowSize=[[NSApp delegate] window].frame.size;
//TURN ON MENU
[self switchMainMenuItems:YES];
//Local Monitor hotkeys
[NSEvent addLocalMonitorForEventsMatchingMask: NSKeyDownMask
handler:^(NSEvent *event) { return [self localMonitorKeydownEvents:event];}];
//------MediaKey
if (!self.keyTap)
self.keyTap= [[SPMediaKeyTap alloc] initWithDelegate:self];
if([SPMediaKeyTap usesGlobalMediaKeyTap])
[self.keyTap startWatchingMediaKeys];
else
NSLog(@"Media key monitoring disabled");
//---EndMediakey
_isInitialLoadingFinish=YES;
[self loadMainPlaylist];
}
if (!Settings.sharedInstance.settings.token){
[self.vkAPI logout];
}
}
/*
* Notafication center delagate
*******************************/
#pragma mark Notafication Center
- (BOOL)userNotificationCenter:(NSUserNotificationCenter *)center
shouldPresentNotification:(NSUserNotification *)notification{
return YES;
}
-(void)userNotificationCenter:(NSUserNotificationCenter *)center
didActivateNotification:(NSUserNotification *)notification{
[self gotoCurrentTrack:nil];
[[[NSApp delegate] window] makeKeyWindow];
[[[NSApp delegate] window] makeMainWindow];
}
/*
* ControlsView Methods Delegate
***************************************/
-(void)isHovered:(BOOL)flag{
if (![_popoverVolume isShown]) {
[self removeSubviews];
if (flag) {
[self addSubviewHelper:self.Controls0 slerve:self.Controls2];
}else{
[self addSubviewHelper:self.Controls0 slerve:self.Controls1];
}
}
}
/*
* TEMP Methods
****************************************/
#pragma mark Temp
-(void)switchMainMenuItems:(BOOL)flag{
//whole menu controls
for (NSMenuItem * item in [self.controlsMenu itemArray])
[item setEnabled:flag];
//Whole dock menu
for (NSMenuItem * item in [self.dockMenu itemArray])
[item setEnabled:flag];
//Whole status menu
for (NSMenuItem * item in [self.statusMenu itemArray])
[item setEnabled:flag];
//Whole viewmenu
for (NSMenuItem * item in [self.viewMenu itemArray])
[item setEnabled:flag];
//Partly mainmenu
[[self.editMenu itemWithTag:3] setEnabled:flag];
}
-(void) authorizationVK:(BOOL)flag{
id window=[[NSApp delegate] window];
if ([window frame].size.height < 343|| [window frame].size.width < 223){
CGRect rect = NSMakeRect( [window frame].origin.x, [window frame].origin.y, 223, 343);
[window setFrame:rect display:YES animate:YES];
}
for (NSView * view in [[[[NSApp delegate] window] contentView] subviews]) {
[view setHidden:flag];
}
if (flag) {
[self addSubviewHelper:[[[NSApp delegate] window] contentView] slerve:self.lockView];
[self.lockView setHidden:!flag];
[self.PC pause];
}else{
[self.lockView removeFromSuperview];
}
[self switchMainMenuItems:!flag];
}
- (NSString *) URLEncodedString:(NSString*)str {
NSMutableString * output = [NSMutableString string];
const char * source = [str UTF8String];
unsigned long sourceLen = strlen(source);
for (int i = 0; i < sourceLen; ++i) {
const unsigned char thisChar = (const unsigned char)source[i];
if (false && thisChar == ' '){
[output appendString:@"+"];
} else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' ||
(thisChar >= 'a' && thisChar <= 'z') ||
(thisChar >= 'A' && thisChar <= 'Z') ||
(thisChar >= '0' && thisChar <= '9')) {
[output appendFormat:@"%c", thisChar];
} else {
[output appendFormat:@"%%%02X", thisChar];
}
}
return output;
}
-(void) addStatusBarItem{
statusItem=[[NSStatusBar systemStatusBar] statusItemWithLength:NSVariableStatusItemLength];
[statusItem setMenu:self.statusMenu];
[statusItem setHighlightMode:YES];
if(self.PC.player.rate==1.0)
[statusItem setImage:[NSImage imageNamed:@"pauseTemplate"]];
else
[statusItem setImage:[NSImage imageNamed:@"playTemplate"]];
}
-(void) removeStatusBarItem{
[[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
}
- (void)registerHandlerLinks{
[[NSAppleEventManager sharedAppleEventManager] setEventHandler:self
andSelector:@selector(getUrl:withReplyEvent:)
forEventClass:kInternetEventClass
andEventID:kAEGetURL];
}
- (void)getUrl:( NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent {
NSString * str=[[event paramDescriptorForKeyword:keyDirectObject] stringValue];
NSString * prefix=@"com.ttitt.b-music://";
if (![str hasPrefix:prefix]) return;
NSString * tokenString=[str substringFromIndex:prefix.length];
if ([tokenString characterAtIndex:0]==63) {
//LASTFM
[self.lastfmAPI parseTokenUsernameFormString:tokenString];
}else{
//VK
[self.vkAPI parseAccessTokenAndUserIdFormString:tokenString];
}
}
-(NSEvent*) localMonitorKeydownEvents:(NSEvent*)event{
// NSLog(@"%hu %@",event.keyCode, [[[NSApp keyWindow] firstResponder] className]);
// return event;
if (event.modifierFlags& NSCommandKeyMask) return event;
if ([[[NSApp keyWindow] firstResponder] isKindOfClass:[NSTextView class]]){
if (event.keyCode==125) {
[_tableview keyDown:event];
}else if (event.keyCode==126){
[_tableview keyDown:event];
}else if (event.keyCode==36 && _tableview.selectedRow>-1) {
[[[_tableview viewAtColumn:0 row:_tableview.selectedRow makeIfNecessary:NO] viewWithTag:1] performClick:nil];
return nil;
}
return event;
}
if (event.keyCode==36 && _tableview.selectedRow>-1) {
[[[_tableview viewAtColumn:0 row:_tableview.selectedRow makeIfNecessary:NO] viewWithTag:1] performClick:nil];
return nil;
}
[_tableview keyDown:event];
return nil;
}
//----------------------------------------------------------------//
+(void)initialize;
{
if([self class] != [AppController class]) return;
// Register defaults for the whitelist of apps that want to use media keys
[[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:
[SPMediaKeyTap defaultMediaKeyUserBundleIdentifiers], kMediaKeyUsingBundleIdentifiersDefaultsKey,
nil]];
}
-(void)mediaKeyTap:(SPMediaKeyTap*)keyTap receivedMediaKeyEvent:(NSEvent*)event;
{
NSAssert([event type] == NSSystemDefined && [event subtype] == SPSystemDefinedEventMediaKeys, @"Unexpected NSEvent in mediaKeyTap:receivedMediaKeyEvent:");
// here be dragons...
int keyCode = (([event data1] & 0xFFFF0000) >> 16);
int keyFlags = ([event data1] & 0x0000FFFF);
BOOL keyIsPressed = (((keyFlags & 0xFF00) >> 8)) == 0xA;
int keyRepeat = (keyFlags & 0x1);
if (keyIsPressed) {
NSString *debugString = [NSString stringWithFormat:@"%@", keyRepeat?@", repeated.":@"."];
switch (keyCode) {
case NX_KEYTYPE_PLAY:
[self play:nil];
debugString = [@"Play/pause pressed" stringByAppendingString:debugString];
break;
case NX_KEYTYPE_FAST:
if (!keyRepeat) [self next:nil];
debugString = [@"Ffwd pressed" stringByAppendingString:debugString];
break;
case NX_KEYTYPE_REWIND:
if (!keyRepeat) [self previous:nil];
debugString = [@"Rewind pressed" stringByAppendingString:debugString];
break;
default:
debugString = [NSString stringWithFormat:@"Key %d pressed%@", keyCode, debugString];
break;
// More cases defined in hidsystem/ev_keymap.h
}
NSLog(@"%@",debugString);
}
}
//----------------------------------------------------------------//
//-(void) globalMonitorKeydownEvents:(NSEvent*)event{
// if (!(event.modifierFlags&NSCommandKeyMask)) return;
//// NSLog(@"%li",event.data1);
// switch (event.data1) {
// case 1051136://Play
// [self play:nil];
// break;
// case 1247745://ffwd
// _userHoldKey=YES;
// double change1=[[self.BottomControls1 viewWithTag:2] doubleValue]+[[self.BottomControls1 viewWithTag:2] maxValue]*2/100;
// if (change1>[[self.BottomControls1 viewWithTag:2] maxValue]){
// [self next:nil];
// [[self.BottomControls1 viewWithTag:2] setProgress:0];
// [self.PC setRuntime:0];
// }else{
// [[self.BottomControls1 viewWithTag:2] setProgress:change1];
// [self.PC setRuntime:change1];
// }
//
// break;
// case 1248000://End ffwd
// if (!_userHoldKey) [self next:nil];
// _userHoldKey=NO;
// break;
// case 1313281://Rewind
// _userHoldKey=YES;
// double change=[[self.BottomControls1 viewWithTag:2] doubleValue]-[[self.BottomControls1 viewWithTag:2] maxValue]*2/100;
// if (change<0){
// [self previous:nil];
//
// [[self.BottomControls1 viewWithTag:2] setProgress:[[self.BottomControls1 viewWithTag:2] maxValue]];
// [self.PC setRuntime:[[self.BottomControls1 viewWithTag:2] maxValue]];
// }else{
// [[self.BottomControls1 viewWithTag:2] setProgress:change];
// [self.PC setRuntime:change];
// }
// break;
// case 1313536://End Rewind
// if (!_userHoldKey) [self previous:nil];
// _userHoldKey=NO;
// break;
// }
//}
-(void) removeSubviews{
[self.Controls1 removeFromSuperview];
[self.Controls2 removeFromSuperview];
}
-(void) addSubviewHelper:(NSView*)master slerve:(NSView*)slerve{
[master addSubview:slerve];
[slerve setFrame:[master bounds]];
[slerve setAutoresizingMask:NSViewWidthSizable|NSViewHeightSizable];
}
//Switcher to pause state in table view
-(void) setPauseStateForButton:(id)object state:(BOOL)flag{
NSInteger num=(int)[_viewPlaylist indexOfObject:object];
if (num>-1) [[[_tableview viewAtColumn:0 row:num makeIfNecessary:NO] viewWithTag:1] setPauseState:flag];
}
-(void) loadMainPlaylist{
id response =[self.vkAPI audio_get];
if (![self.vkAPI checkForErrorResponse:response]) return;//Some error happend
_viewPlaylist=[[NSMutableArray alloc] initWithArray:[[response objectForKey:@"response"] objectForKey:@"items"]];
_soundPlaylist=[_viewPlaylist mutableCopy];
if (Settings.sharedInstance.settings.shuffle) { _shufflePlaylist=[self.PC generateShufflePlaylist:_soundPlaylist]; }
[self.tableview performSelectorOnMainThread:@selector(reloadData)
withObject:nil
waitUntilDone:NO];
}
//Show preferences window
-(void) showPreferencesWichTag:(int)tag{
if (!preferences) {
preferences=[[Preferences alloc] initWithWindowNibName:@"Preferences"];
[preferences setDelegate:self];
}
preferences.showViewWithTag = tag;
[preferences showWindow:self];
}
/*
* Player Methods
*******************************/
#pragma mark Player
-(void)nextTrack{
[self next:self];
}
-(void) isPlayerPlaying:(BOOL)flag{
[[self.Controls2 viewWithTag:3] setPauseState:flag];
[self setPauseStateForButton:_currentTrack state:flag];
NSString * state;
if (flag) {
state=@"Pause";
[statusItem setImage:[NSImage imageNamed:@"pauseTemplate"]];
}else{
state=@"Play";
[statusItem setImage:[NSImage imageNamed:@"playTemplate"]];
}
[[self.controlsMenu itemWithTag:1] setTitle:state];
[[self.statusMenu itemWithTag:1] setTitle:state];
[[self.dockMenu itemWithTag:1] setTitle:state];
}
-(void) durationTrack:(double)duration{
NSString * title=[_currentTrack objectForKey:@"title"];
NSString * artist=[_currentTrack objectForKey:@"artist"];
NSString * durationString=[_currentTrack objectForKey:@"duration"];
[[self.Controls1 viewWithTag:1] setStringValue:title];//Set title for player
[[self.Controls1 viewWithTag:2] setStringValue:artist];//Set artist for player
[[self.BottomControls1 viewWithTag:2] setMaxValue:duration];//Set duration for slider
NSInteger num=(int)[_viewPlaylist indexOfObject:_currentTrack];
_scrobbleIndicator=NO;//Reset inicator
dispatch_queue_t downloadQueue = dispatch_queue_create("com.ttitt.b-music.lastfm", NULL);
dispatch_async(downloadQueue, ^{
if (num>-1){
NSButton * btnPlayTableCell=[[_tableview viewAtColumn:0 row:num makeIfNecessary:NO] viewWithTag:1];
//Set updateNowPlayng lastfm
[self.lastfmAPI track_updateNowPlaying:artist
track:title
duration:durationString];
NSImage * image;
//Search artwork
if (Settings.sharedInstance.settings.searchArtwork) {
image =[self.lastfmAPI getImageWithArtist:artist track:title size:3];
}
dispatch_async(dispatch_get_main_queue(), ^{
//set dock icon
if (Settings.sharedInstance.settings.showArtworkDock)
[NSApp setApplicationIconImage: image];
if (!_imageList)
_imageList = [[NSMutableDictionary alloc]init];
if (image){
[_imageList setObject:image forKey:_currentTrack];
[btnPlayTableCell setImage:image];
}
});
}
});
//Show notafications
if (Settings.sharedInstance.settings.showNotafications){
NSUserNotification *notification = [[NSUserNotification alloc] init];
notification.title = title;
notification.informativeText = artist;
[[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:notification];
}
}
-(void) bufferingTrack:(double)seconds{
[[self.BottomControls1 viewWithTag:2] setBuffering:seconds];
}
-(void) runtimeTrack:(double)seconds
secondsString:(NSString *)str
scrobble:(BOOL)scrobble{
[[self.BottomControls1 viewWithTag:2] setProgress:seconds];
[[self.BottomControls1 viewWithTag:1] setTitle:str];
if (!_scrobbleIndicator && scrobble) {
NSLog(@"SCROBBLE REUQUEST");
NSString * title=[_currentTrack objectForKey:@"title"];
NSString * artist=[_currentTrack objectForKey:@"artist"];
//Scrobbing request
[self.lastfmAPI track_scrobble:artist
track:title];
_scrobbleIndicator=YES;
}
}
/*
* TableView Methods
*
*****************************************************************************************/
#pragma mark Table
- (NSInteger)numberOfRowsInTableView:(NSTableView *)aTableView{ // count of table view items
return [_viewPlaylist count];
}
- (NSView *)tableView:(NSTableView *)tableView
viewForTableColumn:(NSTableColumn *)tableColumn
row:(NSInteger)row{
TableCellView * cellview=[tableView makeViewWithIdentifier:@"MainCell" owner:self];
id obj=[_viewPlaylist objectAtIndex:row];
[[cellview viewWithTag:2] setStringValue:[obj objectForKey:@"title"]];
[[cellview viewWithTag:3] setStringValue:[obj objectForKey:@"artist"]];
[[cellview viewWithTag:4] setTitle:[self.PC convertTime:[[obj objectForKey:@"duration"] doubleValue]]];
[[cellview viewWithTag:1] setPauseState:([obj isEqualTo:_currentTrack])? YES : NO];
if (_imageList) {
NSImage * image = [_imageList objectForKey:obj];
[[cellview viewWithTag:1] setImage:image];
}
return cellview;
}
-(void)tableViewSelectionDidChange:(NSNotification *)notification{
if ([_currentTableRow isEqualToString:@"MainRow"]){
[[self.editMenu itemWithTag:1] setEnabled:NO];
[[self.editMenu itemWithTag:2] setEnabled:YES];
}else if([_currentTableRow isEqualToString:@"SearchRow"]){
[[self.editMenu itemWithTag:1] setEnabled:YES];
[[self.editMenu itemWithTag:2] setEnabled:NO];
}
}
- (NSTableRowView *)tableView:(NSTableView *)tableView
rowViewForRow:(NSInteger)row{
return [tableView makeViewWithIdentifier:_currentTableRow owner:self];
}
#pragma mark -
#pragma mark IBAcrions
/*
*@ IBActions
*/
-(IBAction)supportLockScreenShowStore:(id)sender{
[self showPreferencesWichTag:4];
}
-(IBAction)supportLockScreen:(id)sender{ NSLog(@"SupportLock Screen");
[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://ttitt.ru/b-music/"]];
}
-(IBAction)loginAuthVk:(id)sender{ NSLog(@"loginAuthVk");
[self.vkAPI login];
}
-(IBAction)signupAuthVk:(id)sender{ NSLog(@"signupAuthVk");
[self.vkAPI signup];
}
-(IBAction)preferences:(id)sender{ NSLog(@"Preferences");
[self showPreferencesWichTag:0];
}
-(IBAction)play:(id)sender{ NSLog(@"Play");
[self setPauseStateForButton:_currentTrack state:NO];
if ([sender isKindOfClass:[PlayButtonCell class]]) {
NSInteger row=[_tableview rowForView:sender];
if (![_soundPlaylist isEqualTo:_viewPlaylist]){ //Chech to play new playlist
_soundPlaylist=[_viewPlaylist mutableCopy];
_shufflePlaylist=[self.PC generateShufflePlaylist:_soundPlaylist];
}
id obj=[_soundPlaylist objectAtIndex:row];
if ([obj isEqualTo:_currentTrack]) {
if(self.PC.player.rate==1.0) [self.PC pause];
else [self.PC play];
}else{
_currentTrack=[[NSDictionary alloc] initWithDictionary:obj];
[self.PC play:[_currentTrack objectForKey:@"url"]];
}
}else{
if (_currentTrack==nil) {
_currentTrack=[[NSDictionary alloc] initWithDictionary:[(Settings.sharedInstance.settings.shuffle)?_shufflePlaylist:_soundPlaylist objectAtIndex:0]];
NSLog(@"%@",_currentTrack);
[self.PC play:[_currentTrack objectForKey:@"url"]];
}else{
if(self.PC.player.rate==1.0) [self.PC pause];
else [self.PC play];
}
}
}
-(IBAction)next:(id)sender{ NSLog(@"Next");
[self setPauseStateForButton:_currentTrack state:NO];
NSInteger num=(int)[(Settings.sharedInstance.settings.shuffle)?_shufflePlaylist:_soundPlaylist indexOfObject:_currentTrack]+1;
if ([(Settings.sharedInstance.settings.shuffle)?_shufflePlaylist:_soundPlaylist count]-num < 1){
num=0;
if(Settings.sharedInstance.settings.shuffle){
_shufflePlaylist=[self.PC generateShufflePlaylist:_soundPlaylist];
}
}
_currentTrack=[[NSDictionary alloc] initWithDictionary:[(Settings.sharedInstance.settings.shuffle)?_shufflePlaylist:_soundPlaylist objectAtIndex:num]];
[self.PC play:[_currentTrack objectForKey:@"url"]];
}
-(IBAction)previous:(id)sender{ NSLog(@"Previous");
[self setPauseStateForButton:_currentTrack state:NO];
NSInteger num=(int)[(Settings.sharedInstance.settings.shuffle)?_shufflePlaylist:_soundPlaylist indexOfObject:_currentTrack];
if (num-1<0) num=0; else num-=1;
_currentTrack=[[NSDictionary alloc] initWithDictionary:[(Settings.sharedInstance.settings.shuffle)?_shufflePlaylist:_soundPlaylist objectAtIndex:num]];
[self.PC play:[_currentTrack objectForKey:@"url"]];
}
-(IBAction)decreaseVolume:(id)sender{ NSLog(@"Decrease volume");
Settings.sharedInstance.settings.volume-=0.1;
if (Settings.sharedInstance.settings.volume<0){ Settings.sharedInstance.settings.volume=0;}else if (Settings.sharedInstance.settings.volume==0){return;}
[self.volume setProgress:Settings.sharedInstance.settings.volume];
[self.PC.player setVolume:Settings.sharedInstance.settings.volume];
[Settings.sharedInstance saveSettings];
}
-(IBAction)increaseVolume:(id)sender{ NSLog(@"IncreaseVolume");
Settings.sharedInstance.settings.volume+=0.1;
if (Settings.sharedInstance.settings.volume>2){
Settings.sharedInstance.settings.volume=2;
}else if (Settings.sharedInstance.settings.volume==2){
return;
}
[self.volume setProgress:Settings.sharedInstance.settings.volume];
[self.PC.player setVolume:Settings.sharedInstance.settings.volume];
[Settings.sharedInstance saveSettings];
}
-(IBAction)mute:(id)sender{NSLog(@"Mute");
Settings.sharedInstance.settings.volume=0;
[self.volume setProgress:Settings.sharedInstance.settings.volume];
[self.PC.player setVolume:Settings.sharedInstance.settings.volume];
[Settings.sharedInstance saveSettings];
}
-(IBAction)shuffle:(id)sender{NSLog(@"Shuffle");
Settings.sharedInstance.settings.shuffle=!Settings.sharedInstance.settings.shuffle;
[[self.Controls2 viewWithTag:8] setFlag:Settings.sharedInstance.settings.shuffle];//Set shuffle on view
[[self.controlsMenu itemWithTag:5] setState:Settings.sharedInstance.settings.shuffle];//Set shuffle on menu
[Settings.sharedInstance saveSettings];
if (Settings.sharedInstance.settings.shuffle)
_shufflePlaylist=[self.PC generateShufflePlaylist:_soundPlaylist];
}
-(IBAction)repeat:(id)sender{NSLog(@"Repeat");
Settings.sharedInstance.settings.repeat=!Settings.sharedInstance.settings.repeat;
[[self.Controls2 viewWithTag:7] setFlag:Settings.sharedInstance.settings.repeat];//Set repear on view
[[self.controlsMenu itemWithTag:6] setState:Settings.sharedInstance.settings.repeat];//Set repeat on menu
[Settings.sharedInstance saveSettings];
}
-(IBAction)alwaysOnTop:(id)sender{NSLog(@"Always On top");
if (!Settings.sharedInstance.settings.alwaysOnTop) {
[[[NSApp delegate] window] setLevel:1000];
[[self.windowMenu itemWithTag:4] setState:1];
[[[NSApp delegate] window] setCollectionBehavior: NSWindowCollectionBehaviorCanJoinAllSpaces];
}else{
[[[NSApp delegate] window] setLevel:0];
[[self.windowMenu itemWithTag:4] setState:0];
[[[NSApp delegate] window] setCollectionBehavior: NSWindowCollectionBehaviorDefault];
}
Settings.sharedInstance.settings.alwaysOnTop=!Settings.sharedInstance.settings.alwaysOnTop;
[Settings.sharedInstance saveSettings];
}
-(IBAction)visitWebsite:(id)sender{ NSLog(@"visitwebsite");
[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://ttitt.ru/"]];
}
-(IBAction)more:(id)sender{ NSLog(@"More");
[[_tableview viewAtColumn:0 row:[_tableview rowForView:sender] makeIfNecessary:NO] slideCell:150];
[sender mouseExited:nil];
}
-(IBAction)buyInItunec:(id)sender{ NSLog(@"Buy In Itunes");
NSInteger row=[_tableview rowForView:sender];
id obj=[_viewPlaylist objectAtIndex:row];
NSString * artist=[obj objectForKey:@"artist"];
NSString * track=[obj objectForKey:@"title"];
NSString *strURL = [NSString stringWithFormat:@"http://ttitt.ru/track?artist=%@&title=%@",[self URLEncodedString:artist], [self URLEncodedString:track]];
[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:strURL]];
}
-(IBAction)addTrack:(id)sender{NSLog(@"AddtTrack");
NSInteger row=([sender isKindOfClass:[NSMenuItem class]])?[_tableview selectedRow]:[_tableview rowForView:sender];
id obj=[_viewPlaylist objectAtIndex:row];
BOOL result=[self.vkAPI audio_addWithOwner_id:[obj objectForKey:@"owner_id"]
idTrack:[obj objectForKey:@"id"]];
if (!result) return;// Some error happend
[[[_tableview rowViewAtRow:row makeIfNecessary:NO] viewWithTag:4] setComplete];
//[[_tableview viewAtColumn:0 row:_row makeIfNecessary:NO] slideCell:0];
}
-(IBAction)removeTrack:(id)sender{NSLog(@"RemoveTrack");
NSInteger row=([sender isKindOfClass:[NSMenuItem class]])?[_tableview selectedRow]:[_tableview rowForView:sender];
id obj=[_viewPlaylist objectAtIndex:row];
BOOL result=[self.vkAPI audio_deleteWithOwner_id:[obj objectForKey:@"owner_id"]
idTrack:[obj objectForKey:@"id"]];
if (!result) return;// Some error happend
if ([_soundPlaylist isEqualTo:_viewPlaylist]){ //Chech to play new playlist
[_soundPlaylist removeObjectAtIndex:row];
}
[_viewPlaylist removeObjectAtIndex:row];
[_tableview removeRowsAtIndexes:[[NSIndexSet alloc] initWithIndex:row] withAnimation:NSTableViewAnimationSlideUp];
}
-(IBAction)showVolume:(id)sender{ NSLog(@"ShowVolume");
[self.popoverVolume showRelativeToRect:[sender bounds] ofView:sender preferredEdge:NSMaxXEdge];
}
-(IBAction)volume:(id)sender{NSLog(@"Volume");
NSEvent *event = [[NSApplication sharedApplication] currentEvent];
BOOL endingDrag = event.type == NSLeftMouseUp;
[sender setProgress:[sender floatValue]];
Settings.sharedInstance.settings.volume=[sender floatValue];
[self.PC.player setVolume:[sender floatValue]];
if(endingDrag) [Settings.sharedInstance saveSettings];
}
-(IBAction)runtime:(id)sender{NSLog(@"Runtime");
NSEvent *event = [[NSApplication sharedApplication] currentEvent];
BOOL endingDrag = event.type == NSLeftMouseUp;
[sender setProgress:[sender doubleValue]];
if(endingDrag) [self.PC setRuntime:[sender doubleValue]];
}
-(IBAction)switchRuntime:(id)sender{ NSLog(@"Switch Runtime");
Settings.sharedInstance.settings.runTime=!Settings.sharedInstance.settings.runTime;
[Settings.sharedInstance saveSettings];
}
-(IBAction)showSearch:(id)sender{NSLog(@"ShowSearch");
//Set search view height
if ([self.searchViewHeight constant]>0) {
[[self.searchViewHeight animator] setConstant:0];
[self.searchField setEnabled:NO];
[[self.Controls2 viewWithTag:6] setFlag:NO];//Show search button change color
}else{
[[self.searchViewHeight animator] setConstant:30];
[self.searchField setEnabled:YES];
[self.searchField selectText:nil];
[[self.Controls2 viewWithTag:6] setFlag:YES];//Show search button change color
}
}
-(IBAction)search:(id)sender{NSLog(@"Search");
if ([sender stringValue].length!=0) {
_currentTableRow=@"SearchRow";
id response =[self.vkAPI audio_searchWithSearchQuery:[sender stringValue]];
if (![self.vkAPI checkForErrorResponse:response]) return;//Some error happend
_viewPlaylist=[[NSMutableArray alloc] initWithArray:[[response objectForKey:@"response"] objectForKey:@"items"]];
[self.tableview performSelectorOnMainThread:@selector(reloadData)
withObject:nil
waitUntilDone:NO];
if([[sender stringValue] isEqual:@"Sergey Popov"]){[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"https://vk.com/serji"]];}
}else{
[self loadMainPlaylist];
_currentTableRow=@"MainRow";
}
}
-(IBAction)showPlaylist:(id)sender{ NSLog(@"ShowPlaylist");
CGRect rect;
CGFloat widthPlayer=250;
CGFloat heightPlayer=70;
id window=[[NSApp delegate] window];
if ([sender isKindOfClass:[NSMenuItem class]]) {
if ([sender tag]==2) {
if ([self.searchViewHeight constant]>0)
heightPlayer+=30;
CGFloat xPos=[window frame].origin.x + [window frame].size.width - widthPlayer;
CGFloat yPos=[window frame].origin.y + [window frame].size.height - heightPlayer;
rect=NSMakeRect(xPos, yPos, widthPlayer, heightPlayer);
}else if ([sender tag]==1){
CGFloat xPos=[window frame].origin.x + [window frame].size.width - _windowSize.width;
CGFloat yPos=[window frame].origin.y + [window frame].size.height - _windowSize.height;
rect=NSMakeRect(xPos, yPos, _windowSize.width, _windowSize.height);
}else if ([sender tag]==3){
rect=[[NSScreen mainScreen] visibleFrame];
}
}else{
if ([self.searchViewHeight constant]>0){
heightPlayer+=30;
}
if ([window frame].size.width==widthPlayer && [window frame].size.height==heightPlayer) {
CGFloat xPos=[window frame].origin.x + [window frame].size.width - _windowSize.width;
CGFloat yPos=[window frame].origin.y + [window frame].size.height - _windowSize.height;
rect=NSMakeRect(xPos, yPos, _windowSize.width, _windowSize.height);
}else{
CGFloat xPos=[window frame].origin.x + [window frame].size.width - widthPlayer;
CGFloat yPos=[window frame].origin.y + [window frame].size.height - heightPlayer;
rect=NSMakeRect(xPos, yPos, widthPlayer, heightPlayer);
}
}
[window setFrame:rect display:YES animate:YES];
}
-(IBAction)minimize:(id)sender{NSLog(@"Minimize");
id window=[[NSApp delegate] window];
[window miniaturize:self];
}
-(IBAction)gotoCurrentTrack:(id)sender{ NSLog(@"Go to Current Track");
int selectTrack=(int)[_viewPlaylist indexOfObject:_currentTrack];
[_tableview scrollRowToVisible:selectTrack];
[_tableview selectRowIndexes:[NSIndexSet indexSetWithIndex:selectTrack] byExtendingSelection:NO];
}
-(IBAction)close:(id)sender{ NSLog(@"Close");
[[[NSApp delegate] window] close];
}
-(IBAction)logout:(id)sender{ NSLog(@"Logout");
[self.vkAPI logout];
}
@end
| {
"content_hash": "990e3ac0e40eb0d2f77a4c0ffca48bbb",
"timestamp": "",
"source": "github",
"line_count": 979,
"max_line_length": 161,
"avg_line_length": 37.36772216547497,
"alnum_prop": 0.6384932892327038,
"repo_name": "Serjip/b-music",
"id": "7b53070f4998ca8ab5bf9d439b96e23387113b77",
"size": "36583",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "b-music/AppController.m",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Objective-C",
"bytes": "265351"
}
],
"symlink_target": ""
} |
require 'spec_helper'
describe 'apache::mod::dev', :type => :class do
[
['RedHat', '6'],
['Debian', '6'],
['FreeBSD', '9'],
].each do |osfamily, operatingsystemrelease|
if osfamily == 'FreeBSD'
let :pre_condition do
'include apache::package'
end
end
context "on a #{osfamily} OS" do
let :facts do
{
:osfamily => osfamily,
:operatingsystemrelease => operatingsystemrelease,
}
end
it { should include_class('apache::dev') }
end
end
end
| {
"content_hash": "81d37ad0a51e6cae22e79009e719d648",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 60,
"avg_line_length": 24.26086956521739,
"alnum_prop": 0.53584229390681,
"repo_name": "HTML24/FoosLeader",
"id": "eee0bb1fa608dd78c3f367aed96c39a1ce71f604",
"size": "558",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "puppet/modules/apache/spec/classes/mod/dev_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "2634"
},
{
"name": "Batchfile",
"bytes": "98"
},
{
"name": "CSS",
"bytes": "359295"
},
{
"name": "HTML",
"bytes": "110960"
},
{
"name": "JavaScript",
"bytes": "457447"
},
{
"name": "PHP",
"bytes": "157042"
},
{
"name": "Pascal",
"bytes": "1092"
},
{
"name": "Puppet",
"bytes": "380523"
},
{
"name": "Ruby",
"bytes": "395850"
},
{
"name": "Shell",
"bytes": "82041"
}
],
"symlink_target": ""
} |
//
// NSDictionary+Additions.h
#import <Foundation/Foundation.h>
@interface NSDictionary (Additions)
- (id)lastObject;
@end
| {
"content_hash": "d41164d7829fdf76abd7f627de991ff9",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 35,
"avg_line_length": 11.818181818181818,
"alnum_prop": 0.7230769230769231,
"repo_name": "AlexandrKurochkin/iOSTools",
"id": "87dff4e0b58fc1f1d5b5ee9247eea7b21054c598",
"size": "1645",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "iOSTools/ObjcAdditions/NSDictionary+Additions.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "1877"
},
{
"name": "Objective-C",
"bytes": "134372"
},
{
"name": "Ruby",
"bytes": "740"
}
],
"symlink_target": ""
} |
$(document).ready(function() {
console.log('jQuery is loaded');
}); | {
"content_hash": "118a83b02dbef558b8e8e6c7adc038f5",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 36,
"avg_line_length": 23.666666666666668,
"alnum_prop": 0.6338028169014085,
"repo_name": "gianpaj/pomodoro",
"id": "4c24363fe2ed990a3afe080b36f8f90d254a3ece",
"size": "71",
"binary": false,
"copies": "1",
"ref": "refs/heads/w1",
"path": "public/js/main.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "41"
},
{
"name": "HTML",
"bytes": "1308"
},
{
"name": "JavaScript",
"bytes": "2225"
}
],
"symlink_target": ""
} |
"""
core.configs
"""
__author__ = 'Rnd495'
__all__ = ['Configs', 'ConfigsError']
import os
import json
# check "config/now.conf"
# if not exists, create by copying "config/default.conf" to "config/now.conf"
ROOT_PATH = os.path.split(os.path.split(__file__)[0])[0]
CONFIG_PATH_NOW = os.path.join(ROOT_PATH, "config/now.conf")
CONFIG_PATH_DEFAULT = os.path.join(ROOT_PATH, "config/default.conf")
CONFIG_NOTNULL = [
'database_url',
'init_admin_username',
'init_admin_password'
]
if not os.path.exists(CONFIG_PATH_NOW):
# try to copy from default
import shutil
shutil.copy(CONFIG_PATH_DEFAULT, CONFIG_PATH_NOW)
del shutil
class ConfigsError(Exception):
"""
ConfigsError
"""
def __init__(self, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
self.error_line = kwargs.get('line', None)
class Configs(object):
"""
Configs
"""
def __init__(self, config_file_name):
with open(config_file_name, 'rb') as file_handle:
for line in file_handle:
line = line.strip()
# lines startswith '#' is commit
if not line or line.startswith('#'):
continue
separator_index = line.find('=')
if separator_index < 0:
raise ConfigsError('ConfigsError: config line syntax error with "%s"' % line)
name = line[:separator_index].strip()
value = line[separator_index + 1:].strip()
# accept upper case
if value.lower() in ('true', 'false'):
value = value.lower()
# param type parse
try:
data = json.loads(value)
self.__dict__[name] = data
except ValueError:
raise ConfigsError('ConfigsError: unknown data format "%s"' % value)
for name in CONFIG_NOTNULL:
if self.__dict__.get(name, None) is None:
raise ConfigsError('ConfigsError: property "%s" is not set' % name)
@staticmethod
def instance(config_file_name=None):
if not hasattr(Configs, "_instance"):
Configs._instance = Configs(config_file_name or CONFIG_PATH_NOW)
return Configs._instance
if __name__ == '__main__':
print "NOW_CONFIGS: "
print "path:", CONFIG_PATH_NOW
for k, v in Configs.instance().__dict__.iteritems():
print k, "=", v | {
"content_hash": "3ddd8fcd283098c9368306493dc797be",
"timestamp": "",
"source": "github",
"line_count": 76,
"max_line_length": 97,
"avg_line_length": 32.60526315789474,
"alnum_prop": 0.5585149313962873,
"repo_name": "SakuraSa/TenhouLoggerX",
"id": "fb8d38a9d4279160b1b528e866dd9747833490dc",
"size": "2516",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "core/configs.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1412"
},
{
"name": "HTML",
"bytes": "19738"
},
{
"name": "JavaScript",
"bytes": "11684"
},
{
"name": "Python",
"bytes": "57478"
}
],
"symlink_target": ""
} |
package de.codecentric.ebss.model;
public class Recipient {
private String firstName;
private String lastName;
private Address invoiceAdress;
private Address deliveryAdress;
public Recipient(String firstName, String lastName, Address invoiceAdress, Address deliveryAdress) {
this.firstName = firstName;
this.lastName = lastName;
this.invoiceAdress = invoiceAdress;
this.deliveryAdress = deliveryAdress;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Address getInvoiceAdress() {
return invoiceAdress;
}
public void setInvoiceAdress(Address invoiceAdress) {
this.invoiceAdress = invoiceAdress;
}
public Address getDeliveryAdress() {
return deliveryAdress;
}
public void setDeliveryAdress(Address deliveryAdress) {
this.deliveryAdress = deliveryAdress;
}
}
| {
"content_hash": "8244beb6a0a22bda78d6f9121df3fb1f",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 101,
"avg_line_length": 24.75609756097561,
"alnum_prop": 0.7684729064039408,
"repo_name": "codecentric/event-based-shopping-system",
"id": "25225dc55ae2978d1b5b56016d1ef73501b83445",
"size": "1015",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "commodities-reservation-service/src/main/java/de/codecentric/ebss/model/Recipient.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "10350"
},
{
"name": "Java",
"bytes": "29040"
}
],
"symlink_target": ""
} |
<?php
namespace Stripe\Exception\OAuth;
/**
* InvalidGrantException is thrown when a specified code doesn't exist, is
* expired, has been used, or doesn't belong to you; a refresh token doesn't
* exist, or doesn't belong to you; or if an API key's mode (live or test)
* doesn't match the mode of a code or refresh token.
*/
class InvalidGrantException extends OAuthErrorException
{
}
| {
"content_hash": "e42656f6fb127f03a1416f40f9acf17d",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 76,
"avg_line_length": 30.076923076923077,
"alnum_prop": 0.7416879795396419,
"repo_name": "unaio/una",
"id": "898b3a77618525c9d322c71e82435605f4bf8433",
"size": "391",
"binary": false,
"copies": "36",
"ref": "refs/heads/master",
"path": "upgrade/files/12.1.0-13.0.0.A1/files/plugins/stripe/stripe-php/lib/Exception/OAuth/InvalidGrantException.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "9522763"
},
{
"name": "Dockerfile",
"bytes": "2367"
},
{
"name": "HTML",
"bytes": "6194660"
},
{
"name": "JavaScript",
"bytes": "24733694"
},
{
"name": "Less",
"bytes": "3020615"
},
{
"name": "Makefile",
"bytes": "1196"
},
{
"name": "PHP",
"bytes": "158741504"
},
{
"name": "Ruby",
"bytes": "210"
},
{
"name": "Shell",
"bytes": "3327"
},
{
"name": "Smarty",
"bytes": "3461"
}
],
"symlink_target": ""
} |
package prediction
// Copyright (c) Microsoft and contributors. 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.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/date"
"github.com/satori/go.uuid"
)
// BoundingBox ...
type BoundingBox struct {
Left *float64 `json:"left,omitempty"`
Top *float64 `json:"top,omitempty"`
Width *float64 `json:"width,omitempty"`
Height *float64 `json:"height,omitempty"`
}
// ImagePrediction ...
type ImagePrediction struct {
autorest.Response `json:"-"`
ID *uuid.UUID `json:"id,omitempty"`
Project *uuid.UUID `json:"project,omitempty"`
Iteration *uuid.UUID `json:"iteration,omitempty"`
Created *date.Time `json:"created,omitempty"`
Predictions *[]Model `json:"predictions,omitempty"`
}
// ImageURL ...
type ImageURL struct {
URL *string `json:"url,omitempty"`
}
// Model ...
type Model struct {
Probability *float64 `json:"probability,omitempty"`
TagID *uuid.UUID `json:"tagId,omitempty"`
TagName *string `json:"tagName,omitempty"`
BoundingBox *BoundingBox `json:"boundingBox,omitempty"`
}
| {
"content_hash": "bf50a04503e39e6b4ee89aab06e0e26e",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 84,
"avg_line_length": 33.36363636363637,
"alnum_prop": 0.7068119891008174,
"repo_name": "sferich888/origin",
"id": "2f0051cfe5f59d74d686ebefd006e37a78b3b4cf",
"size": "1835",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "vendor/github.com/Azure/azure-sdk-for-go/services/cognitiveservices/v1.1/customvision/prediction/models.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Awk",
"bytes": "921"
},
{
"name": "DIGITAL Command Language",
"bytes": "117"
},
{
"name": "Dockerfile",
"bytes": "9805"
},
{
"name": "Go",
"bytes": "13133534"
},
{
"name": "Makefile",
"bytes": "8268"
},
{
"name": "Python",
"bytes": "16068"
},
{
"name": "Shell",
"bytes": "825010"
}
],
"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 (1.8.0_151) on Wed Jul 17 13:50:51 MST 2019 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Interface org.wildfly.swarm.config.mail.mail_session.SMTPServerConsumer (BOM: * : All 2.5.0.Final API)</title>
<meta name="date" content="2019-07-17">
<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="Uses of Interface org.wildfly.swarm.config.mail.mail_session.SMTPServerConsumer (BOM: * : All 2.5.0.Final API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../org/wildfly/swarm/config/mail/mail_session/SMTPServerConsumer.html" title="interface in org.wildfly.swarm.config.mail.mail_session">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../../overview-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 class="aboutLanguage">Thorntail API, 2.5.0.Final</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/wildfly/swarm/config/mail/mail_session/class-use/SMTPServerConsumer.html" target="_top">Frames</a></li>
<li><a href="SMTPServerConsumer.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>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Interface org.wildfly.swarm.config.mail.mail_session.SMTPServerConsumer" class="title">Uses of Interface<br>org.wildfly.swarm.config.mail.mail_session.SMTPServerConsumer</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../../org/wildfly/swarm/config/mail/mail_session/SMTPServerConsumer.html" title="interface in org.wildfly.swarm.config.mail.mail_session">SMTPServerConsumer</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.wildfly.swarm.config.mail">org.wildfly.swarm.config.mail</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#org.wildfly.swarm.config.mail.mail_session">org.wildfly.swarm.config.mail.mail_session</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="#org.wildfly.swarm.mail">org.wildfly.swarm.mail</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.wildfly.swarm.config.mail">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../org/wildfly/swarm/config/mail/mail_session/SMTPServerConsumer.html" title="interface in org.wildfly.swarm.config.mail.mail_session">SMTPServerConsumer</a> in <a href="../../../../../../../org/wildfly/swarm/config/mail/package-summary.html">org.wildfly.swarm.config.mail</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../org/wildfly/swarm/config/mail/package-summary.html">org.wildfly.swarm.config.mail</a> with parameters of type <a href="../../../../../../../org/wildfly/swarm/config/mail/mail_session/SMTPServerConsumer.html" title="interface in org.wildfly.swarm.config.mail.mail_session">SMTPServerConsumer</a></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>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../../org/wildfly/swarm/config/mail/MailSession.html" title="type parameter in MailSession">T</a></code></td>
<td class="colLast"><span class="typeNameLabel">MailSession.</span><code><span class="memberNameLink"><a href="../../../../../../../org/wildfly/swarm/config/mail/MailSession.html#smtpServer-org.wildfly.swarm.config.mail.mail_session.SMTPServerConsumer-">smtpServer</a></span>(<a href="../../../../../../../org/wildfly/swarm/config/mail/mail_session/SMTPServerConsumer.html" title="interface in org.wildfly.swarm.config.mail.mail_session">SMTPServerConsumer</a> consumer)</code>
<div class="block">Mail session server</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="org.wildfly.swarm.config.mail.mail_session">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../org/wildfly/swarm/config/mail/mail_session/SMTPServerConsumer.html" title="interface in org.wildfly.swarm.config.mail.mail_session">SMTPServerConsumer</a> in <a href="../../../../../../../org/wildfly/swarm/config/mail/mail_session/package-summary.html">org.wildfly.swarm.config.mail.mail_session</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../org/wildfly/swarm/config/mail/mail_session/package-summary.html">org.wildfly.swarm.config.mail.mail_session</a> that return <a href="../../../../../../../org/wildfly/swarm/config/mail/mail_session/SMTPServerConsumer.html" title="interface in org.wildfly.swarm.config.mail.mail_session">SMTPServerConsumer</a></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>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>default <a href="../../../../../../../org/wildfly/swarm/config/mail/mail_session/SMTPServerConsumer.html" title="interface in org.wildfly.swarm.config.mail.mail_session">SMTPServerConsumer</a><<a href="../../../../../../../org/wildfly/swarm/config/mail/mail_session/SMTPServerConsumer.html" title="type parameter in SMTPServerConsumer">T</a>></code></td>
<td class="colLast"><span class="typeNameLabel">SMTPServerConsumer.</span><code><span class="memberNameLink"><a href="../../../../../../../org/wildfly/swarm/config/mail/mail_session/SMTPServerConsumer.html#andThen-org.wildfly.swarm.config.mail.mail_session.SMTPServerConsumer-">andThen</a></span>(<a href="../../../../../../../org/wildfly/swarm/config/mail/mail_session/SMTPServerConsumer.html" title="interface in org.wildfly.swarm.config.mail.mail_session">SMTPServerConsumer</a><<a href="../../../../../../../org/wildfly/swarm/config/mail/mail_session/SMTPServerConsumer.html" title="type parameter in SMTPServerConsumer">T</a>> after)</code> </td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../org/wildfly/swarm/config/mail/mail_session/package-summary.html">org.wildfly.swarm.config.mail.mail_session</a> with parameters of type <a href="../../../../../../../org/wildfly/swarm/config/mail/mail_session/SMTPServerConsumer.html" title="interface in org.wildfly.swarm.config.mail.mail_session">SMTPServerConsumer</a></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>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>default <a href="../../../../../../../org/wildfly/swarm/config/mail/mail_session/SMTPServerConsumer.html" title="interface in org.wildfly.swarm.config.mail.mail_session">SMTPServerConsumer</a><<a href="../../../../../../../org/wildfly/swarm/config/mail/mail_session/SMTPServerConsumer.html" title="type parameter in SMTPServerConsumer">T</a>></code></td>
<td class="colLast"><span class="typeNameLabel">SMTPServerConsumer.</span><code><span class="memberNameLink"><a href="../../../../../../../org/wildfly/swarm/config/mail/mail_session/SMTPServerConsumer.html#andThen-org.wildfly.swarm.config.mail.mail_session.SMTPServerConsumer-">andThen</a></span>(<a href="../../../../../../../org/wildfly/swarm/config/mail/mail_session/SMTPServerConsumer.html" title="interface in org.wildfly.swarm.config.mail.mail_session">SMTPServerConsumer</a><<a href="../../../../../../../org/wildfly/swarm/config/mail/mail_session/SMTPServerConsumer.html" title="type parameter in SMTPServerConsumer">T</a>> after)</code> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="org.wildfly.swarm.mail">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../org/wildfly/swarm/config/mail/mail_session/SMTPServerConsumer.html" title="interface in org.wildfly.swarm.config.mail.mail_session">SMTPServerConsumer</a> in <a href="../../../../../../../org/wildfly/swarm/mail/package-summary.html">org.wildfly.swarm.mail</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subinterfaces, and an explanation">
<caption><span>Subinterfaces of <a href="../../../../../../../org/wildfly/swarm/config/mail/mail_session/SMTPServerConsumer.html" title="interface in org.wildfly.swarm.config.mail.mail_session">SMTPServerConsumer</a> in <a href="../../../../../../../org/wildfly/swarm/mail/package-summary.html">org.wildfly.swarm.mail</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Interface and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>interface </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../org/wildfly/swarm/mail/EnhancedSMTPServerConsumer.html" title="interface in org.wildfly.swarm.mail">EnhancedSMTPServerConsumer</a></span></code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= 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><a href="../../../../../../../org/wildfly/swarm/config/mail/mail_session/SMTPServerConsumer.html" title="interface in org.wildfly.swarm.config.mail.mail_session">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../../overview-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 class="aboutLanguage">Thorntail API, 2.5.0.Final</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/wildfly/swarm/config/mail/mail_session/class-use/SMTPServerConsumer.html" target="_top">Frames</a></li>
<li><a href="SMTPServerConsumer.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>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2019 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
| {
"content_hash": "4dbd841db29de4c24f56cd5ddba39027",
"timestamp": "",
"source": "github",
"line_count": 227,
"max_line_length": 667,
"avg_line_length": 59.22907488986784,
"alnum_prop": 0.665823726292302,
"repo_name": "wildfly-swarm/wildfly-swarm-javadocs",
"id": "888633c32216ff9d3623945beaa17c3455472668",
"size": "13445",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "2.5.0.Final/apidocs/org/wildfly/swarm/config/mail/mail_session/class-use/SMTPServerConsumer.html",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
import os.path
import sys
import logging
from typing import List
import pygame
from .scenes.loginscene import LoginScene
from .config import config
class Game:
def __init__(self):
self.logger = logging.getLogger(__name__)
pygame.init()
self._clock = pygame.time.Clock()
# TODO: window icon doesn't show
icon_path = os.path.abspath(os.path.join(config.get(section="hacc", option="asset_dir"), "icon.png"))
icon = pygame.image.load(icon_path)
pygame.display.set_icon(icon)
self._width = config.getint(section="hacc", option="width")
self._height = config.getint(section="hacc", option="height")
self._display = pygame.display.set_mode((self._width, self._height),
pygame.DOUBLEBUF,
config.getint(section="hacc", option="depth"))
self._fps = config.getint(section="hacc", option="fps")
pygame.display.set_caption("hacc")
self._running = True
loginmenu = LoginScene(width=self._width, height=self._height)
self._scene = loginmenu
def _handle_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
self._quit()
elif event.type == pygame.KEYDOWN:
# if event.key == K_LEFT:
# if self.snake.direction != 1:
# self.snake.direction = 0
# elif event.key == K_RIGHT:
# if self.snake.direction != 0:
# self.snake.direction = 1
# elif event.key == K_UP:
# if self.snake.direction != 3:
# self.snake.direction = 2
# elif event.key == K_DOWN:
# if self.snake.direction != 2:
# self.snake.direction = 3
# elif event.key == K_ESCAPE:
# pygame.event.post(pygame.event.Event(QUIT))
pass
def _update(self):
self._scene.update()
def _render(self):
self._display.fill((0, 0, 0))
scene_surface = self._scene.render()
self._display.blit(scene_surface, (0, 0))
def mainloop(self):
while self._running:
self._handle_events()
self._update()
self._render()
self._clock.tick(self._fps)
def _quit(self, errors: List = None):
"""
Shutdow the game and pygame nicely.
:param errors: List of errors.
:return:
"""
pygame.quit()
if errors is None:
sys.exit(0)
else:
# TODO: handle errors
sys.exit(1)
| {
"content_hash": "0558f1cde2e644919a73a6264788249d",
"timestamp": "",
"source": "github",
"line_count": 90,
"max_line_length": 109,
"avg_line_length": 30.81111111111111,
"alnum_prop": 0.5106382978723404,
"repo_name": "XenGi/hacc",
"id": "df0793c7ab21c90dcbab1bf106f2de3783bd54a7",
"size": "2773",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "hacc/game.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "7469"
}
],
"symlink_target": ""
} |
angular.module('ui.bootstrap.datepickerPopup', ['ui.bootstrap.datepicker', 'ui.bootstrap.position'])
.value('$datepickerPopupLiteralWarning', true)
.constant('uibDatepickerPopupConfig', {
altInputFormats: [],
appendToBody: false,
clearText: 'Clear',
closeOnDateSelection: true,
closeText: 'Done',
currentText: 'Today',
datepickerPopup: 'yyyy-MM-dd',
datepickerPopupTemplateUrl: 'uib/template/datepickerPopup/popup.html',
datepickerTemplateUrl: 'uib/template/datepicker/datepicker.html',
html5Types: {
date: 'yyyy-MM-dd',
'datetime-local': 'yyyy-MM-ddTHH:mm:ss.sss',
'month': 'yyyy-MM'
},
onOpenFocus: true,
showButtonBar: true,
placement: 'auto bottom-left'
})
.controller('UibDatepickerPopupController', ['$scope', '$element', '$attrs', '$compile', '$log', '$parse', '$window', '$document', '$rootScope', '$uibPosition', 'dateFilter', 'uibDateParser', 'uibDatepickerPopupConfig', '$timeout', 'uibDatepickerConfig', '$datepickerPopupLiteralWarning',
function($scope, $element, $attrs, $compile, $log, $parse, $window, $document, $rootScope, $position, dateFilter, dateParser, datepickerPopupConfig, $timeout, datepickerConfig, $datepickerPopupLiteralWarning) {
var cache = {},
isHtml5DateInput = false;
var dateFormat, closeOnDateSelection, appendToBody, onOpenFocus,
datepickerPopupTemplateUrl, datepickerTemplateUrl, popupEl, datepickerEl, scrollParentEl,
ngModel, ngModelOptions, $popup, altInputFormats, watchListeners = [],
timezone;
this.init = function(_ngModel_) {
ngModel = _ngModel_;
ngModelOptions = _ngModel_.$options;
closeOnDateSelection = angular.isDefined($attrs.closeOnDateSelection) ?
$scope.$parent.$eval($attrs.closeOnDateSelection) :
datepickerPopupConfig.closeOnDateSelection;
appendToBody = angular.isDefined($attrs.datepickerAppendToBody) ?
$scope.$parent.$eval($attrs.datepickerAppendToBody) :
datepickerPopupConfig.appendToBody;
onOpenFocus = angular.isDefined($attrs.onOpenFocus) ?
$scope.$parent.$eval($attrs.onOpenFocus) : datepickerPopupConfig.onOpenFocus;
datepickerPopupTemplateUrl = angular.isDefined($attrs.datepickerPopupTemplateUrl) ?
$attrs.datepickerPopupTemplateUrl :
datepickerPopupConfig.datepickerPopupTemplateUrl;
datepickerTemplateUrl = angular.isDefined($attrs.datepickerTemplateUrl) ?
$attrs.datepickerTemplateUrl : datepickerPopupConfig.datepickerTemplateUrl;
altInputFormats = angular.isDefined($attrs.altInputFormats) ?
$scope.$parent.$eval($attrs.altInputFormats) :
datepickerPopupConfig.altInputFormats;
$scope.showButtonBar = angular.isDefined($attrs.showButtonBar) ?
$scope.$parent.$eval($attrs.showButtonBar) :
datepickerPopupConfig.showButtonBar;
if (datepickerPopupConfig.html5Types[$attrs.type]) {
dateFormat = datepickerPopupConfig.html5Types[$attrs.type];
isHtml5DateInput = true;
} else {
dateFormat = $attrs.uibDatepickerPopup || datepickerPopupConfig.datepickerPopup;
$attrs.$observe('uibDatepickerPopup', function(value, oldValue) {
var newDateFormat = value || datepickerPopupConfig.datepickerPopup;
// Invalidate the $modelValue to ensure that formatters re-run
// FIXME: Refactor when PR is merged: https://github.com/angular/angular.js/pull/10764
if (newDateFormat !== dateFormat) {
dateFormat = newDateFormat;
ngModel.$modelValue = null;
if (!dateFormat) {
throw new Error('uibDatepickerPopup must have a date format specified.');
}
}
});
}
if (!dateFormat) {
throw new Error('uibDatepickerPopup must have a date format specified.');
}
if (isHtml5DateInput && $attrs.uibDatepickerPopup) {
throw new Error('HTML5 date input types do not support custom formats.');
}
// popup element used to display calendar
popupEl = angular.element('<div uib-datepicker-popup-wrap><div uib-datepicker></div></div>');
if (ngModelOptions) {
timezone = ngModelOptions.timezone;
$scope.ngModelOptions = angular.copy(ngModelOptions);
$scope.ngModelOptions.timezone = null;
if ($scope.ngModelOptions.updateOnDefault === true) {
$scope.ngModelOptions.updateOn = $scope.ngModelOptions.updateOn ?
$scope.ngModelOptions.updateOn + ' default' : 'default';
}
popupEl.attr('ng-model-options', 'ngModelOptions');
} else {
timezone = null;
}
popupEl.attr({
'ng-model': 'date',
'ng-change': 'dateSelection(date)',
'template-url': datepickerPopupTemplateUrl
});
// datepicker element
datepickerEl = angular.element(popupEl.children()[0]);
datepickerEl.attr('template-url', datepickerTemplateUrl);
if (!$scope.datepickerOptions) {
$scope.datepickerOptions = {};
}
if (isHtml5DateInput) {
if ($attrs.type === 'month') {
$scope.datepickerOptions.datepickerMode = 'month';
$scope.datepickerOptions.minMode = 'month';
}
}
datepickerEl.attr('datepicker-options', 'datepickerOptions');
if (!isHtml5DateInput) {
// Internal API to maintain the correct ng-invalid-[key] class
ngModel.$$parserName = 'date';
ngModel.$validators.date = validator;
ngModel.$parsers.unshift(parseDate);
ngModel.$formatters.push(function(value) {
if (ngModel.$isEmpty(value)) {
$scope.date = value;
return value;
}
$scope.date = dateParser.fromTimezone(value, timezone);
if (angular.isNumber($scope.date)) {
$scope.date = new Date($scope.date);
}
return dateParser.filter($scope.date, dateFormat);
});
} else {
ngModel.$formatters.push(function(value) {
$scope.date = dateParser.fromTimezone(value, timezone);
return value;
});
}
// Detect changes in the view from the text box
ngModel.$viewChangeListeners.push(function() {
$scope.date = parseDateString(ngModel.$viewValue);
});
$element.on('keydown', inputKeydownBind);
$popup = $compile(popupEl)($scope);
// Prevent jQuery cache memory leak (template is now redundant after linking)
popupEl.remove();
if (appendToBody) {
$document.find('body').append($popup);
} else {
$element.after($popup);
}
$scope.$on('$destroy', function() {
if ($scope.isOpen === true) {
if (!$rootScope.$$phase) {
$scope.$apply(function() {
$scope.isOpen = false;
});
}
}
$popup.remove();
$element.off('keydown', inputKeydownBind);
$document.off('click', documentClickBind);
if (scrollParentEl) {
scrollParentEl.off('scroll', positionPopup);
}
angular.element($window).off('resize', positionPopup);
//Clear all watch listeners on destroy
while (watchListeners.length) {
watchListeners.shift()();
}
});
};
$scope.getText = function(key) {
return $scope[key + 'Text'] || datepickerPopupConfig[key + 'Text'];
};
$scope.isDisabled = function(date) {
if (date === 'today') {
date = dateParser.fromTimezone(new Date(), timezone);
}
var dates = {};
angular.forEach(['minDate', 'maxDate'], function(key) {
if ($scope.datepickerOptions[key] === null) {
dates[key] = null;
} else if (angular.isDate($scope.datepickerOptions[key])) {
dates[key] = dateParser.fromTimezone(new Date($scope.datepickerOptions[key]), timezone);
} else {
if ($datepickerPopupLiteralWarning) {
$log.warn('Literal date support has been deprecated, please switch to date object usage');
}
dates[key] = new Date(dateFilter($scope.datepickerOptions[key], 'medium'));
}
});
return $scope.datepickerOptions &&
dates.minDate && $scope.compare(date, dates.minDate) < 0 ||
dates.maxDate && $scope.compare(date, dates.maxDate) > 0;
};
$scope.compare = function(date1, date2) {
return new Date(date1.getFullYear(), date1.getMonth(), date1.getDate()) - new Date(date2.getFullYear(), date2.getMonth(), date2.getDate());
};
// Inner change
$scope.dateSelection = function(dt) {
if (angular.isDefined(dt)) {
$scope.date = dt;
}
var date = $scope.date ? dateParser.filter($scope.date, dateFormat) : null; // Setting to NULL is necessary for form validators to function
$element.val(date);
ngModel.$setViewValue(date);
if (closeOnDateSelection) {
$scope.isOpen = false;
$element[0].focus();
}
};
$scope.keydown = function(evt) {
if (evt.which === 27) {
evt.stopPropagation();
$scope.isOpen = false;
$element[0].focus();
}
};
$scope.select = function(date, evt) {
evt.stopPropagation();
if (date === 'today') {
var today = new Date();
if (angular.isDate($scope.date)) {
date = new Date($scope.date);
date.setFullYear(today.getFullYear(), today.getMonth(), today.getDate());
} else {
date = new Date(today.setHours(0, 0, 0, 0));
}
}
$scope.dateSelection(date);
};
$scope.close = function(evt) {
evt.stopPropagation();
$scope.isOpen = false;
$element[0].focus();
};
$scope.disabled = angular.isDefined($attrs.disabled) || false;
if ($attrs.ngDisabled) {
watchListeners.push($scope.$parent.$watch($parse($attrs.ngDisabled), function(disabled) {
$scope.disabled = disabled;
}));
}
$scope.$watch('isOpen', function(value) {
if (value) {
if (!$scope.disabled) {
$timeout(function() {
positionPopup();
if (onOpenFocus) {
$scope.$broadcast('uib:datepicker.focus');
}
$document.on('click', documentClickBind);
var placement = $attrs.popupPlacement ? $attrs.popupPlacement : datepickerPopupConfig.placement;
if (appendToBody || $position.parsePlacement(placement)[2]) {
scrollParentEl = scrollParentEl || angular.element($position.scrollParent($element));
if (scrollParentEl) {
scrollParentEl.on('scroll', positionPopup);
}
} else {
scrollParentEl = null;
}
angular.element($window).on('resize', positionPopup);
}, 0, false);
} else {
$scope.isOpen = false;
}
} else {
$document.off('click', documentClickBind);
if (scrollParentEl) {
scrollParentEl.off('scroll', positionPopup);
}
angular.element($window).off('resize', positionPopup);
}
});
function cameltoDash(string) {
return string.replace(/([A-Z])/g, function($1) { return '-' + $1.toLowerCase(); });
}
function parseDateString(viewValue) {
var date = dateParser.parse(viewValue, dateFormat, $scope.date);
if (isNaN(date)) {
for (var i = 0; i < altInputFormats.length; i++) {
date = dateParser.parse(viewValue, altInputFormats[i], $scope.date);
if (!isNaN(date)) {
return date;
}
}
}
return date;
}
function parseDate(viewValue) {
if (angular.isNumber(viewValue)) {
// presumably timestamp to date object
viewValue = new Date(viewValue);
}
if (!viewValue) {
return null;
}
if (angular.isDate(viewValue) && !isNaN(viewValue)) {
return viewValue;
}
if (angular.isString(viewValue)) {
var date = parseDateString(viewValue);
if (!isNaN(date)) {
return dateParser.toTimezone(date, timezone);
}
}
return ngModel.$options && ngModel.$options.allowInvalid ? viewValue : undefined;
}
function validator(modelValue, viewValue) {
var value = modelValue || viewValue;
if (!$attrs.ngRequired && !value) {
return true;
}
if (angular.isNumber(value)) {
value = new Date(value);
}
if (!value) {
return true;
}
if (angular.isDate(value) && !isNaN(value)) {
return true;
}
if (angular.isString(value)) {
return !isNaN(parseDateString(viewValue));
}
return false;
}
function documentClickBind(event) {
if (!$scope.isOpen && $scope.disabled) {
return;
}
var popup = $popup[0];
var dpContainsTarget = $element[0].contains(event.target);
// The popup node may not be an element node
// In some browsers (IE) only element nodes have the 'contains' function
var popupContainsTarget = popup.contains !== undefined && popup.contains(event.target);
if ($scope.isOpen && !(dpContainsTarget || popupContainsTarget)) {
$scope.$apply(function() {
$scope.isOpen = false;
});
}
}
function inputKeydownBind(evt) {
if (evt.which === 27 && $scope.isOpen) {
evt.preventDefault();
evt.stopPropagation();
$scope.$apply(function() {
$scope.isOpen = false;
});
$element[0].focus();
} else if (evt.which === 40 && !$scope.isOpen) {
evt.preventDefault();
evt.stopPropagation();
$scope.$apply(function() {
$scope.isOpen = true;
});
}
}
function positionPopup() {
if ($scope.isOpen) {
var dpElement = angular.element($popup[0].querySelector('.uib-datepicker-popup'));
var placement = $attrs.popupPlacement ? $attrs.popupPlacement : datepickerPopupConfig.placement;
var position = $position.positionElements($element, dpElement, placement, appendToBody);
dpElement.css({top: position.top + 'px', left: position.left + 'px'});
if (dpElement.hasClass('uib-position-measure')) {
dpElement.removeClass('uib-position-measure');
}
}
}
$scope.$on('uib:datepicker.mode', function() {
$timeout(positionPopup, 0, false);
});
}])
.directive('uibDatepickerPopup', function() {
return {
require: ['ngModel', 'uibDatepickerPopup'],
controller: 'UibDatepickerPopupController',
scope: {
datepickerOptions: '=?',
isOpen: '=?',
currentText: '@',
clearText: '@',
closeText: '@'
},
link: function(scope, element, attrs, ctrls) {
var ngModel = ctrls[0],
ctrl = ctrls[1];
ctrl.init(ngModel);
}
};
})
.directive('uibDatepickerPopupWrap', function() {
return {
replace: true,
transclude: true,
templateUrl: function(element, attrs) {
return attrs.templateUrl || 'uib/template/datepickerPopup/popup.html';
}
};
});
| {
"content_hash": "2b739972ef29076bd95ac3497e92f7f3",
"timestamp": "",
"source": "github",
"line_count": 459,
"max_line_length": 288,
"avg_line_length": 31.664488017429193,
"alnum_prop": 0.6312783817256089,
"repo_name": "jcmosqued/quatroparedes",
"id": "318a9494407713f3499b7be5cfbf795acc17f59c",
"size": "14534",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "node_modules/angular-ui-bootstrap/src/datepickerPopup/popup.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "31524"
},
{
"name": "HTML",
"bytes": "188573"
},
{
"name": "JavaScript",
"bytes": "841528"
},
{
"name": "PHP",
"bytes": "844"
},
{
"name": "Shell",
"bytes": "414"
}
],
"symlink_target": ""
} |
require 'rails_helper'
describe DateNotInFutureValidator do
let(:test_model) do
Class.new do
include ActiveModel::Validations
attr_accessor :date_attr
validates :date_attr, date_not_in_future: true
end
end
subject { test_model.new }
it 'passes when attribute is a valid date' do
subject.date_attr = Date.current
expect(subject).to be_valid
end
it 'fails when attribute is not a date' do
subject.date_attr = 'fake_date'
expect(subject).to_not be_valid
end
it 'returns appropriate message when attribute is not a date' do
subject.date_attr = 'fake_date'
expect(subject).to_not be_valid
expect(subject.errors[:date_attr]).to eq ['is not a valid date']
end
it 'passes when the date attribute is in the past' do
subject.date_attr = 4.days.ago
expect(subject).to be_valid
end
it 'fails when the date attribute is in the future' do
subject.date_attr = 4.days.from_now
expect(subject).not_to be_valid
end
it 'returns appropriate message when date is in future' do
subject.date_attr = 4.days.from_now
subject.valid?
expect(subject.errors[:date_attr]).to eq ['is not valid (cannot be in the future)']
end
end
| {
"content_hash": "fbf0f6074d7a3b7c1b7949ffab8a590f",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 87,
"avg_line_length": 25.458333333333332,
"alnum_prop": 0.6890343698854338,
"repo_name": "evo2013/osra",
"id": "3b68826d00e411f1801b443c03ca75678ee058d5",
"size": "1222",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "spec/lib/validators/date_not_in_future_validator_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1491"
},
{
"name": "CoffeeScript",
"bytes": "122"
},
{
"name": "JavaScript",
"bytes": "683"
},
{
"name": "Ruby",
"bytes": "284345"
}
],
"symlink_target": ""
} |
module Ammado
# https://api.ammado.com/#FundraiserCoverEndpoint
class FundraiserCover < ApiResource
def create
File.open(api.default_images_folder + file_name) do |file|
file_postfix = file_name.split('.').last
upload_io_file = UploadIO.new(file, AMMADO_FILE_POSTFIX_TO_TYPE[file_postfix], file_name)
code, response = api.post_multipart(resource_create_path, params.merge(coverImage: upload_io_file, signature: calculate_signature, apiKey: api.key))
@params.merge!(response)
return code == '201'
end
end
def resource_create_path
"/v1/fundraiser/#{fundraiser_id}/coverimage"
end
def calculate_signature
Rails.logger.info('Calculate signature for ' + @params.to_s)
signature_parts = []
signature_parts << fundraiser_id
signature_parts << Base64.strict_encode64(file_name)
signature_parts << api.secret
plain_signature = signature_parts.flatten.join('.')
Rails.logger.info('Plain signature is ' + plain_signature)
return Digest::SHA1.hexdigest(plain_signature).upcase
end
end
end
| {
"content_hash": "32f1f679c59658234cb084d8f6c49b31",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 156,
"avg_line_length": 33.93939393939394,
"alnum_prop": 0.675,
"repo_name": "mxrguspxrt/ammado",
"id": "ffd6b7b02e8868e71f5d8ff7446e12073851b6ed",
"size": "1120",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/ammado/fundraiser_cover.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "16619"
}
],
"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 (1.8.0_31) on Wed Dec 17 20:48:13 PST 2014 -->
<title>BasicListUI.FocusHandler (Java Platform SE 8 )</title>
<meta name="date" content="2014-12-17">
<meta name="keywords" content="javax.swing.plaf.basic.BasicListUI.FocusHandler class">
<meta name="keywords" content="repaintCellFocus()">
<meta name="keywords" content="focusGained()">
<meta name="keywords" content="focusLost()">
<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="BasicListUI.FocusHandler (Java Platform SE 8 )";
}
}
catch(err) {
}
//-->
var methods = {"i0":10,"i1":10,"i2":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/BasicListUI.FocusHandler.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><strong>Java™ Platform<br>Standard Ed. 8</strong></div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../javax/swing/plaf/basic/BasicListUI.html" title="class in javax.swing.plaf.basic"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../javax/swing/plaf/basic/BasicListUI.ListDataHandler.html" title="class in javax.swing.plaf.basic"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?javax/swing/plaf/basic/BasicListUI.FocusHandler.html" target="_top">Frames</a></li>
<li><a href="BasicListUI.FocusHandler.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">javax.swing.plaf.basic</div>
<h2 title="Class BasicListUI.FocusHandler" class="title">Class BasicListUI.FocusHandler</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li><a href="../../../../java/lang/Object.html" title="class in java.lang">java.lang.Object</a></li>
<li>
<ul class="inheritance">
<li>javax.swing.plaf.basic.BasicListUI.FocusHandler</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd><a href="../../../../java/awt/event/FocusListener.html" title="interface in java.awt.event">FocusListener</a>, <a href="../../../../java/util/EventListener.html" title="interface in java.util">EventListener</a></dd>
</dl>
<dl>
<dt>Enclosing class:</dt>
<dd><a href="../../../../javax/swing/plaf/basic/BasicListUI.html" title="class in javax.swing.plaf.basic">BasicListUI</a></dd>
</dl>
<hr>
<br>
<pre>public class <span class="typeNameLabel">BasicListUI.FocusHandler</span>
extends <a href="../../../../java/lang/Object.html" title="class in java.lang">Object</a>
implements <a href="../../../../java/awt/event/FocusListener.html" title="interface in java.awt.event">FocusListener</a></pre>
<div class="block">This class should be treated as a "protected" inner class.
Instantiate it only within subclasses of <code>BasicListUI</code>.</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="../../../../javax/swing/plaf/basic/BasicListUI.FocusHandler.html#FocusHandler--">FocusHandler</a></span>()</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>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../javax/swing/plaf/basic/BasicListUI.FocusHandler.html#focusGained-java.awt.event.FocusEvent-">focusGained</a></span>(<a href="../../../../java/awt/event/FocusEvent.html" title="class in java.awt.event">FocusEvent</a> e)</code>
<div class="block">Invoked when a component gains the keyboard focus.</div>
</td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../javax/swing/plaf/basic/BasicListUI.FocusHandler.html#focusLost-java.awt.event.FocusEvent-">focusLost</a></span>(<a href="../../../../java/awt/event/FocusEvent.html" title="class in java.awt.event">FocusEvent</a> e)</code>
<div class="block">Invoked when a component loses the keyboard focus.</div>
</td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code>protected void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../javax/swing/plaf/basic/BasicListUI.FocusHandler.html#repaintCellFocus--">repaintCellFocus</a></span>()</code> </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.<a href="../../../../java/lang/Object.html" title="class in java.lang">Object</a></h3>
<code><a href="../../../../java/lang/Object.html#clone--">clone</a>, <a href="../../../../java/lang/Object.html#equals-java.lang.Object-">equals</a>, <a href="../../../../java/lang/Object.html#finalize--">finalize</a>, <a href="../../../../java/lang/Object.html#getClass--">getClass</a>, <a href="../../../../java/lang/Object.html#hashCode--">hashCode</a>, <a href="../../../../java/lang/Object.html#notify--">notify</a>, <a href="../../../../java/lang/Object.html#notifyAll--">notifyAll</a>, <a href="../../../../java/lang/Object.html#toString--">toString</a>, <a href="../../../../java/lang/Object.html#wait--">wait</a>, <a href="../../../../java/lang/Object.html#wait-long-">wait</a>, <a href="../../../../java/lang/Object.html#wait-long-int-">wait</a></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="FocusHandler--">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>FocusHandler</h4>
<pre>public FocusHandler()</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="repaintCellFocus--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>repaintCellFocus</h4>
<pre>protected void repaintCellFocus()</pre>
</li>
</ul>
<a name="focusGained-java.awt.event.FocusEvent-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>focusGained</h4>
<pre>public void focusGained(<a href="../../../../java/awt/event/FocusEvent.html" title="class in java.awt.event">FocusEvent</a> e)</pre>
<div class="block"><span class="descfrmTypeLabel">Description copied from interface: <code><a href="../../../../java/awt/event/FocusListener.html#focusGained-java.awt.event.FocusEvent-">FocusListener</a></code></span></div>
<div class="block">Invoked when a component gains the keyboard focus.</div>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code><a href="../../../../java/awt/event/FocusListener.html#focusGained-java.awt.event.FocusEvent-">focusGained</a></code> in interface <code><a href="../../../../java/awt/event/FocusListener.html" title="interface in java.awt.event">FocusListener</a></code></dd>
</dl>
</li>
</ul>
<a name="focusLost-java.awt.event.FocusEvent-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>focusLost</h4>
<pre>public void focusLost(<a href="../../../../java/awt/event/FocusEvent.html" title="class in java.awt.event">FocusEvent</a> e)</pre>
<div class="block"><span class="descfrmTypeLabel">Description copied from interface: <code><a href="../../../../java/awt/event/FocusListener.html#focusLost-java.awt.event.FocusEvent-">FocusListener</a></code></span></div>
<div class="block">Invoked when a component loses the keyboard focus.</div>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code><a href="../../../../java/awt/event/FocusListener.html#focusLost-java.awt.event.FocusEvent-">focusLost</a></code> in interface <code><a href="../../../../java/awt/event/FocusListener.html" title="interface in java.awt.event">FocusListener</a></code></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/BasicListUI.FocusHandler.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><strong>Java™ Platform<br>Standard Ed. 8</strong></div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../javax/swing/plaf/basic/BasicListUI.html" title="class in javax.swing.plaf.basic"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../javax/swing/plaf/basic/BasicListUI.ListDataHandler.html" title="class in javax.swing.plaf.basic"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?javax/swing/plaf/basic/BasicListUI.FocusHandler.html" target="_top">Frames</a></li>
<li><a href="BasicListUI.FocusHandler.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 ======= -->
<p class="legalCopy"><small><font size="-1"> <a href="http://bugreport.sun.com/bugreport/">Submit a bug or feature</a> <br>For further API reference and developer documentation, see <a href="http://download.oracle.com/javase/8/docs/index.html" target="_blank">Java SE Documentation</a>. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.<br> <a href="../../../../../legal/cpyr.html">Copyright</a> © 1993, 2015, Oracle and/or its affiliates. All rights reserved. </font></small></p>
</body>
</html>
| {
"content_hash": "1ae634cfb21c88f0337bcbdbc82a32ae",
"timestamp": "",
"source": "github",
"line_count": 331,
"max_line_length": 767,
"avg_line_length": 44.8821752265861,
"alnum_prop": 0.6531367797522887,
"repo_name": "fbiville/annotation-processing-ftw",
"id": "395190fd90dd8a28804ade0bbd5f73c13faa0437",
"size": "14856",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/java/jdk8/javax/swing/plaf/basic/BasicListUI.FocusHandler.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "191178"
},
{
"name": "HTML",
"bytes": "63904"
},
{
"name": "Java",
"bytes": "107042"
},
{
"name": "JavaScript",
"bytes": "246677"
}
],
"symlink_target": ""
} |
using VersionOne.SDK.APIClient;
namespace VersionOne.ServerConnector.Entities {
public class Link {
public const string OnMenuProperty = "OnMenu";
public const string UrlProperty = "URL";
public string Title { get; set; }
public string Url { get; set; }
public bool OnMenu { get; set; }
public Link(string url, string title, bool onMenu) {
Title = title;
Url = url;
OnMenu = onMenu;
}
public Link(string url, string title) : this(url, title, true) { }
internal Link(Asset asset) {
Title = asset.GetAttribute(asset.AssetType.GetAttributeDefinition(Entity.NameProperty)).Value.ToString();
Url = asset.GetAttribute(asset.AssetType.GetAttributeDefinition(UrlProperty)).Value.ToString();
OnMenu = (bool)asset.GetAttribute(asset.AssetType.GetAttributeDefinition(OnMenuProperty)).Value;
}
public override bool Equals(object obj) {
if(ReferenceEquals(null, obj)) {
return false;
}
if(ReferenceEquals(this, obj)) {
return true;
}
return obj.GetType() == typeof(Link) && Equals((Link) obj);
}
private bool Equals(Link other) {
return Equals(other.Title, Title) && Equals(other.Url, Url) && other.OnMenu.Equals(OnMenu);
}
public override int GetHashCode() {
var result = (Title != null ? Title.GetHashCode() : 0);
result = (result*397) ^ (Url != null ? Url.GetHashCode() : 0);
result = (result*397) ^ OnMenu.GetHashCode();
return result;
}
}
} | {
"content_hash": "ded86f2181091a691dfb543b1d87cdfc",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 117,
"avg_line_length": 35.458333333333336,
"alnum_prop": 0.5775558166862514,
"repo_name": "KellyKey/Sigma",
"id": "212c68953c51cc92d2b08376069b928494c04bb4",
"size": "1704",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "VersionOne.ServerConnector/Entities/Link.cs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C#",
"bytes": "530656"
},
{
"name": "PowerShell",
"bytes": "318"
},
{
"name": "Shell",
"bytes": "4671"
}
],
"symlink_target": ""
} |
author: slowe
comments: true
date: 2008-11-07 10:45:11+00:00
layout: post
slug: where-is-bluebear-going-with-kodiak
title: Where is Bluebear Going with Kodiak?
wordpress_id: 1014
categories: Musing
tags:
- Linux
- Macintosh
- Virtualization
- VMware
- Windows
- Xen
---
I wouldn't go so far as to say that I broke the news on [Kodiak](http://www.bluebearllc.net/kodiak/), but since my first post on Kodiak [back in August][1], Bluebear has seen quite a bit of coverage around the Internet. Fellow virtualization blogger Duncan Epping of [Yellow Bricks](http://www.yellow-bricks.com/) has discussed Kodiak a number of times (here are only a few):
[Bluebear's Kodiak!](http://www.yellow-bricks.com/2008/09/30/bluebears-kodiak/)
[Bluebear's Kodiak, what's all the fuss about...](http://www.yellow-bricks.com/2008/09/30/bluebears-kodiak-whats-all-the-fuss-about/)
[Kodiak 0.02 coming out real soon...](http://www.yellow-bricks.com/2008/10/20/kodiak-002-coming-out-real-soon/)
That's not to mention coverage by [virtualization.com](http://virtualization.com/news/2008/07/16/bluebear-koala-kodiak/), [Reuters.com](http://www.reuters.com/article/pressRelease/idUS149341+10-Jul-2008+BW20080710), and numerous other bloggers, experts, and analysts.
But where is Bluebear headed with Kodiak? What is their vision? Well, I don't speak for Bluebear, but I did want to share some insight I'd gathered during a conversation with one of the Kodiak developers. I was curious to know how VMware's announcements of cross-platform vCenter Server and cross-platform VI Client at VMworld 2008 would affect Kodiak. Perhaps because of VMware's market leadership, most people see Kodiak as only a cross-platform VI replacement. The truth is, according to my information, Kodiak's true value lies elsewhere. While it _can_ be viewed as a VI Client replacement, and while it _does_ bring cross-platform functionality to the table, there's more to it than just that. Thus, cross-platform support by VMware---while sorely needed for quite some time---shouldn't really impact Kodiak all that much.
So what is the value of Kodiak beyond cross-platform support? Good question! Here's a couple of points I gathered from of our conversation:
* Multi-hypervisor management: One stated goal for Kodiak has always been to provide the ability to manage multiple, different hypervisors---not only ESX and ESXi, but also Xen, VirtualBox, etc. This is an area that only Microsoft is dabbling in with SCVMM, which will manage Hyper-V and ESX (via VirtualCenter only). Kodiak can manage ESX directly or via VirtualCenter.
* Management via visualization: I don't know if this is what drove Bluebear to use Adobe AIR or if it's a result of using Adobe AIR, but the idea behind managing virtualization with Kodiak is more through visualization than anything else. Bluebear wants users to be able to respond quickly to potential issues by making it possible to see those potential issues instead of waiting for a notification or an e-mail that something's wrong.
I'm sure that Bluebear has all sorts of super-secret stuff in the works that will further differentiate their product from VMware's cross-platform VI Client, even though the two products aren't intended to directly compete.
And, of course, this doesn't take into account Bluebear's hardware side, aka Koala, which doesn't get nearly the same amount of attention as Kodiak. Personally, I'm kinda hoping that the Koala will end up affordable enough for me to pick one up, as I could surely use it to host various virtual servers at home for media streaming, home automation, etc. But I digress...
Anyway, I think I have a pile of beta invites for Kodiak, so if anyone is interested post a comment here and I'll see what I can do. Then you can take a look at the product yourself---keeping in mind that it is a very early beta---and see what you think about the future of Kodiak.
[1]: {% post_url 2008-08-29-bluebear-and-kodiak %}
| {
"content_hash": "1837acf32ccf46ab8f80929dbcd9d136",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 828,
"avg_line_length": 94.33333333333333,
"alnum_prop": 0.7796567390206967,
"repo_name": "lowescott/lowescott.github.io",
"id": "be3e92d74804ea1582f0be0bde045667e5cef5bd",
"size": "3966",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_posts/2008-11-07-where-is-bluebear-going-with-kodiak.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "133971"
},
{
"name": "HTML",
"bytes": "10990"
},
{
"name": "Ruby",
"bytes": "48"
}
],
"symlink_target": ""
} |
'use strict';
var altProperty = require('../../util/altproperty'),
sanitize = require('../../util/sanitize');
module.exports = {
'name': 'shutdown',
'exec': function (options, callback) {
var self = this;
if (!callback && typeof options === 'function') {
callback = options;
options = {};
}
// Map alternative properties to 'id'
options = altProperty(options, 'id', ['domainId', 'domId']);
// Map alternative properties to 'name'
options = altProperty(options, 'name', ['domainName', 'domName']);
if (!options.name && !options.id && !options.all) {
return callback(new Error('shutdown: Missing required property \'name\' or \'id\' in options'));
}
if (options.name && options.id) {
return callback(new Error('shutdown: You may supply \'name\' or \'id\' not both'));
}
if (options.all) {
// Shutdown all vms - so first check if the filter grants permission to all runnig VMs
this.executor.exec('xl', ['list', '-l'], function (err, data) {
if (err) {
return callback(err);
}
var list = JSON.parse(data.stdout.toString('utf8'));
list = list.map(function (elem) {
return elem.config.c_info.name;
});
var filteredList = list.filter(function (elem) {
return self.filter(elem);
});
if (list.length !== filteredList.length) {
return callback(new Error('Not allowed to shutdown all VMs'));
}
self.executor.exec('xl', ['shutdown', '-a'], function (err, data) {
if (err) {
return callback(err);
}
if (data.stderr.length > 0) {
return callback(new Error(data.stderr.toString('utf8').trim()));
}
return callback(null, data.stdout.trim());
});
});
} else if (options.name) {
// Sanitize domain id
var name = sanitize.domName(options.name);
// Check if this DomU may be accessed
if (!self.filter(name)) {
return callback(new Error(options.name + ' is an invalid domain identifier (rc=-6)'));
}
this.executor.exec('xl', ['shutdown', name], function (err, data) {
if (err) {
return callback(err);
}
// Shutdown response is printed on stderr - maybe a XEN bug?
if (data.code === 0 && data.stdout.length === 0) {
return callback(null, data.stderr.toString('utf8').trim());
} else if (data.stderr.length === 0 && data.stdout.length > 0) {
return callback(null, data.stdout.toString('utf8').trim());
} else {
return callback(new Error(data.stderr.toString('utf8').trim()));
}
});
} else if (options.id) {
// Sanitize domain name
var id = sanitize.domId(options.id);
// Empty string (means sanitize failed) or 0 are not supported
if (!id) {
return callback(new Error('Invalid DomU id'));
}
// Get Dom name to check the filter
self.domname({
'id': id,
'skipFilter': true // Skip filtering in domname to return an accurate error message here
}, function (err, domName) {
if (err && self.executor.options.debug) {
console.log('Debug: Error thrown by domname:', err);
}
// Check if this DomU may be accessed
if (err || !self.filter(domName)) {
return callback(new Error('Shutting down domain ' + options.id + '\n' +
'libxl: error: libxl_dom.c:35:libxl__domain_type: unable to get domain type for domid=' + options.id + '\n' +
'shutdown failed (rc=-3)'));
}
// To prevent code duplication, call the shutdown logic itself, this time with the name property set
self.shutdown({
'name': domName
}, callback);
});
}
}
};
| {
"content_hash": "edbc3aa2a800261be39a360d1bc68e16",
"timestamp": "",
"source": "github",
"line_count": 117,
"max_line_length": 129,
"avg_line_length": 38.53846153846154,
"alnum_prop": 0.4823685961410512,
"repo_name": "benurb/node-xl-wrapper",
"id": "ce10d5097ceb48290f6ad3ed3490b3de0c123bb1",
"size": "4509",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/command/shutdown.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "43872"
}
],
"symlink_target": ""
} |
require 'rails/generators/active_record'
module Dallal
module Generators
class NotificationGenerator < ActiveRecord::Generators::Base
source_root File.expand_path(File.join(File.dirname(__FILE__), 'templates'))
def notifications_table_name
"#{table_name.singularize}_notifications"
end
def copy_migration
migration_template "migration.rb", "db/migrate/create_#{notifications_table_name}.rb"
end
def copy_files
copy_file "model.rb", model_path
if self.behavior == :invoke
inject_into_class(model_path, model_class_name, model_content)
end
end
private
def model_class_name
"#{table_name.singularize}_notification".classify
end
def user_model_name
Dallal.configuration.user_class_name.downcase
end
def model_path
"app/models/#{table_name.singularize}_notification.rb"
end
def model_content
<<-TEXT
belongs_to #{user_model_name}
TEXT
end
end
end
end
| {
"content_hash": "2d3e844e190e97f57173b709bd1fe931",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 93,
"avg_line_length": 23.977272727272727,
"alnum_prop": 0.6350710900473934,
"repo_name": "laertispappas/dallal",
"id": "4d267ae2770291d5c7feed0116acc2a64cbd09d3",
"size": "1055",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/generators/dallal/notification/notification_generator.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1372"
},
{
"name": "HTML",
"bytes": "5292"
},
{
"name": "JavaScript",
"bytes": "1192"
},
{
"name": "Ruby",
"bytes": "77784"
}
],
"symlink_target": ""
} |
@interface RevealDetailViewController : UIViewController <UITableViewDataSource,UITableViewDelegate>
@end
| {
"content_hash": "870f79a7975dee53e3adace378740a32",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 100,
"avg_line_length": 35.666666666666664,
"alnum_prop": 0.8785046728971962,
"repo_name": "denty/unestsDemo",
"id": "233cc255f1f85e30e5fda48e0109a535891ea808",
"size": "281",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "UnestsDemo/UnestsDemo/VC/RevealDetailViewController.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Objective-C",
"bytes": "31082"
}
],
"symlink_target": ""
} |
class CommonNameMismatchHandler;
class Profile;
namespace base {
class Clock;
}
namespace content {
class RenderViewHost;
class WebContents;
}
// This class is responsible for deciding what type of interstitial to show for
// an SSL validation error. The display of the interstitial might be delayed by
// a few seconds (2 by default) while trying to determine the cause of the
// error. During this window, the class will: check for a clock error, wait for
// a name-mismatch suggested URL, or wait for a captive portal result to arrive.
// If there is a name mismatch error and a corresponding suggested URL
// result arrives in this window, the user is redirected to the suggested URL.
// Failing that, if a captive portal detected result arrives in the time window,
// a captive portal error page is shown. If none of these potential error
// causes match, an SSL interstitial is shown.
//
// This class should only be used on the UI thread because its implementation
// uses captive_portal::CaptivePortalService which can only be accessed on the
// UI thread.
class SSLErrorHandler : public content::WebContentsUserData<SSLErrorHandler>,
public content::WebContentsObserver,
public content::NotificationObserver {
public:
typedef base::Callback<void(content::WebContents*)> TimerStartedCallback;
// Entry point for the class. The parameters are the same as SSLBlockingPage
// constructor.
static void HandleSSLError(content::WebContents* web_contents,
int cert_error,
const net::SSLInfo& ssl_info,
const GURL& request_url,
int options_mask,
scoped_ptr<SSLCertReporter> ssl_cert_reporter,
const base::Callback<void(bool)>& callback);
// Testing methods.
static void SetInterstitialDelayForTest(base::TimeDelta delay);
// The callback pointer must remain valid for the duration of error handling.
static void SetInterstitialTimerStartedCallbackForTest(
TimerStartedCallback* callback);
static void SetClockForTest(base::Clock* testing_clock);
protected:
// The parameters are the same as SSLBlockingPage's constructor.
SSLErrorHandler(content::WebContents* web_contents,
int cert_error,
const net::SSLInfo& ssl_info,
const GURL& request_url,
int options_mask,
scoped_ptr<SSLCertReporter> ssl_cert_reporter,
const base::Callback<void(bool)>& callback);
~SSLErrorHandler() override;
// Called when an SSL cert error is encountered. Triggers a captive portal
// check and fires a one shot timer to wait for a "captive portal detected"
// result to arrive.
void StartHandlingError();
const base::OneShotTimer<SSLErrorHandler>& get_timer() const {
return timer_;
}
// These are virtual for tests:
virtual void CheckForCaptivePortal();
virtual bool GetSuggestedUrl(const std::vector<std::string>& dns_names,
GURL* suggested_url) const;
virtual void CheckSuggestedUrl(const GURL& suggested_url);
virtual void NavigateToSuggestedURL(const GURL& suggested_url);
virtual bool IsErrorOverridable() const;
virtual void ShowCaptivePortalInterstitial(const GURL& landing_url);
virtual void ShowSSLInterstitial();
void ShowBadClockInterstitial(const base::Time& now);
// Gets the result of whether the suggested URL is valid. Displays
// common name mismatch interstitial or ssl interstitial accordingly.
void CommonNameMismatchHandlerCallback(
const CommonNameMismatchHandler::SuggestedUrlCheckResult& result,
const GURL& suggested_url);
private:
// content::NotificationObserver:
void Observe(
int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) override;
// content::WebContentsObserver:
void DidStartNavigationToPendingEntry(
const GURL& url,
content::NavigationController::ReloadType reload_type) override;
// content::WebContentsObserver:
void NavigationStopped() override;
// Deletes the SSLErrorHandler. This method is called when the page
// load stops or when there is a new navigation.
void DeleteSSLErrorHandler();
content::WebContents* web_contents_;
const int cert_error_;
const net::SSLInfo ssl_info_;
const GURL request_url_;
const int options_mask_;
base::Callback<void(bool)> callback_;
Profile* const profile_;
content::NotificationRegistrar registrar_;
base::OneShotTimer<SSLErrorHandler> timer_;
scoped_ptr<CommonNameMismatchHandler> common_name_mismatch_handler_;
scoped_ptr<SSLCertReporter> ssl_cert_reporter_;
DISALLOW_COPY_AND_ASSIGN(SSLErrorHandler);
};
#endif // CHROME_BROWSER_SSL_SSL_ERROR_HANDLER_H_
| {
"content_hash": "63c6f8af6bf09ab9353a1c6a61ede44c",
"timestamp": "",
"source": "github",
"line_count": 125,
"max_line_length": 80,
"avg_line_length": 39.232,
"alnum_prop": 0.7106443719412724,
"repo_name": "ltilve/ChromiumGStreamerBackend",
"id": "30dfb4f4672b051bd8358b04b1c72e510c5e7d48",
"size": "5773",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "chrome/browser/ssl/ssl_error_handler.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "AppleScript",
"bytes": "6973"
},
{
"name": "Arduino",
"bytes": "464"
},
{
"name": "Assembly",
"bytes": "37073"
},
{
"name": "Batchfile",
"bytes": "8451"
},
{
"name": "C",
"bytes": "9568645"
},
{
"name": "C++",
"bytes": "246813997"
},
{
"name": "CSS",
"bytes": "943687"
},
{
"name": "DM",
"bytes": "60"
},
{
"name": "Groff",
"bytes": "2494"
},
{
"name": "HTML",
"bytes": "27371019"
},
{
"name": "Java",
"bytes": "15348315"
},
{
"name": "JavaScript",
"bytes": "20872607"
},
{
"name": "Makefile",
"bytes": "70983"
},
{
"name": "Objective-C",
"bytes": "2029825"
},
{
"name": "Objective-C++",
"bytes": "10156554"
},
{
"name": "PHP",
"bytes": "97817"
},
{
"name": "PLpgSQL",
"bytes": "182741"
},
{
"name": "Perl",
"bytes": "63937"
},
{
"name": "Protocol Buffer",
"bytes": "494625"
},
{
"name": "Python",
"bytes": "8594611"
},
{
"name": "Shell",
"bytes": "486464"
},
{
"name": "Standard ML",
"bytes": "5106"
},
{
"name": "XSLT",
"bytes": "418"
},
{
"name": "nesC",
"bytes": "18347"
}
],
"symlink_target": ""
} |
use super::Tokenizer;
use super::matcher::*;
use super::token::{Token, TokenType};
use std::str::Chars;
use std::rc::Rc;
pub fn lexer(data: &mut Chars) -> Lexer {
let tokenizer = Tokenizer::new(data);
let mut lexer = Lexer::new(tokenizer);
let eol = vec!["\n"].iter().map(|&x| x.to_string()).collect();
let symbols = vec![
"(",
")",
"[",
"]",
",",
":",
"{",
"}",
"!",
"|",
"=",
"..",
".",
].iter().map(|&x| x.to_string()).collect();
let operators = vec![
"++",
"+",
"-",
"*",
"/",
"/",
"%",
"^",
">",
"<",
">=",
"<=",
"==",
"!=",
].iter().map(|&x| x.to_string()).collect();
let types = vec![
"num", "str", "idc", "bool",
].iter().map(|&x| x.to_string()).collect();
let boolean = vec![
"true",
"false",
].iter().map(|&x| x.to_string()).collect();
let matcher_eol = ConstantMatcher::new(TokenType::EOL, eol);
let matcher_symbol = ConstantMatcher::new(TokenType::Symbol, symbols);
let matcher_operator = ConstantMatcher::new(TokenType::Operator, operators);
let matcher_boolean = KeyMatcher::new(TokenType::BoolLiteral, boolean);
let matcher_types = KeyMatcher::new(TokenType::Type, types);
let matcher_whitespace = WhitespaceMatcher {};
let matcher_int_literal = IntLiteralMatcher {};
let matcher_float_literal = FloatLiteralMatcher {};
let matcher_identifier = IdentifierMatcher {};
let matcher_string_literal = StringLiteralMatcher {};
lexer.matchers_mut().push(Rc::new(matcher_eol));
lexer.matchers_mut().push(Rc::new(matcher_whitespace));
lexer.matchers_mut().push(Rc::new(matcher_operator));
lexer.matchers_mut().push(Rc::new(matcher_symbol));
lexer.matchers_mut().push(Rc::new(matcher_float_literal));
lexer.matchers_mut().push(Rc::new(matcher_int_literal));
lexer.matchers_mut().push(Rc::new(matcher_string_literal));
lexer.matchers_mut().push(Rc::new(matcher_boolean));
lexer.matchers_mut().push(Rc::new(matcher_types));
lexer.matchers_mut().push(Rc::new(matcher_identifier));
lexer
}
pub struct Lexer {
tokenizer: Tokenizer,
matchers: Vec<Rc<Matcher>>,
}
#[allow(dead_code)]
impl Lexer {
pub fn new(tokenizer: Tokenizer) -> Lexer {
Lexer {
tokenizer,
matchers: Vec::new(),
}
}
pub fn match_token(&mut self) -> Option<Token> {
for matcher in &mut self.matchers {
match self.tokenizer.try_match_token(matcher.as_ref()) {
Some(t) => return Some(t),
None => continue,
}
}
None
}
pub fn matchers(&self) -> &Vec<Rc<Matcher>> {
&self.matchers
}
pub fn matchers_mut(&mut self) -> &mut Vec<Rc<Matcher>> {
&mut self.matchers
}
}
impl Iterator for Lexer {
type Item = Token;
fn next(&mut self) -> Option<Token> {
let token = match self.match_token() {
Some(n) => n,
None => {
println!("invalid token");
return None
},
};
match token.token_type {
TokenType::EOF => None,
TokenType::Whitespace => {
match self.next() {
Some(t) => Some(t),
None => None,
}
}
_ => Some(token),
}
}
}
| {
"content_hash": "0af5e1ddb3784083dbcf9b6ec0ac011f",
"timestamp": "",
"source": "github",
"line_count": 135,
"max_line_length": 86,
"avg_line_length": 26.866666666666667,
"alnum_prop": 0.5017921146953405,
"repo_name": "snail-lang/snail",
"id": "9669cae7a36ebf2484fa94fa5d88b8e7192fd90b",
"size": "3627",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/snail/syntax/lexer/lexer.rs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Rust",
"bytes": "69908"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Elasticsearch.Net;
using Newtonsoft.Json;
namespace Nest
{
[JsonConverter(typeof(IndicesMultiSyntaxJsonConverter))]
[DebuggerDisplay("{DebugDisplay,nq}")]
public class Indices : Union<Indices.AllIndicesMarker, Indices.ManyIndices>, IUrlParameter
{
public class AllIndicesMarker { internal AllIndicesMarker() { } }
public static Indices All { get; } = new Indices(new AllIndicesMarker());
public static Indices AllIndices { get; } = new Indices(new AllIndicesMarker());
public class ManyIndices
{
private readonly List<IndexName> _indices = new List<IndexName>();
public IReadOnlyList<IndexName> Indices => _indices;
internal ManyIndices(IEnumerable<IndexName> indices)
{
indices.ThrowIfEmpty(nameof(indices));
this._indices.AddRange(indices);
}
internal ManyIndices(IEnumerable<string> indices)
{
indices.ThrowIfEmpty(nameof(indices));
this._indices.AddRange(indices.Select(s=>(IndexName)s));
}
public ManyIndices And<T>()
{
this._indices.Add(typeof(T));
return this;
}
}
internal Indices(Indices.AllIndicesMarker all) : base(all) { }
internal Indices(Indices.ManyIndices indices) : base(indices) { }
internal Indices(IEnumerable<IndexName> indices) : base(new ManyIndices(indices)) { }
public static IndexName Index(IndexName index) => index;
public static IndexName Index<T>() => typeof(T);
public static ManyIndices Index(IEnumerable<IndexName> indices) => new ManyIndices(indices);
public static ManyIndices Index(params IndexName[] indices) => new ManyIndices(indices);
public static ManyIndices Index(IEnumerable<string> indices) => new ManyIndices(indices);
public static ManyIndices Index(params string[] indices) => new ManyIndices(indices);
public static Indices Parse(string indicesString)
{
if (indicesString.IsNullOrEmpty()) throw new Exception("can not parse an empty string to Indices");
var indices = indicesString.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
if (indices.Contains("_all")) return Indices.All;
return Index(indices.Select(i => (IndexName)i));
}
public static implicit operator Indices(string indicesString) => Parse(indicesString);
public static implicit operator Indices(ManyIndices many) => new Indices(many);
public static implicit operator Indices(string[] many) => new ManyIndices(many);
public static implicit operator Indices(IndexName[] many) => new ManyIndices(many);
public static implicit operator Indices(IndexName index) => new ManyIndices(new[] { index });
public static implicit operator Indices(Type type) => new ManyIndices(new IndexName[] { type });
private string DebugDisplay => this.Match(
all => "_all",
types => $"Count: {types.Indices.Count} [" + string.Join(",", types.Indices.Select((t, i) => $"({i+1}: {t.DebugDisplay})")) + "]"
);
string IUrlParameter.GetString(IConnectionConfigurationValues settings)
{
return this.Match(
all => "_all",
many =>
{
var nestSettings = settings as IConnectionSettingsValues;
if (nestSettings == null)
throw new Exception("Tried to pass index names on querysting but it could not be resolved because no nest settings are available");
var infer = nestSettings.Inferrer;
var indices = many.Indices.Select(i => infer.IndexName(i)).Distinct();
return string.Join(",", indices);
}
);
}
public override bool Equals(object obj)
{
var other = obj as Indices;
if (other == null) return false;
return this.Match(
all => other.Match(a => true, m => false),
many => other.Match(
a => false,
m => this.GetHashCode().Equals(other.GetHashCode())
)
);
}
public override int GetHashCode()
{
return this.Match(
all => "_all".GetHashCode(),
many => string.Concat(many.Indices.OrderBy(i => i.ToString())).GetHashCode()
);
}
}
}
| {
"content_hash": "ce5cb3e0d6a2e00d0ba85920067e68c3",
"timestamp": "",
"source": "github",
"line_count": 109,
"max_line_length": 137,
"avg_line_length": 36.48623853211009,
"alnum_prop": 0.7060598441035957,
"repo_name": "CSGOpenSource/elasticsearch-net",
"id": "ce4e53f326a6962d44f0a45d5158df2cecb2b9b6",
"size": "3977",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/Nest/CommonAbstractions/Infer/Indices/Indices.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "3270"
},
{
"name": "C#",
"bytes": "8180341"
},
{
"name": "F#",
"bytes": "42280"
},
{
"name": "HTML",
"bytes": "295209"
},
{
"name": "Shell",
"bytes": "1853"
},
{
"name": "Smalltalk",
"bytes": "3426"
}
],
"symlink_target": ""
} |
.class public interface abstract Lorg/xml/sax/ContentHandler;
.super Ljava/lang/Object;
.source "ContentHandler.java"
# virtual methods
.method public abstract characters([CII)V
.annotation system Ldalvik/annotation/Throws;
value = {
Lorg/xml/sax/SAXException;
}
.end annotation
.end method
.method public abstract endDocument()V
.annotation system Ldalvik/annotation/Throws;
value = {
Lorg/xml/sax/SAXException;
}
.end annotation
.end method
.method public abstract endElement(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V
.annotation system Ldalvik/annotation/Throws;
value = {
Lorg/xml/sax/SAXException;
}
.end annotation
.end method
.method public abstract endPrefixMapping(Ljava/lang/String;)V
.annotation system Ldalvik/annotation/Throws;
value = {
Lorg/xml/sax/SAXException;
}
.end annotation
.end method
.method public abstract ignorableWhitespace([CII)V
.annotation system Ldalvik/annotation/Throws;
value = {
Lorg/xml/sax/SAXException;
}
.end annotation
.end method
.method public abstract processingInstruction(Ljava/lang/String;Ljava/lang/String;)V
.annotation system Ldalvik/annotation/Throws;
value = {
Lorg/xml/sax/SAXException;
}
.end annotation
.end method
.method public abstract setDocumentLocator(Lorg/xml/sax/Locator;)V
.end method
.method public abstract skippedEntity(Ljava/lang/String;)V
.annotation system Ldalvik/annotation/Throws;
value = {
Lorg/xml/sax/SAXException;
}
.end annotation
.end method
.method public abstract startDocument()V
.annotation system Ldalvik/annotation/Throws;
value = {
Lorg/xml/sax/SAXException;
}
.end annotation
.end method
.method public abstract startElement(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/xml/sax/Attributes;)V
.annotation system Ldalvik/annotation/Throws;
value = {
Lorg/xml/sax/SAXException;
}
.end annotation
.end method
.method public abstract startPrefixMapping(Ljava/lang/String;Ljava/lang/String;)V
.annotation system Ldalvik/annotation/Throws;
value = {
Lorg/xml/sax/SAXException;
}
.end annotation
.end method
| {
"content_hash": "6d2ae349af3c985e2615c98390becaf1",
"timestamp": "",
"source": "github",
"line_count": 88,
"max_line_length": 117,
"avg_line_length": 27.136363636363637,
"alnum_prop": 0.6758793969849246,
"repo_name": "Liberations/Flyme5_devices_base_cm",
"id": "ef158b76ce73f29990c176c4d4e68841715a9897",
"size": "2388",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vendor/aosp/core-libart.jar.out/smali/org/xml/sax/ContentHandler.smali",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "GLSL",
"bytes": "1500"
},
{
"name": "HTML",
"bytes": "96769"
},
{
"name": "Makefile",
"bytes": "11209"
},
{
"name": "Python",
"bytes": "1195"
},
{
"name": "Shell",
"bytes": "55270"
},
{
"name": "Smali",
"bytes": "160321888"
}
],
"symlink_target": ""
} |
package tools;
import org.capcaval.lafabrique.lafab.LaFabCommands;
import prj.DefaultProject;
public class Build {
/**
* @param args
*/
public static void main(String[] args) {
LaFabCommands c = new LaFabCommands();
DefaultProject dp = new DefaultProject();
String cr = c.build(dp.getDefaultProject().getSimpleName());
System.out.println(cr);
}
}
| {
"content_hash": "0f3a18863c369f6df132e913f96b71d8",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 62,
"avg_line_length": 17.09090909090909,
"alnum_prop": 0.6968085106382979,
"repo_name": "CapCaval/ccProjects",
"id": "36b6f4cfcc73c981b990ff393d1f75d87c3e7416",
"size": "376",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "00_prj/tools/Build.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "2447"
},
{
"name": "CSS",
"bytes": "1949"
},
{
"name": "HTML",
"bytes": "18206"
},
{
"name": "Java",
"bytes": "988896"
},
{
"name": "Shell",
"bytes": "2639"
}
],
"symlink_target": ""
} |
var assert = require('assert');
var ecstasy = require('../index.js');
describe('Engine', function() {
var engine;
beforeEach(function() {
engine = new ecstasy.Engine();
});
describe('#c() (registerComponent)', function() {
it('should return bit position of new component', function() {
for(var i = 0; i < 100; ++i) {
assert.equal(i, engine.c("c_"+i, null));
}
});
it('should return bit position of already added component', function() {
for(var i = 0; i < 100; ++i) {
engine.c("c_"+i, null);
assert.equal(i, engine.c("c_"+i, null));
}
});
});
describe('#getComponentConstructor()', function() {
it('should return correct constructor', function() {
for(var i = 0; i < 100; ++i) {
engine.c("c_"+i, "c_"+i);
}
for(var i = 0; i < 100; ++i) {
assert.equal("c_"+i, engine.getComponentConstructor("c_"+i));
}
});
it('should return null if unknown', function() {
assert.equal(null, engine.getComponentConstructor("value"));
});
});
describe('#getComponentBit()', function() {
it('should return bit position of already added component', function() {
for(var i = 0; i < 100; ++i) {
engine.c("c_"+i, "c_"+i);
}
for(var i = 0; i < 100; ++i) {
assert.equal(i, engine.getComponentBit("c_"+i));
}
});
it('should call registerComponent if not added', function() {
for(var i = 0; i < 100; ++i) {
assert.equal(i, engine.getComponentBit("c_"+i));
}
});
});
describe('#getComponentName()', function() {
it('should return name correctly', function() {
for(var i = 0; i < 100; ++i) {
engine.c("c_"+i, "c_"+i);
}
for(var i = 0; i < 100; ++i) {
assert.equal("c_"+i, engine.getComponentName(i));
}
});
});
describe('#getComponentsBitSet()', function() {
var valid, componentSet;
beforeEach(function() {
for(var i = 0; i < 100; ++i) {
engine.c("c_"+i, "c_"+i);
}
});
it('should return BitSet with the component bits', function() {
valid = new ecstasy.BitSet();
componentSet = [];
for(var i = 0; i < 100; ++i) {
valid.set(i, true);
componentSet.push("c_"+i);
}
assert.deepEqual(valid, engine.getComponentsBitSet(componentSet));
valid = new ecstasy.BitSet();
componentSet = [];
for(var i = 0; i < 100; i += 2) {
valid.set(i, true);
componentSet.push("c_"+i);
}
assert.deepEqual(valid, engine.getComponentsBitSet(componentSet));
});
});
describe('#obtainEntityId()', function() {
it('should return unique incrementing numbers', function() {
for(var i = 0; i < 100; ++i) {
assert.equal(i, engine.obtainEntityId());
}
});
});
describe('#addEntity()', function() {
var entity;
beforeEach(function() {
entity = new ecstasy.Entity(engine);
});
it('should set entity id after adding', function() {
engine.addEntity(entity);
assert.equal(0, entity.id);
});
it('should not add already added entity', function() {
engine.addEntity(entity);
assert.equal(0, entity.id);
engine.addEntity(entity);
assert.equal(0, entity.id);
});
it('should add entity with defined entity id', function() {
var entity2 = new ecstasy.Entity(engine);
entity2.id = 3;
engine.addEntity(entity2);
assert(entity2.listeners('componentAdded').length == 1);
assert(entity2.listeners('componentRemoved').length == 1);
entity.id = 6;
engine.addEntity(entity);
assert(entity.listeners('componentAdded').length == 1);
assert(entity.listeners('componentRemoved').length == 1);
});
it('should add event listeners', function() {
engine.addEntity(entity);
assert(entity.listeners('componentAdded').length == 1);
assert(entity.listeners('componentRemoved').length == 1);
});
it('should emit entityAdded', function(done) {
engine.on('entityAdded', function(e) {
assert(entity, e);
done();
});
engine.addEntity(entity);
});
it('should add to componentGroups', function() {
var entities = engine.e('hello');
entity.add('hello', {});
engine.addEntity(entity);
assert.equal(entity, entities[0]);
});
});
describe('#createEntity()', function() {
it('should return entity with id', function() {
for(var i = 0; i < 100; ++i) {
assert.equal(i, engine.createEntity().id);
}
});
it('should emit entityAdded', function(done) {
engine.on('entityAdded', function(e) {
done();
});
engine.createEntity();
});
});
describe('#removeEntity()', function() {
var entity;
beforeEach(function() {
entity = engine.createEntity();
});
it('should remove reference to entity from array', function() {
engine.removeEntity(entity);
assert.equal(null, engine.getEntity(entity.id));
});
it('should emit entityRemoved', function(done) {
engine.on('entityRemoved', function(e) {
assert(entity, e);
done();
});
engine.removeEntity(entity);
});
it('should remove event listeners', function() {
engine.removeEntity(entity);
assert(entity.listeners('componentAdded').length == 0);
assert(entity.listeners('componentRemoved').length == 0);
});
it('should remove from componentGroups', function() {
var entities = engine.e('hello');
entity.add('hello', {});
assert.equal(entity, entities[0]);
engine.removeEntity(entity);
assert.equal(null, entities[0]);
});
});
describe('#e()', function() {
var entity;
beforeEach(function() {
engine.c('test', function() {});
entity = engine.e().c('test', {});
});
it('should create new entity if there is no arguments', function() {
assert.equal(1, engine.e().id);
assert(engine.e() instanceof ecstasy.Entity);
});
it('should get an entity with that id if a number is given', function() {
assert.equal(entity, engine.e(0));
});
it('should create entity with template if an object is given', function() {
engine.c('pos', function(options) {
this.x = options.x || 0;
});
entity = engine.e({
test: {},
pos: {
x: 127
}
});
assert.equal(entity.id, 1);
assert(entity.c('test'));
assert(entity.c('pos'));
assert.equal(entity.c('pos').x, 127);
});
it('should call getEntitiesFor otherwise', function() {
assert.deepEqual([entity], engine.e('test'));
});
});
describe('#removeAllEntities()', function() {
var entity;
beforeEach(function() {
entity = engine.createEntity();
});
it('should remove all the entities', function() {
assert.equal(1, engine.getEntities().length);
engine.removeAllEntities();
assert.equal(0, engine.getEntities().length);
});
it('should emit entityRemoved', function(done) {
engine.on('entityRemoved', function(e) {
done();
});
engine.removeAllEntities();
});
});
describe('#getEntity()', function() {
var entity;
beforeEach(function() {
entity = engine.createEntity();
});
it('should return specified entity', function() {
assert.equal(entity, engine.getEntity(0));
});
it('should return null if not found', function() {
assert.equal(null, engine.getEntity(1));
});
});
describe('#registerComponentGroup()', function() {
var entity, group, group2;
beforeEach(function() {
engine.c('test', function() {});
engine.c('test2', function() {});
entity = engine.e().c('test', {});
group = ecstasy.ComponentGroup.createBuilder(engine)
.contain('test').build();
group2 = ecstasy.ComponentGroup.createBuilder(engine)
.contain('test2').build();
});
it('should return entities array', function() {
assert.deepEqual([entity], engine.registerComponentGroup(group));
assert.deepEqual([], engine.registerComponentGroup(group2));
});
it('should not register duplicate instances', function() {
var p1 = engine.registerComponentGroup(group);
var p2 = engine.registerComponentGroup(group);
assert.deepEqual([entity], p1);
assert.deepEqual([entity], p2);
assert.equal(p1, p2);
});
it('should not register different duplicate instances', function() {
var groupDup = ecstasy.ComponentGroup.createBuilder(engine)
.contain('test').build();
var p1 = engine.registerComponentGroup(group);
var p2 = engine.registerComponentGroup(groupDup);
assert.deepEqual([entity], p1);
assert.deepEqual([entity], p2);
assert.equal(p1, p2);
});
it('should set id of ComponentGroup', function() {
engine.registerComponentGroup(group);
engine.registerComponentGroup(group2);
assert.equal(0, group.id);
assert.equal(1, group2.id);
});
it('should emit entityAdded', function(done) {
group.on('entityAdded', function(e) {
assert(entity, e);
done();
});
engine.registerComponentGroup(group);
});
});
describe('#getEntitiesFor()', function() {
var entity, group;
beforeEach(function() {
engine.c('test', function() {});
entity = engine.e().c('test', {});
group = ecstasy.ComponentGroup.createBuilder(engine)
.contain('test').build();
});
it('should create ComponentGroup if string', function() {
assert.deepEqual([entity], engine.getEntitiesFor('test'));
});
it('should call registerComponentGroup if ComponentGroup', function() {
assert.deepEqual([entity], engine.getEntitiesFor(group));
});
});
describe('#getComponentGroup()', function() {
var entity, group;
beforeEach(function() {
engine.c('test', function() {});
entity = engine.e().c('test', {});
group = ecstasy.ComponentGroup.createBuilder(engine)
.contain('test').build();
});
it('should return its ComponentGroup', function() {
var entities = engine.getEntitiesFor(group);
assert.equal(group, engine.getComponentGroup(entities));
});
});
describe('#updateComponentGroup()', function() {
var entity, entities;
beforeEach(function() {
entity = engine.e();
entities = engine.e('test');
});
it('should add to componentGroups if matches', function() {
entity.add('test', {});
assert.equal(entity, entities[0]);
});
it('should remove from componentGroups if not matches anymore', function() {
entity.add('test', {});
assert.equal(entity, entities[0]);
entity.remove('test');
assert.equal(null, entities[0]);
});
});
describe('#s()', function() {
it('should return SystemBuilder if that key doesn\'t exist', function() {
assert(engine.s('test') instanceof ecstasy.SystemBuilder);
});
it('should return the System if that key exists', function() {
var system = {};
engine.addSystem('test', system);
assert.equal(system, engine.s('test'));
});
it('should add the System otherwise', function() {
var system = {};
engine.s('test', system);
assert.equal(system, engine.s('test'));
});
});
describe('#addSystem()', function() {
var system;
beforeEach(function() {
system = {};
});
it('should set id of the system', function() {
engine.addSystem('key', system);
assert.equal(0, system._id);
});
it('should call system.add()', function(done) {
system.add = function(e) {
assert.equal(engine, e);
done();
}
engine.addSystem('key', system);
});
it('should set _systemsSortRequired', function() {
engine.addSystem('key', system);
assert(engine._systemsSortRequired);
});
});
describe('#createSystem()', function() {
it('should return a SystemBuilder', function() {
assert(engine.createSystem('key') instanceof ecstasy.SystemBuilder);
});
});
describe('#getSystem()', function() {
var system;
beforeEach(function() {
system = {};
engine.addSystem('key', system);
});
it('should return a system with that key', function() {
assert.equal(system, engine.getSystem('key'));
});
});
describe('#removeSystem()', function() {
var system;
beforeEach(function() {
system = {};
engine.addSystem('key', system);
});
it('should remove reference to system', function() {
engine.removeSystem('key');
assert.equal(null, engine.getSystem('key'));
});
it('should call system.remove()', function(done) {
system.remove = function(e) {
assert.equal(engine, e);
done();
}
engine.removeSystem('key');
});
});
describe('#sortSystem()', function() {
var system1, system2, system3;
beforeEach(function() {
system1 = {priority: 0};
system2 = {priority: 0};
system3 = {priority: 0};
system4 = {priority: 100};
});
it('should sort the systems array in right order', function() {
engine.addSystem('4', system4);
engine.addSystem('3', system3);
engine.addSystem('2', system2);
engine.addSystem('1', system1);
engine.sortSystems();
assert.equal(system3, engine.systems[0]);
assert.equal(system2, engine.systems[1]);
assert.equal(system1, engine.systems[2]);
assert.equal(system4, engine.systems[3]);
});
it('should sort the systems array in right order', function() {
engine.addSystem('1', system1);
engine.addSystem('2', system2);
engine.addSystem('3', system3);
engine.addSystem('4', system4);
engine.sortSystems();
assert.equal(system1, engine.systems[0]);
assert.equal(system2, engine.systems[1]);
assert.equal(system3, engine.systems[2]);
assert.equal(system4, engine.systems[3]);
});
it('should sort the systems array in right order', function() {
engine.addSystem('1', system1);
engine.addSystem('2', system2);
engine.addSystem('3', system3);
system1._id = 2;
system3._id = 0;
engine.sortSystems();
assert.equal(system3, engine.systems[0]);
assert.equal(system2, engine.systems[1]);
assert.equal(system1, engine.systems[2]);
});
it('should sort the systems array in right order', function() {
engine.addSystem('1', system1);
engine.addSystem('2', system2);
engine.addSystem('3', system3);
system2._id = 0;
engine.sortSystems();
assert.equal(system1, engine.systems[0]);
assert.equal(system2, engine.systems[1]);
assert.equal(system3, engine.systems[2]);
});
});
describe('#update()', function() {
var system;
beforeEach(function() {
system = {};
engine.addSystem('key', system);
});
it('should call system.update()', function(done) {
system.update = function(delta) {
assert.equal(12, delta);
done();
}
engine.update(12);
});
});
describe('#serialize()', function() {
it('should serialize engine correctly', function() {
// I don't think systems and components should be serialized
engine.c('test', function() {this.data = '11'});
engine.e().c('test', {});
assert.deepEqual({
components: ['test'],
systems: [],
entities: [
{
id: 0,
components: {
'test': {
data: '11'
}
}
}
],
entityPos: 1
}, engine.serialize());
});
});
describe('#deserialize()', function() {
it('should deserialize engine correctly', function() {
engine.c('test', function() {this.data = '11'});
engine.deserialize({
entities: [
{
id: 0,
components: {
'test': {
data: '11'
}
}
}
],
entityPos: 1
});
assert.deepEqual({
data: '11'
}, engine.e(0).c('test'));
});
});
});
| {
"content_hash": "cb34b938565608671ef699618106094a",
"timestamp": "",
"source": "github",
"line_count": 507,
"max_line_length": 80,
"avg_line_length": 32.21696252465483,
"alnum_prop": 0.5739561650544875,
"repo_name": "yoo2001818/ecstasy",
"id": "3f380ea29b0b8a11f20767b06dfdf7f8ade040d9",
"size": "16334",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "test/engine.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "86282"
}
],
"symlink_target": ""
} |
package org.moe.gradle.tasks;
import org.gradle.api.GradleException;
import org.gradle.api.file.ConfigurableFileCollection;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.InputFile;
import org.gradle.api.tasks.InputFiles;
import org.gradle.api.tasks.Internal;
import org.gradle.api.tasks.OutputFile;
import org.gradle.api.tasks.SourceSet;
import org.moe.common.utils.NativeUtil;
import org.moe.gradle.MoePlugin;
import org.moe.gradle.MoeSDK;
import org.moe.gradle.anns.IgnoreUnused;
import org.moe.gradle.anns.NotNull;
import org.moe.gradle.anns.Nullable;
import org.moe.gradle.remote.Server;
import org.moe.gradle.remote.file.FileList;
import org.moe.gradle.utils.Arch;
import org.moe.gradle.utils.Mode;
import org.moe.gradle.utils.Require;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
public class Dex2Oat extends AbstractBaseTask {
private static final String CONVENTION_DEX2OAT_EXEC = "dex2oatExec";
private static final String CONVENTION_ARCH_FAMILY = "archFamily";
private static final String CONVENTION_BASE = "base";
private static final String CONVENTION_IMAGE_CLASSES = "imageClasses";
private static final String CONVENTION_EMIT_DEBUG_INFO = "emitDebugInfo";
private static final String CONVENTION_INPUT_FILES = "inputFiles";
private static final String CONVENTION_COMPILER_BACKEND = "compilerBackend";
private static final String CONVENTION_DEST_IMAGE_FILE = "destImageFile";
private static final String CONVENTION_DEST_OAT_FILE = "destOatFile";
private static final String BACKEND_QUICK = "Quick";
private static final String BACKEND_OPTIMIZING = "Optimizing";
private static final String[] ALL_BACKENDS = new String[]{BACKEND_QUICK, BACKEND_OPTIMIZING};
@Nullable
private Object dex2oatExec;
@InputFile
@NotNull
public File getDex2oatExec() {
return getProject().file(getOrConvention(dex2oatExec, CONVENTION_DEX2OAT_EXEC));
}
@IgnoreUnused
public void setDex2oatExec(@Nullable Object dex2oatExec) {
this.dex2oatExec = dex2oatExec;
}
@Nullable
private String archFamily;
@Input
@NotNull
public String getArchFamily() {
return getOrConvention(archFamily, CONVENTION_ARCH_FAMILY);
}
@IgnoreUnused
public void setArchFamily(@Nullable String archFamily) {
this.archFamily = archFamily == null ? null : Arch.validateArchFamily(archFamily);
}
@Nullable
private Long base;
@Input
@NotNull
public Long getBase() {
return getOrConvention(base, CONVENTION_BASE);
}
@IgnoreUnused
public void setBase(@Nullable Long base) {
this.base = base;
}
@Nullable
private Object imageClasses;
@InputFile
@NotNull
public File getImageClasses() {
return getProject().file(getOrConvention(imageClasses, CONVENTION_IMAGE_CLASSES));
}
@IgnoreUnused
public void setImageClasses(@Nullable Object imageClasses) {
this.imageClasses = imageClasses;
}
@Nullable
private Boolean emitDebugInfo;
@Input
@NotNull
public Boolean getEmitDebugInfo() {
return getOrConvention(emitDebugInfo, CONVENTION_EMIT_DEBUG_INFO);
}
@IgnoreUnused
public void setEmitDebugInfo(@Nullable Boolean emitDebugInfo) {
this.emitDebugInfo = emitDebugInfo;
}
@Nullable
private Set<Object> inputFiles;
@InputFiles
@NotNull
public ConfigurableFileCollection getInputFiles() {
return getProject().files(getOrConvention(inputFiles, CONVENTION_INPUT_FILES));
}
@IgnoreUnused
public void setInputFiles(@Nullable Collection<Object> inputFiles) {
this.inputFiles = inputFiles == null ? null : new HashSet<>(inputFiles);
}
@Nullable
private String compilerBackend;
@Input
@NotNull
public String getCompilerBackend() {
return getOrConvention(compilerBackend, CONVENTION_COMPILER_BACKEND);
}
@IgnoreUnused
public void setCompilerBackend(@Nullable String compilerBackend) {
this.compilerBackend = compilerBackend == null ? null : validateBackend(compilerBackend);
}
@Nullable
private Object destImageFile;
@OutputFile
@NotNull
public File getDestImageFile() {
return getProject().file(getOrConvention(destImageFile, CONVENTION_DEST_IMAGE_FILE));
}
@IgnoreUnused
public void setDestImageFile(@Nullable Object destImageFile) {
this.destImageFile = destImageFile;
}
@Nullable
private Object destOatFile;
@OutputFile
@NotNull
public File getDestOatFile() {
return getProject().file(getOrConvention(destOatFile, CONVENTION_DEST_OAT_FILE));
}
@IgnoreUnused
public void setDestOatFile(@Nullable Object destOatFile) {
this.destOatFile = destOatFile;
}
@Override
protected void run() {
getMoePlugin().requireMacHostOrRemoteServerConfig(this);
final Server remoteServer = getMoePlugin().getRemoteServer();
if (remoteServer != null) {
final String dex2oatExec;
final String imageClasses;
try {
dex2oatExec = remoteServer.getSDKRemotePath(getDex2oatExec());
imageClasses = remoteServer.getSDKRemotePath(getImageClasses());
} catch (IOException e) {
throw new GradleException("Unsupported configuration", e);
}
final FileList fileList = new FileList(getProject().getProjectDir(), remoteServer.getBuildDir());
StringBuilder dexFiles = new StringBuilder();
StringBuilder remoteDexFilesCheck = new StringBuilder();
getInputFiles().forEach(it -> {
String path;
boolean needsUpload = false;
try {
path = remoteServer.getSDKRemotePath(it);
} catch (IOException ignore) {
needsUpload = true;
try {
path = getInnerProjectRelativePath(it).toString();
} catch (IOException e) {
throw new GradleException("Unsupported configuration", e);
}
}
if (dexFiles.length() > 0) {
dexFiles.append(':');
remoteDexFilesCheck.append(" && ");
}
if (needsUpload) {
final String remotePath = fileList.add(it);
dexFiles.append(remotePath);
remoteDexFilesCheck.append("[ -f '").append(remotePath).append("' ]");
} else {
dexFiles.append(path);
remoteDexFilesCheck.append("[ -f '").append(path).append("' ]");
}
});
remoteServer.upload("dex2oat inputs", fileList);
remoteServer.exec("dex2oat inputs check", remoteDexFilesCheck.toString());
final Path destArtRel;
final Path destOatRel;
try {
destArtRel = getInnerProjectRelativePath(getDestImageFile());
destOatRel = getInnerProjectRelativePath(getDestOatFile());
} catch (IOException e) {
throw new GradleException("Unsupported configuration", e);
}
final String remoteDestArt = remoteServer.getRemotePath(destArtRel);
final String remoteDestOat = remoteServer.getRemotePath(destOatRel);
remoteServer.exec("prepare output directories", "" +
"mkdir -p `dirname " + remoteDestArt + "` && " +
"mkdir -p `dirname " + remoteDestOat + "`");
String optionalRosetta = "";
if (remoteServer.isRemoteAARCH64() && !Arch.FAMILY_ARM64.equalsIgnoreCase(getArchFamily())) {
optionalRosetta = "arch --x86_64 ";
}
remoteServer.exec("dex2oat", optionalRosetta + dex2oatExec + " " +
"--instruction-set=" + Arch.validateArchFamily(getArchFamily()) + " " +
"--base=0x" + Long.toHexString(getBase()) + " " +
"--compiler-backend=" + validateBackend(getCompilerBackend()) + " " +
(getEmitDebugInfo() ? "--generate-debug-info" : "--no-generate-debug-info") + " " +
"--image=" + remoteDestArt + " " +
"--image-classes=" + imageClasses + " " +
"--oat-file=" + remoteDestOat + " " +
"--dex-file=" + dexFiles
);
remoteServer.downloadFile("art", remoteDestArt, getDestImageFile().getParentFile());
remoteServer.downloadFile("oat", remoteDestOat, getDestOatFile().getParentFile());
} else {
exec(spec -> {
// Set executable
if (NativeUtil.isHostAARCH64() && !Arch.FAMILY_ARM64.equalsIgnoreCase(getArchFamily())) {
// Run dex2oat using rosetta 2 when compiling non-arm64 target on Apple silicon
// because currently the arm64 version of dex2oat does not work reliably due to
// the issue of word size & alignment mismatch.
// TODO: solve this?
spec.setExecutable("arch");
spec.args("--x86_64");
spec.args(getDex2oatExec());
} else {
spec.setExecutable(getDex2oatExec());
}
// Set target options
spec.args("--instruction-set=" + Arch.validateArchFamily(getArchFamily()));
spec.args("--base=0x" + Long.toHexString(getBase()));
// Set compiler backend
spec.args("--compiler-backend=" + validateBackend(getCompilerBackend()));
// Include or not include ELF symbols in oat file
if (getEmitDebugInfo()) {
spec.args("--generate-debug-info");
} else {
spec.args("--no-generate-debug-info");
}
// Set files
spec.args("--image=" + getDestImageFile().getAbsolutePath());
spec.args("--image-classes=" + getImageClasses().getAbsolutePath());
spec.args("--oat-file=" + getDestOatFile().getAbsolutePath());
// Set inputs
StringBuilder dexFiles = new StringBuilder();
getInputFiles().forEach(it -> {
if (dexFiles.length() > 0) {
dexFiles.append(':');
}
dexFiles.append(it.getAbsolutePath());
});
spec.args("--dex-file=" + dexFiles);
});
}
}
private Dex dexTaskDep;
@NotNull
@Internal
public Dex getDexTaskDep() {
return Require.nonNull(dexTaskDep);
}
@NotNull
protected final void setupMoeTask(@NotNull SourceSet sourceSet, @NotNull Mode mode, @NotNull String archFamily) {
Require.nonNull(sourceSet);
Require.nonNull(mode);
Require.nonNull(archFamily);
setSupportsRemoteBuild(true);
final MoeSDK sdk = getMoeSDK();
// Construct default output path
final Path out = Paths.get(MoePlugin.MOE, sourceSet.getName(), "dex2oat", mode.name + "-" + archFamily);
setDescription("Generates art+oat files (sourceset: " + sourceSet.getName() + ", mode: " + mode.name +
", arch-family: " + archFamily + ").");
// Add dependencies
final Dex dexTask = getMoePlugin().getTaskBy(Dex.class, sourceSet, mode);
dexTaskDep = dexTask;
dependsOn(dexTask);
// Update convention mapping
addConvention(CONVENTION_DEX2OAT_EXEC, sdk::getDex2OatExec);
addConvention(CONVENTION_ARCH_FAMILY, () -> archFamily);
addConvention(CONVENTION_BASE, () -> {
if (Arch.FAMILY_ARM.equals(archFamily)) {
return 0x10000000L;
} else if (Arch.FAMILY_ARM64.equals(archFamily)) {
return 0x10000000L;
} else if (Arch.FAMILY_X86.equals(archFamily)) {
return 0x40000000L;
} else if (Arch.FAMILY_X86_64.equals(archFamily)) {
return 0x40000000L;
} else {
throw new GradleException("Unexpected arch family '" + archFamily + "'");
}
});
addConvention(CONVENTION_IMAGE_CLASSES, sdk::getPreloadedClassesFile);
addConvention(CONVENTION_EMIT_DEBUG_INFO, () -> mode == Mode.DEBUG);
addConvention(CONVENTION_INPUT_FILES, () -> {
final Set<File> files = new HashSet<>();
files.addAll(dexTask.getDestJars());
return files;
});
addConvention(CONVENTION_COMPILER_BACKEND, () -> BACKEND_QUICK);
addConvention(CONVENTION_DEST_IMAGE_FILE, () -> resolvePathInBuildDir(out, "image.art"));
addConvention(CONVENTION_DEST_OAT_FILE, () -> resolvePathInBuildDir(out, "application.oat"));
addConvention(CONVENTION_LOG_FILE, () -> resolvePathInBuildDir(out, "Dex2Oat.log"));
}
private static String validateBackend(@NotNull String name) {
Require.nonNull(name);
for (String backend : ALL_BACKENDS) {
if (backend.equalsIgnoreCase(name)) {
return backend;
}
}
throw new GradleException("Unknown backend '" + name + "', supported: " + Arrays.asList(ALL_BACKENDS));
}
}
| {
"content_hash": "809bcac6a35a412226d2d5d617cade88",
"timestamp": "",
"source": "github",
"line_count": 372,
"max_line_length": 117,
"avg_line_length": 36.986559139784944,
"alnum_prop": 0.6048404680572717,
"repo_name": "multi-os-engine/moe-plugin-gradle",
"id": "de0393156c759413e8fd37f0d7b3e337c7a567a7",
"size": "14316",
"binary": false,
"copies": "1",
"ref": "refs/heads/moe-master",
"path": "src/main/java/org/moe/gradle/tasks/Dex2Oat.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "514344"
},
{
"name": "Kotlin",
"bytes": "15664"
}
],
"symlink_target": ""
} |
#undef TARGET_FPMATH_DEFAULT
#define TARGET_FPMATH_DEFAULT (TARGET_SSE2 ? FPMATH_SSE : FPMATH_387)
#undef TARGET_SUBTARGET32_ISA_DEFAULT
#define TARGET_SUBTARGET32_ISA_DEFAULT \
(OPTION_MASK_ISA_MMX | OPTION_MASK_ISA_SSE | OPTION_MASK_ISA_SSE2)
| {
"content_hash": "133ed82593d2dcb4ebd649ccae429e2f",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 69,
"avg_line_length": 31.375,
"alnum_prop": 0.7609561752988048,
"repo_name": "execunix/vinos",
"id": "4e4656fa0d1e55770df289b423c66cabf2a51048",
"size": "932",
"binary": false,
"copies": "27",
"ref": "refs/heads/master",
"path": "external/gpl3/gcc/dist/gcc/config/i386/ssemath.h",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<!DOCTYPE html>
<!-- This site was created in Webflow. http://www.webflow.com -->
<!-- Last Published: Wed Aug 22 2018 10:36:56 GMT+0000 (UTC) -->
<html data-wf-page="5b585594e017c37b31b35b32" data-wf-site="5b584d6c929c5a13cdce1830">
<head>
<meta charset="utf-8">
<title>Not Found</title>
<meta content="Domenico Solazzo is a software developer with more than 15 years of experience. He has experience with several technologies. Needing help with your SaaS platform? ReactJS? GraphQL? React Native or Swift? Let's talk and collaborate together!" name="description">
<meta content="Not Found" property="og:title">
<meta content="width=device-width, initial-scale=1" name="viewport">
<meta content="Webflow" name="generator">
<link href="css/normalize.css" rel="stylesheet" type="text/css">
<link href="css/webflow.css" rel="stylesheet" type="text/css">
<link href="css/domenicosolazzo.webflow.css" rel="stylesheet" type="text/css">
<script src="https://ajax.googleapis.com/ajax/libs/webfont/1.4.7/webfont.js" type="text/javascript"></script>
<script type="text/javascript">WebFont.load({ google: { families: ["Oswald:200,300,400,500,600,700","Droid Sans:400,700","Montserrat:100,100italic,200,200italic,300,300italic,400,400italic,500,500italic,600,600italic,700,700italic,800,800italic,900,900italic","Merriweather:300,300italic,400,400italic,700,700italic,900,900italic","Exo:100,100italic,200,200italic,300,300italic,400,400italic,500,500italic,600,600italic,700,700italic,800,800italic,900,900italic","Roboto:300,regular,500"] }});</script>
<!-- [if lt IE 9]><script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.min.js" type="text/javascript"></script><![endif] -->
<script type="text/javascript">!function(o,c){var n=c.documentElement,t=" w-mod-";n.className+=t+"js",("ontouchstart"in o||o.DocumentTouch&&c instanceof DocumentTouch)&&(n.className+=t+"touch")}(window,document);</script>
<link href="images/Favicon.png" rel="shortcut icon" type="image/x-icon">
<link href="images/Webclip.png" rel="apple-touch-icon">
<script type="text/javascript">(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');ga('create', 'UA-18172240-2', 'auto');ga('set', 'anonymizeIp', true);ga('send', 'pageview');</script>
</head>
<body>
<div class="utility-page-wrap">
<div class="utility-page-content"><img src="https://d3e54v103j8qbb.cloudfront.net/static/page-not-found.211a85e40c.svg">
<h2>Page not found</h2>
<div>The page you are looking for doesn't exist or has been moved.</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" type="text/javascript" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="js/webflow.js" type="text/javascript"></script>
<!-- [if lte IE 9]><script src="https://cdnjs.cloudflare.com/ajax/libs/placeholders/3.0.2/placeholders.min.js"></script><![endif] -->
</body>
</html> | {
"content_hash": "0fb7053e95447c4b654f45c972598616",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 509,
"avg_line_length": 95.3529411764706,
"alnum_prop": 0.7196175200493522,
"repo_name": "domenicosolazzo/domenicosolazzo.github.io",
"id": "be5d7a4081ac4b78c84e5f6e7081bedf674c34e1",
"size": "3242",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "404.html",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "60964"
},
{
"name": "HTML",
"bytes": "29764"
}
],
"symlink_target": ""
} |
package org.pentaho.di.trans.steps.getfilesrowscount;
import java.util.List;
import java.util.Map;
import org.apache.commons.vfs2.FileObject;
import org.pentaho.di.core.CheckResult;
import org.pentaho.di.core.CheckResultInterface;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.util.Utils;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleStepException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.fileinput.FileInputList;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.row.value.ValueMetaInteger;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.repository.ObjectId;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.resource.ResourceDefinition;
import org.pentaho.di.resource.ResourceNamingInterface;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStepMeta;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
import org.pentaho.metastore.api.IMetaStore;
import org.w3c.dom.Node;
public class GetFilesRowsCountMeta extends BaseStepMeta implements StepMetaInterface {
private static Class<?> PKG = GetFilesRowsCountMeta.class; // for i18n purposes, needed by Translator2!!
public static final String[] RequiredFilesDesc = new String[] {
BaseMessages.getString( PKG, "System.Combo.No" ), BaseMessages.getString( PKG, "System.Combo.Yes" ) };
public static final String[] RequiredFilesCode = new String[] { "N", "Y" };
private static final String NO = "N";
private static final String YES = "Y";
public static final String DEFAULT_ROWSCOUNT_FIELDNAME = "rowscount";
/** Array of filenames */
private String[] fileName;
/** Wildcard or filemask (regular expression) */
private String[] fileMask;
/** Wildcard or filemask to exclude (regular expression) */
private String[] excludeFileMask;
/** Flag indicating that a row number field should be included in the output */
private boolean includeFilesCount;
/** The name of the field in the output containing the file number */
private String filesCountFieldName;
/** The name of the field in the output containing the row number */
private String rowsCountFieldName;
/** The row separator type */
private String RowSeparator_format;
/** The row separator */
private String RowSeparator;
/** file name from previous fields **/
private boolean filefield;
private boolean isaddresult;
private String outputFilenameField;
/** Array of boolean values as string, indicating if a file is required. */
private String[] fileRequired;
/** Array of boolean values as string, indicating if we need to fetch sub folders. */
private String[] includeSubFolders;
/** Flag : check if a data is there right after separator **/
private boolean smartCount;
public GetFilesRowsCountMeta() {
super(); // allocate BaseStepMeta
}
/**
* @return Returns the row separator.
*/
public String getRowSeparator() {
return RowSeparator;
}
/**
* @param RowSeparatorin
* The RowSeparator to set.
*/
public void setRowSeparator( String RowSeparatorin ) {
this.RowSeparator = RowSeparatorin;
}
/**
* @return Returns the row separator format.
*/
public String getRowSeparatorFormat() {
return RowSeparator_format;
}
/**
* @param isaddresult
* The isaddresult to set.
*/
public void setAddResultFile( boolean isaddresult ) {
this.isaddresult = isaddresult;
}
/**
* @param smartCount
* The smartCount to set.
*/
public void setSmartCount( boolean smartCount ) {
this.smartCount = smartCount;
}
/**
* @return Returns the excludeFileMask.
* Deprecated due to typo
*/
@Deprecated
public String[] getExludeFileMask() {
return excludeFileMask;
}
/**
* @return Returns the excludeFileMask.
*/
public String[] getExcludeFileMask() {
return excludeFileMask;
}
/**
* @param excludeFileMask
* The excludeFileMask to set.
*/
public void setExcludeFileMask( String[] excludeFileMask ) {
this.excludeFileMask = excludeFileMask;
}
/**
* @return Returns isaddresult.
*/
public boolean isAddResultFile() {
return isaddresult;
}
/**
* @return Returns smartCount.
*/
public boolean isSmartCount() {
return smartCount;
}
/**
* @return Returns the output filename_Field.
* Deprecated due to typo
*/
@Deprecated
public String setOutputFilenameField() {
return outputFilenameField;
}
/**
* @return Returns the output filename_Field.
*/
public String getOutputFilenameField() {
return outputFilenameField;
}
/**
* @param outputFilenameField
* The output filename_field to set.
*/
public void setOutputFilenameField( String outputFilenameField ) {
this.outputFilenameField = outputFilenameField;
}
/**
* @return Returns the File field.
*/
public boolean isFileField() {
return filefield;
}
/**
* @param filefield
* The file field to set.
*/
public void setFileField( boolean filefield ) {
this.filefield = filefield;
}
/**
* @param RowSeparator_formatin
* The RowSeparator_format to set.
*/
public void setRowSeparatorFormat( String RowSeparator_formatin ) {
this.RowSeparator_format = RowSeparator_formatin;
}
/**
* @return Returns the fileMask.
*/
public String[] getFileMask() {
return fileMask;
}
public void setFileRequired( String[] fileRequiredin ) {
for ( int i = 0; i < fileRequiredin.length; i++ ) {
this.fileRequired[i] = getRequiredFilesCode( fileRequiredin[i] );
}
}
public String[] getIncludeSubFolders() {
return includeSubFolders;
}
public void setIncludeSubFolders( String[] includeSubFoldersin ) {
for ( int i = 0; i < includeSubFoldersin.length; i++ ) {
this.includeSubFolders[i] = getRequiredFilesCode( includeSubFoldersin[i] );
}
}
public String getRequiredFilesCode( String tt ) {
if ( tt == null ) {
return RequiredFilesCode[0];
}
if ( tt.equals( RequiredFilesDesc[1] ) ) {
return RequiredFilesCode[1];
} else {
return RequiredFilesCode[0];
}
}
public String getRequiredFilesDesc( String tt ) {
if ( tt == null ) {
return RequiredFilesDesc[0];
}
if ( tt.equals( RequiredFilesCode[1] ) ) {
return RequiredFilesDesc[1];
} else {
return RequiredFilesDesc[0];
}
}
/**
* @param fileMask
* The fileMask to set.
*/
public void setFileMask( String[] fileMask ) {
this.fileMask = fileMask;
}
/**
* @return Returns the fileName.
*/
public String[] getFileName() {
return fileName;
}
/**
* @param fileName
* The fileName to set.
*/
public void setFileName( String[] fileName ) {
this.fileName = fileName;
}
/**
* @return Returns the includeCountFiles.
*/
public boolean includeCountFiles() {
return includeFilesCount;
}
/**
* @param includeFilesCount
* The "includes files count" flag to set.
*/
public void setIncludeCountFiles( boolean includeFilesCount ) {
this.includeFilesCount = includeFilesCount;
}
public String[] getFileRequired() {
return this.fileRequired;
}
/**
* @return Returns the FilesCountFieldName.
*/
public String getFilesCountFieldName() {
return filesCountFieldName;
}
/**
* @return Returns the RowsCountFieldName.
*/
public String getRowsCountFieldName() {
return rowsCountFieldName;
}
/**
* @param filesCountFieldName
* The filesCountFieldName to set.
*/
public void setFilesCountFieldName( String filesCountFieldName ) {
this.filesCountFieldName = filesCountFieldName;
}
/**
* @param rowsCountFieldName
* The rowsCountFieldName to set.
*/
public void setRowsCountFieldName( String rowsCountFieldName ) {
this.rowsCountFieldName = rowsCountFieldName;
}
public void loadXML( Node stepnode, List<DatabaseMeta> databases, IMetaStore metaStore ) throws KettleXMLException {
readData( stepnode );
}
public Object clone() {
GetFilesRowsCountMeta retval = (GetFilesRowsCountMeta) super.clone();
int nrFiles = fileName.length;
retval.allocate( nrFiles );
System.arraycopy( fileName, 0, retval.fileName, 0, nrFiles );
System.arraycopy( fileMask, 0, retval.fileMask, 0, nrFiles );
System.arraycopy( excludeFileMask, 0, retval.excludeFileMask, 0, nrFiles );
System.arraycopy( fileRequired, 0, retval.fileRequired, 0, nrFiles );
System.arraycopy( includeSubFolders, 0, retval.includeSubFolders, 0, nrFiles );
return retval;
}
public String getXML() {
StringBuilder retval = new StringBuilder( 300 );
retval.append( " " ).append( XMLHandler.addTagValue( "files_count", includeFilesCount ) );
retval.append( " " ).append( XMLHandler.addTagValue( "files_count_fieldname", filesCountFieldName ) );
retval.append( " " ).append( XMLHandler.addTagValue( "rows_count_fieldname", rowsCountFieldName ) );
retval.append( " " ).append( XMLHandler.addTagValue( "rowseparator_format", RowSeparator_format ) );
retval.append( " " ).append( XMLHandler.addTagValue( "row_separator", RowSeparator ) );
retval.append( " " ).append( XMLHandler.addTagValue( "isaddresult", isaddresult ) );
retval.append( " " ).append( XMLHandler.addTagValue( "filefield", filefield ) );
retval.append( " " ).append( XMLHandler.addTagValue( "filename_Field", outputFilenameField ) );
retval.append( " " ).append( XMLHandler.addTagValue( "smartCount", smartCount ) );
retval.append( " <file>" ).append( Const.CR );
for ( int i = 0; i < fileName.length; i++ ) {
retval.append( " " ).append( XMLHandler.addTagValue( "name", fileName[i] ) );
retval.append( " " ).append( XMLHandler.addTagValue( "filemask", fileMask[i] ) );
retval.append( " " ).append( XMLHandler.addTagValue( "exclude_filemask", excludeFileMask[i] ) );
retval.append( " " ).append( XMLHandler.addTagValue( "file_required", fileRequired[i] ) );
retval.append( " " ).append( XMLHandler.addTagValue( "include_subfolders", includeSubFolders[i] ) );
}
retval.append( " </file>" ).append( Const.CR );
return retval.toString();
}
/**
* Adjust old outdated values to new ones
*
* @param original
* The original value
* @return The new/correct equivelant
*/
private String scrubOldRowSeparator( String original ) {
if ( original != null ) {
// Update old files to the new format
if ( original.equalsIgnoreCase( "CR" ) ) {
return "LINEFEED";
} else if ( original.equalsIgnoreCase( "LF" ) ) {
return "CARRIAGERETURN";
}
}
return original;
}
private void readData( Node stepnode ) throws KettleXMLException {
try {
includeFilesCount = "Y".equalsIgnoreCase( XMLHandler.getTagValue( stepnode, "files_count" ) );
filesCountFieldName = XMLHandler.getTagValue( stepnode, "files_count_fieldname" );
rowsCountFieldName = XMLHandler.getTagValue( stepnode, "rows_count_fieldname" );
RowSeparator_format = scrubOldRowSeparator( XMLHandler.getTagValue( stepnode, "rowseparator_format" ) );
RowSeparator = XMLHandler.getTagValue( stepnode, "row_separator" );
smartCount = "Y".equalsIgnoreCase( XMLHandler.getTagValue( stepnode, "smartCount" ) );
String addresult = XMLHandler.getTagValue( stepnode, "isaddresult" );
if ( Utils.isEmpty( addresult ) ) {
isaddresult = true;
} else {
isaddresult = "Y".equalsIgnoreCase( addresult );
}
filefield = "Y".equalsIgnoreCase( XMLHandler.getTagValue( stepnode, "filefield" ) );
outputFilenameField = XMLHandler.getTagValue( stepnode, "filename_Field" );
Node filenode = XMLHandler.getSubNode( stepnode, "file" );
int nrFiles = XMLHandler.countNodes( filenode, "name" );
allocate( nrFiles );
for ( int i = 0; i < nrFiles; i++ ) {
Node filenamenode = XMLHandler.getSubNodeByNr( filenode, "name", i );
Node filemasknode = XMLHandler.getSubNodeByNr( filenode, "filemask", i );
Node excludefilemasknode = XMLHandler.getSubNodeByNr( filenode, "exclude_filemask", i );
Node fileRequirednode = XMLHandler.getSubNodeByNr( filenode, "file_required", i );
Node includeSubFoldersnode = XMLHandler.getSubNodeByNr( filenode, "include_subfolders", i );
fileName[i] = XMLHandler.getNodeValue( filenamenode );
fileMask[i] = XMLHandler.getNodeValue( filemasknode );
excludeFileMask[i] = XMLHandler.getNodeValue( excludefilemasknode );
fileRequired[i] = XMLHandler.getNodeValue( fileRequirednode );
includeSubFolders[i] = XMLHandler.getNodeValue( includeSubFoldersnode );
}
} catch ( Exception e ) {
throw new KettleXMLException( "Unable to load step info from XML", e );
}
}
public void allocate( int nrfiles ) {
fileName = new String[nrfiles];
fileMask = new String[nrfiles];
excludeFileMask = new String[nrfiles];
fileRequired = new String[nrfiles];
includeSubFolders = new String[nrfiles];
}
public void setDefault() {
smartCount = false;
outputFilenameField = "";
filefield = false;
isaddresult = true;
includeFilesCount = false;
filesCountFieldName = "";
rowsCountFieldName = "rowscount";
RowSeparator_format = "CR";
RowSeparator = "";
int nrFiles = 0;
allocate( nrFiles );
for ( int i = 0; i < nrFiles; i++ ) {
fileName[i] = "filename" + ( i + 1 );
fileMask[i] = "";
excludeFileMask[i] = "";
fileRequired[i] = RequiredFilesCode[0];
includeSubFolders[i] = RequiredFilesCode[0];
}
}
public void getFields( RowMetaInterface r, String name, RowMetaInterface[] info, StepMeta nextStep,
VariableSpace space, Repository repository, IMetaStore metaStore ) throws KettleStepException {
ValueMetaInterface v =
new ValueMetaInteger( space.environmentSubstitute( rowsCountFieldName ) );
v.setLength( ValueMetaInterface.DEFAULT_INTEGER_LENGTH, 0 );
v.setOrigin( name );
r.addValueMeta( v );
if ( includeFilesCount ) {
v = new ValueMetaInteger( space.environmentSubstitute( filesCountFieldName ) );
v.setLength( ValueMetaInterface.DEFAULT_INTEGER_LENGTH, 0 );
v.setOrigin( name );
r.addValueMeta( v );
}
}
public void readRep( Repository rep, IMetaStore metaStore, ObjectId id_step, List<DatabaseMeta> databases ) throws KettleException {
try {
includeFilesCount = rep.getStepAttributeBoolean( id_step, "files_count" );
filesCountFieldName = rep.getStepAttributeString( id_step, "files_count_fieldname" );
rowsCountFieldName = rep.getStepAttributeString( id_step, "rows_count_fieldname" );
RowSeparator_format = scrubOldRowSeparator( rep.getStepAttributeString( id_step, "rowseparator_format" ) );
RowSeparator = rep.getStepAttributeString( id_step, "row_separator" );
smartCount = rep.getStepAttributeBoolean( id_step, "smartCount" );
String addresult = rep.getStepAttributeString( id_step, "isaddresult" );
if ( Utils.isEmpty( addresult ) ) {
isaddresult = true;
} else {
isaddresult = rep.getStepAttributeBoolean( id_step, "isaddresult" );
}
filefield = rep.getStepAttributeBoolean( id_step, "filefield" );
outputFilenameField = rep.getStepAttributeString( id_step, "filename_Field" );
int nrFiles = rep.countNrStepAttributes( id_step, "file_name" );
allocate( nrFiles );
for ( int i = 0; i < nrFiles; i++ ) {
fileName[i] = rep.getStepAttributeString( id_step, i, "file_name" );
fileMask[i] = rep.getStepAttributeString( id_step, i, "file_mask" );
excludeFileMask[i] = rep.getStepAttributeString( id_step, i, "exclude_file_mask" );
fileRequired[i] = rep.getStepAttributeString( id_step, i, "file_required" );
if ( !YES.equalsIgnoreCase( fileRequired[i] ) ) {
fileRequired[i] = NO;
}
includeSubFolders[i] = rep.getStepAttributeString( id_step, i, "include_subfolders" );
if ( !YES.equalsIgnoreCase( includeSubFolders[i] ) ) {
includeSubFolders[i] = NO;
}
}
} catch ( Exception e ) {
throw new KettleException( BaseMessages.getString(
PKG, "GetFilesRowsCountMeta.Exception.ErrorReadingRepository" ), e );
}
}
public void saveRep( Repository rep, IMetaStore metaStore, ObjectId id_transformation, ObjectId id_step ) throws KettleException {
try {
rep.saveStepAttribute( id_transformation, id_step, "files_count", includeFilesCount );
rep.saveStepAttribute( id_transformation, id_step, "files_count_fieldname", filesCountFieldName );
rep.saveStepAttribute( id_transformation, id_step, "rows_count_fieldname", rowsCountFieldName );
rep.saveStepAttribute( id_transformation, id_step, "rowseparator_format", RowSeparator_format );
rep.saveStepAttribute( id_transformation, id_step, "row_separator", RowSeparator );
rep.saveStepAttribute( id_transformation, id_step, "isaddresult", isaddresult );
rep.saveStepAttribute( id_transformation, id_step, "smartCount", smartCount );
rep.saveStepAttribute( id_transformation, id_step, "filefield", filefield );
rep.saveStepAttribute( id_transformation, id_step, "filename_Field", outputFilenameField );
for ( int i = 0; i < fileName.length; i++ ) {
rep.saveStepAttribute( id_transformation, id_step, i, "file_name", fileName[i] );
rep.saveStepAttribute( id_transformation, id_step, i, "file_mask", fileMask[i] );
rep.saveStepAttribute( id_transformation, id_step, i, "exclude_file_mask", excludeFileMask[i] );
rep.saveStepAttribute( id_transformation, id_step, i, "file_required", fileRequired[i] );
rep.saveStepAttribute( id_transformation, id_step, i, "include_subfolders", includeSubFolders[i] );
}
} catch ( Exception e ) {
throw new KettleException( BaseMessages.getString(
PKG, "GetFilesRowsCountMeta.Exception.ErrorSavingToRepository", "" + id_step ), e );
}
}
public FileInputList getFiles( VariableSpace space ) {
return FileInputList.createFileList(
space, fileName, fileMask, excludeFileMask, fileRequired, includeSubFolderBoolean() );
}
private boolean[] includeSubFolderBoolean() {
int len = fileName.length;
boolean[] includeSubFolderBoolean = new boolean[len];
for ( int i = 0; i < len; i++ ) {
includeSubFolderBoolean[i] = YES.equalsIgnoreCase( includeSubFolders[i] );
}
return includeSubFolderBoolean;
}
public void check( List<CheckResultInterface> remarks, TransMeta transMeta, StepMeta stepMeta,
RowMetaInterface prev, String[] input, String[] output, RowMetaInterface info, VariableSpace space,
Repository repository, IMetaStore metaStore ) {
CheckResult cr;
// See if we get input...
if ( input.length > 0 ) {
cr =
new CheckResult( CheckResult.TYPE_RESULT_ERROR, BaseMessages.getString(
PKG, "GetFilesRowsCountMeta.CheckResult.NoInputExpected" ), stepMeta );
remarks.add( cr );
} else {
cr =
new CheckResult( CheckResult.TYPE_RESULT_OK, BaseMessages.getString(
PKG, "GetFilesRowsCountMeta.CheckResult.NoInput" ), stepMeta );
remarks.add( cr );
}
FileInputList fileInputList = getFiles( transMeta );
if ( fileInputList == null || fileInputList.getFiles().size() == 0 ) {
cr =
new CheckResult( CheckResult.TYPE_RESULT_ERROR, BaseMessages.getString(
PKG, "GetFilesRowsCountMeta.CheckResult.NoFiles" ), stepMeta );
remarks.add( cr );
} else {
cr =
new CheckResult( CheckResult.TYPE_RESULT_OK, BaseMessages.getString(
PKG, "GetFilesRowsCountMeta.CheckResult.FilesOk", "" + fileInputList.getFiles().size() ), stepMeta );
remarks.add( cr );
}
if ( ( RowSeparator_format.equals( "CUSTOM" ) ) && ( RowSeparator == null ) ) {
cr =
new CheckResult( CheckResult.TYPE_RESULT_ERROR, BaseMessages.getString(
PKG, "GetFilesRowsCountMeta.CheckResult.NoSeparator" ), stepMeta );
remarks.add( cr );
} else {
cr =
new CheckResult( CheckResult.TYPE_RESULT_OK, BaseMessages.getString(
PKG, "GetFilesRowsCountMeta.CheckResult.SeparatorOk" ), stepMeta );
remarks.add( cr );
}
}
public StepInterface getStep( StepMeta stepMeta, StepDataInterface stepDataInterface, int cnr, TransMeta tr,
Trans trans ) {
return new GetFilesRowsCount( stepMeta, stepDataInterface, cnr, tr, trans );
}
public StepDataInterface getStepData() {
return new GetFilesRowsCountData();
}
/**
* Since the exported transformation that runs this will reside in a ZIP file, we can't reference files relatively. So
* what this does is turn the name of files into absolute paths OR it simply includes the resource in the ZIP file.
* For now, we'll simply turn it into an absolute path and pray that the file is on a shared drive or something like
* that.
*
* @param space
* the variable space to use
* @param definitions
* @param resourceNamingInterface
* @param repository
* The repository to optionally load other resources from (to be converted to XML)
* @param metaStore
* the metaStore in which non-kettle metadata could reside.
*
* @return the filename of the exported resource
*/
public String exportResources( VariableSpace space, Map<String, ResourceDefinition> definitions,
ResourceNamingInterface resourceNamingInterface, Repository repository, IMetaStore metaStore ) throws KettleException {
try {
// The object that we're modifying here is a copy of the original!
// So let's change the filename from relative to absolute by grabbing the file object...
// In case the name of the file comes from previous steps, forget about this!
//
if ( !filefield ) {
for ( int i = 0; i < fileName.length; i++ ) {
FileObject fileObject = KettleVFS.getFileObject( space.environmentSubstitute( fileName[i] ), space );
fileName[i] = resourceNamingInterface.nameResource( fileObject, space, Utils.isEmpty( fileMask[i] ) );
}
}
return null;
} catch ( Exception e ) {
throw new KettleException( e );
}
}
}
| {
"content_hash": "86a9197f1b68846bb62816341387590e",
"timestamp": "",
"source": "github",
"line_count": 669,
"max_line_length": 134,
"avg_line_length": 34.60388639760837,
"alnum_prop": 0.6792656587473002,
"repo_name": "denisprotopopov/pentaho-kettle",
"id": "3fc9ca9fdd9388a43124ddf2ee385f9366cb3835",
"size": "24054",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "engine/src/org/pentaho/di/trans/steps/getfilesrowscount/GetFilesRowsCountMeta.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "14015"
},
{
"name": "CSS",
"bytes": "29902"
},
{
"name": "GAP",
"bytes": "4005"
},
{
"name": "HTML",
"bytes": "85844"
},
{
"name": "Java",
"bytes": "39265303"
},
{
"name": "JavaScript",
"bytes": "305747"
},
{
"name": "Shell",
"bytes": "18924"
},
{
"name": "XSLT",
"bytes": "5600"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.